Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tSQL CASE to control execution

I understand how to use a case statement to return different values:

SELECT CASE Color
         WHEN 'Blue' THEN 'Water'
         WHEN 'Black' THEN 'Oil'
         WHEN 'Red' THEN 'Blood'
       END
  FROM dbo.Liquid

Is there a way to use it to control flow instead of IF-ELSE, i.e.

DECLARE @Color varchar()
SELECT @Color = Color FROM dbo.Liquid WHERE ID = @MyID

CASE (@Color)
  WHEN 'Blue' THEN SELECT 'Water'
  WHEN 'Black' THEN SELECT 'Oil'
  WHEN 'Red' THEN PRINT 'HELP! I''m bleeding!'
END
like image 920
Brad Avatar asked Jan 23 '23 20:01

Brad


1 Answers

No, the CASE expression can not be used to control the flow of execution of Transact-SQL statements, statement blocks, user-defined functions, and stored procedures.

For a list of control-of-flow methods, see Control-of-Flow Language (Transact-SQL).

like image 131
OMG Ponies Avatar answered Jan 25 '23 10:01

OMG Ponies