在 SQL Server 的 case 语句中使用 set [英] Use set in a case statement in SQL Server

查看:52
本文介绍了在 SQL Server 的 case 语句中使用 set的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 CASE 语句在 SQL Server 中设置一个变量.例如:

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

推荐答案

您不能使用 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.

这篇关于在 SQL Server 的 case 语句中使用 set的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆