Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Monday, May 16, 2011

Setting up SQL Server 2008 Express with Profiler

http://blog.tonysneed.com/2010/08/05/setting-up-sql-server-2008-express-with-profiler/

If SQL Express has already been installed, it picks up newly installed tools automatically, no need to re-install it.

Thursday, October 7, 2010

TSQL quirks

I was always sure that len in TSQL is "length",
but NOT: it is "length without trailing spaces":

select len('12345     ') returns 5

It took a while to find what I really need: 
select DATALENGTH('12345     'returns 10

Friday, October 1, 2010

LINQ2Obj vs TSQL: GROUP BY and SUM

I tried to use Dynamic LINQ to create pretty ordinary TSQL query:
SELECT COL1 as B1, COL2 as B2, SUM(CONVERT(Money, COL3)) as B3
FROM a-table
GROUP BY COL1, COL2
HAVING(COL1 < 40)
a-table:
COL1  COL2  COL3
11    "12"  "13"
11    "12"  "23"
31    "32"  "33"
31    "32"  NULL
41    "42"  "43"

Expected result:
B1  B2   B3
11  "12" 36
31  "32" 33

It took me quite a long time to figure out how to create such a query in LINQ using a List of objects as source.
Here is first result of my struggles:
using System.Linq.Dynamic;
. . .

var res =
  list.AsQueryable().Where("COL1<40", null)
    .GroupBy("new(COL1 as B1,COL2 as B2)", "it")
    .Select("new(Key, Sum(COL3==null?0:double.Parse(COL3)) as B3)", null);

The "res" gives two records:
[0]    {Key={B1=11, B2=12}, B3=36}
[1]    {Key={B1=31, B2=32}, B3=33}

Then I need to "flatten" this result to produce what I really needed (but this is another task, not shown here)
[0]    {B1=11, B2=12, B3=36}
[1]    {B1=31, B2=32, B3=33}

Please let me know if anyone has a better solution.

Tuesday, August 10, 2010

LINQ and TSQL behavior difference

I found a lot, but for now record only this one.
When I say "LINQ" I mean LINQ-To-Object, not LINQ-To_Sql.
It took me quite a while to figure out why SQL request produces more records than LINQ request to preliminary loaded same data.
SQL:
SELECT aaa, bbb FROM TABLE WHERE bbb='xxx'; // returns 14 records
LINQ: I preloaded the whole TABLE into list, then query it:
var records = list.AsQueryable()
.Where("bbb==\"xxx\"", null)
.Select("new (aaa, bbb)", null); // returns 12 records

After all I found out that database contains 2 records with bbb='xxx     ' (spaces at the end)
TSQL ignores spaces, LINQ - does not, thus producing 2 less records.

Monday, December 7, 2009

Find all the foreign keys in a database

Get info on structure of all tables

SELECT * FROM INFORMATION_SCHEMA.COLUMNS
order by table_name, ordinal_position