question

n3w2sql avatar image
n3w2sql asked

case with field names

I am trying to find out the logic for using the case function with field names, I have 2 fields [LossesFrom],[RisksFrom] and I am trying to return the result in 1 column, Where one column is null the other has a date so I am trying to have just the one column with the a list of dates, this is my code CASE WHEN [LossesFrom] = NULL THEN [RISKSFROM] ELSE [LossesFrom] END AS [DATE]
sql-server-2008
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Kev Riley avatar image
Kev Riley answered
You can do this with a CASE, but also with a [COALESCE()][1] COALESCE(LossesFrom, RisksFrom) or even a [ISNULL()][2], as there are only 2 options ISNULL(LossesFrom, RisksFrom) [1]: http://msdn.microsoft.com/en-us/library/ms190349.aspx [2]: http://msdn.microsoft.com/en-us/library/ms184325.aspx
1 comment
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

ThomasRushton avatar image ThomasRushton ♦♦ commented ·
And you can have the +1 for providing the alternatives... :-)
0 Likes 0 ·
ThomasRushton avatar image
ThomasRushton answered
You've pretty much cracked it. SELECT CASE WHEN [LossesFrom] IS NULL THEN [RisksFrom] ELSE [LossesFrom] END AS [Date] FROM ... Note: it's "IS NULL", not "= NULL".
1 comment
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Usman Butt avatar image Usman Butt commented ·
+1 for beating me and to keep you on the top ;)
1 Like 1 ·
Usman Butt avatar image
Usman Butt answered
You cannot compare NULL like that. Use CASE WHEN [LossesFrom] IS NULL THEN [RISKSFROM] ELSE [LossesFrom] END AS [DATE]
5 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Usman Butt avatar image Usman Butt commented ·
hahaha...yap :) But Kev Riley beat us both on votes ;)
3 Likes 3 ·
ThomasRushton avatar image ThomasRushton ♦♦ commented ·
Oh, bad luck. 3 seconds too slow... ;-)
0 Likes 0 ·
Usman Butt avatar image Usman Butt commented ·
Spoke too soon ;)
0 Likes 0 ·
ThomasRushton avatar image ThomasRushton ♦♦ commented ·
You mean you didn't vote for @Kev Riley's answer?
0 Likes 0 ·
Usman Butt avatar image Usman Butt commented ·
I did it now. Although it took me to the bottom ;)
0 Likes 0 ·
n3w2sql avatar image
n3w2sql answered
Thank you for this, I think your help will help many others users.:)
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.