The (still online) documentation for MS SQL Server 2005 states that BEGIN...END blocks can be used within CASE when it needs to execute a sequence of statements:
The BEGIN and END statements are used when [...] An element of a CASE function needs to include a block of statements.
...I'm unsure why it says that because CASE defines an expression which always yields a scalar value (including NULL) when evaluated; but BEGIN...END represents statements which do not yield a single value when evaluated.
...unless BEGIN...END could be used as a block preceding any value-yielding expression, but I couldn't find any mention of this in MSSQL 2005's documentation for CASE.
I no-longer maintain a SQL 2005 box in my homelab, my oldest is SQL Server 2016; and I tried a variety of possible T-SQL scripts that nested a BEGIN...END block within CASE within a SELECT but they all result in syntax errors complaining "Incorrect syntax near 'BEGIN'":
- With or without semicolons.
- With both types of
CASE(CASE @x WHEN 1 THEN 2 ELSE 3 ENDandCASE WHEN @x = 1 THEN 2 ELSE 3 END). - Using
BEGIN...ENDfor theWHENclause. - Using
BEGIN...ENDfor theTHENandELSEclauses - including whenTHENis elided. - I also tried it in a
SETstatement (outside of a query), e.g.:SET @var = CASE WHEN ... END.
For example:
USE AdventureWorks;
SELECT
c.*,
CASE c.CultureID
WHEN 'en' THEN 1
WHEN 'es' THEN
BEGIN
DECLARE @y int = 2
THEN @y
END
ELSE 3
END AS caseWhen
FROM
Production.Culture AS c;
If this really was never supported by SQL Server 2005 then was this perhaps a planned-feature which was documented before it was cancelled? It could also be the case (pun-unintended) that the technical-writer for this article was mistaken ( perhaps conflating the END in CASE END?); I'm just surprised that such a documentation error made it into the final release of SQL Server 2005 and still remains uncorrected for 20 years.
Because everyone is telling me to "just swallow your pride and try using AI more and you'll see that it really will save you time!" so I asked ChatGPT (free tier, if it matters) and it immediately confabulated nonsense about "the rarely used T-SQL CASE control-of-flow statement, which behaves similarly to IF…ELSE and allows BEGIN…END." - smh
CASEitself in those docs gives no impression thatBEGIN ... ENDis supportedsqlbol.chm(from 1998) under Accessing and Changing Data > Accessing and Changing Data Fundamentals > Using Multiple Statements > Control-of-Flow > Using BEGIN...END - though the T-SQL Language Reference article (in the same*.chm) onBEGINandCASEmakes no mention of this supposed functionality (though interestingly I do see "CASE" referred to as a "function" and not as an expression). This is all quite strange.IIFandCHOOSEfunctions - though they are just syntax sugar for some usages ofCASE