[英]Set more than one variable value in case statement in sql
declare @Month int
declare @A int
Declare @B int
Set @Month = 1
SELECT
CASE
WHEN @Month=1 THEN @A=11,@B=21
WHEN @Month=2 THEN @A=111,@B=211
ELSE @A=11,@B=13 END
我想根據SQL
中的條件設置多個變量。 怎么做。我這樣做時出錯。
您的CASE
表達式可能像
SELECT @A = CASE @Month WHEN 1 THEN 11
WHEN 2 THEN 111
ELSE 11 END,
@B= CASE @Month WHEN 1 THEN 21
WHEN 2 THEN 211
ELSE 13 END
您可以使用T-SQL 的 IF 語句:
IF @Month = 1
SET @A=11, @B=21
ELSE IF @Month = 2
SET @A=111, @B=211
ELSE
SET @A=11, @B=13
或者通常首選的顯式 scope:
IF @Month = 1
BEGIN
SET @A=11, @B=21
END
ELSE IF @Month = 2
BEGIN
SET @A=111, @B=211
END
ELSE
BEGIN
SET @A=11, @B=13
END
您可以使用派生表:
select @a = coalesce(max(a), 11),
@b = coalesce(max(b), 13)
from (values (1, 11, 21),
(2, 111, 211)
) v(month, a, b)
where month = @month;
我建議這樣做是因為在values()
語句中列出值似乎是列出所有值的一種簡潔方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.