Use set in a case statement in SQL Server

五迷三道 提交于 2021-02-02 09:56:25

问题


I would like to set a variable in SQL Server using a CASE statement. For example:

DECLARE @UNITY VARCHAR(5)
DECLARE @AUX VARCHAR(5)

CASE
    WHEN @UNITY = 'U1' THEN @AUX = 'M1'
    WHEN @UNITY = 'U2' THEN @AUX = 'M2'
    WHEN @UNITY = 'U3' THEN @AUX = 'M3'
END

回答1:


You can't use case as a flow control. An SQL case is an expression that return a scalar value based on condition(s).
It's well documented in the remarks section:

The CASE expression cannot 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).

A working code would be written like this:

DECLARE @UNITY VARCHAR(5)
DECLARE @AUX VARCHAR(5)

SET @AUX = 
CASE @UNITY
    WHEN 'U1' THEN 'M1'
    WHEN 'U2' THEN 'M2'
    WHEN 'U3' THEN 'M3'
END 

Note I'm using the Simple CASE expression syntax for brevity.



来源:https://stackoverflow.com/questions/57058281/use-set-in-a-case-statement-in-sql-server

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!