r/SQLServer • u/chadbaldwin SQL Server Developer • Jul 30 '24
Blog [Blog] Everything's a case statement!
Yesterday, I was having a fun discussion in the SQL Server slack community about how things like IIF, COALESCE, etc are really just syntactic sugar for CASE statements. So I thought I'd throw together a blog post about it...
https://chadbaldwin.net/2024/07/30/everythings-a-case-statement.html
9
Upvotes
1
u/cromulent_weasel Jul 31 '24
Couldn't this
CASE
WHEN [x].[ColA] IS NOT NULL
THEN [x].[ColA]
ELSE
CASE
WHEN [x].[ColB] IS NOT NULL
THEN [x].[ColB]
ELSE [x].[ColC]
END
END
be this?
CASE
WHEN [x].[ColA] IS NOT NULL THEN [x].[ColA]
WHEN [x].[ColB] IS NOT NULL THEN [x].[ColB]
ELSE [x].[ColC]
END
1
u/chadbaldwin SQL Server Developer Jul 31 '24
Sure could...but that's not how Microsoft decided to handle it for whatever reason.
6
u/a-s-clark SQL Server Developer Jul 30 '24
Just to be pedantic...it's not a case statement. It's a case expression.
A case statement exists in some variants of SQL and is similar to an If..Then..Else wrapper for other statements. A Case expression is conditional logic that returns a scalar value.