【问题标题】:Set more than one variable value in case statement in sql在sql中的case语句中设置多个变量值
【发布时间】:2019-10-03 09:11:34
【问题描述】:
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 中的条件设置多个变量。 怎么做。我这样做时出错了。

【问题讨论】:

标签: sql asp.net


【解决方案1】:

你的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

【讨论】:

    【解决方案2】:

    你可以使用T-SQL's IF statement:

    IF @Month = 1 
        SET @A=11, @B=21
    ELSE IF @Month = 2
        SET @A=111, @B=211
    ELSE
        SET @A=11, @B=13
    

    或通常首选的显式范围:

    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
    

    【讨论】:

      【解决方案3】:

      您可以使用派生表:

      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() 语句中列出值似乎是列出所有值的一种简洁方式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-19
        • 1970-01-01
        • 2014-11-10
        相关资源
        最近更新 更多