Wednesday, March 2, 2011

Case statement in LINQ

(from c in Contents
orderby c.ContentId descending
select new { ContentId = c.ContentId, 
         RandomKey = (
             c.ContentRandomKey < 1000 ? "less than 1000" :
         c.ContentRandomKey < 1000 ? "greater than 1000" : "Unknown"
                     )
           }
).Take(100)

This is the generated SQL Statement:

SELECT TOP (100) [t1].[ContentId], [t1].[value] AS [RandomKey]
FROM (
    SELECT [t0].[ContentId], 
        (CASE 
            WHEN [t0].[ContentRandomKey] < 1000 THEN 'less than 1000'
            WHEN [t0].[ContentRandomKey] < 1000 THEN 'greater than 1000'
            ELSE 'Unknown'
         END) AS [value]
    FROM [Content] AS [t0]
    ) AS [t1]
ORDER BY [t1].[ContentId] DESC

Attention:
I think it is always better to use searched case expression. ( CASE WHEN ....)
CASE
WHEN x>0 THEN 1
WHEN x<0 -1
WHEN x IS NULL THEN -2
ELSE 0
END

Because if we use simple case, then we have problem with NULL.
CASE x
WHEN NULL THEN -1
WHEN 1 THEN 1
WHEN 2 THEN 2
ELSE 3 END

(Wrong result, x = NULL does not work, we should use IS NULL)

0 comments:

Post a Comment