Denny.NET

I can haz ASP.NET goodness?

About the author

Denny Ferrassoli
Developer at Casting Networks. MCP / .NET
E-mail me Send mail
Add to Technorati Favorites

Recent comments

Authors

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008

Generating a Case Statement in LINQ to SQL

LINQ is so much fun and makes things so much easier to accomplish. It's also gaining quite a bit of acceptance and it's evolving too with things like: LINQ to JavaScript and LINQ to JSON. I've been playing with LINQ quite a bit and recently I needed to generate a CASE statement with LINQ to SQL. It was fairly easy to accomplish since LINQ is so darn cool! Here is what I came up with:

[code:c#]
var gimmeh_gimmeh =
 from t in db.sc_Timeslots
 where (t.starttime.Minute % 5 == 0) || (t.starttime.Minute % 10 == 0)
 select new
 {
  t.id,
  t.starttime,
  interval = (t.starttime.Minute % 5 == 0) ? "5 Minutes" : "10 Minutes"
 };
[/code]

The line: "interval = ..." generates a CASE statement as shown below.

[code:tsql]
SELECT [t0].[id], [t0].[starttime],
    (CASE
        WHEN (DATEPART(Minute, [t0].[starttime]) % @p4) = @p5 THEN CONVERT(NVarChar(10),@p6)
        ELSE @p7
     END) AS [interval]
FROM [dbo].[sc_Timeslot] AS [t0]
WHERE ((DATEPART(Minute, [t0].[starttime]) % @p0) = @p1) OR ((DATEPART(Minute, [t0].[starttime]) % @p2) = @p3)
[/code]

You can have multiple CASE statements or even concat them like so:

[code:c#]
  interval = ((t.starttime.Minute % 5 == 0) ? "5 Minutes" : "10 Minutes") + ((t.id == 1) ? " (Master ID)" : "")
[/code]

Which will generate the Case statement below (hey I'm starting to rhyme):

[code:tsql]
    (CASE
        WHEN (DATEPART(Minute, [t0].[starttime]) % @p4) = @p5 THEN CONVERT(NVarChar(22),@p6)
        ELSE @p7 + (
            (CASE
                WHEN [t0].[id] = @p8 THEN @p9
                ELSE CONVERT(NVarChar(12),@p10)
             END))
     END) AS [interval]
[/code]

You can also nest the CASE statements... but I think by now you're clever enough to figure that out on your own.

Enjoy!

kick it on DotNetKicks.com
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,
Categories: ASP.NET | Server-Side
Posted by Denny on Friday, February 08, 2008 10:04 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Related posts

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

Monday, May 12, 2008 3:36 AM