且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 SQL Server 的 case 语句中使用 set

更新时间:2021-06-30 16:25:27

您不能使用 case 作为流量控制.SQL case 是根据条件返回标量值的表达式.
它在 备注部分:

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:

CASE 表达式不能用于控制 Transact-SQL 语句、语句块、用户定义函数和存储过程的执行流程.有关流控制方法的列表,请参阅 控制流语言 (Transact-SQL).

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 

请注意,为了简洁起见,我使用的是 Simple CASE 表达式语法.

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