开发者

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-EL开发者_如何学PythonSE, 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


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).


No, you'd need to use an IF statement for that logic since in a CASE statement you're basically returning a value. You could do something like this:

declare @result varchar(500)

SET @result =
CASE
  WHEN @Color = 'Blue' THEN 'Water'
  WHEN @Color = 'Black' THEN 'Oil'
  WHEN @Color = 'Red' THEN 'HELP! I''m bleeding'
END

IF @Color = 'Red'
  PRINT @result

But I think that's about the best you could do. Personally, I'd just use an IF statement here since that's the best choice.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜