Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
585 views
in Technique[技术] by (71.8m points)

tsql - Use set in a case statement in 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...