使用单个SELECT语句和CASE将表值分配给多个变量?

时间:2010-03-26 16:27:51

标签: sql-server-2005 tsql case

我正在尝试使用具有多个CASE语句的单个SELECT将查找表中包含的值分配给多个变量。

该表是一个包含两列的查找表,如下所示:

[GreekAlphabetastic]

  SystemID    Descriptor
  --------    ----------
  1           Alpha
  2           Beta
  3           Epsilon

这是我的语法:

SELECT 

    @VariableTheFirst = 
        CASE
            WHEN myField = 'Alpha' THEN tbl.SystemID
        END,

    @VariableTheSecond = 
        CASE
            WHEN myField = 'Beta' THEN tbl.SystemID
        END,

    @VariableTheThird = 
        CASE
            WHEN myField = 'Epsilon' THEN tbl.SystemID
        END

FROM GreekAlphabetastic tbl

但是,当我在执行此语句后检查变量时,我希望为每个变量分配适当的值,但只有 last 指定了值。

SELECT 
    @VariableTheFirst AS First, 
    @VariableTheSecond AS Second, 
    @VariableTheThird AS Third

Results:

    First    Second    Third
    NULL     NULL      3

我做错了什么?

3 个答案:

答案 0 :(得分:3)

从SELECT中分配局部变量时,只处理的最后一行会影响变量。对于第三行,CASE myField = 'Alpha'CASE myField = 'Beta'为false,变量设置为NULL。 CASE myField = 'Epsilon'为真,@ VariableTheThird为3。

如果你想让它起作用:

SELECT @VariableTheFirst = tbl.SystemID WHERE myField = 'Alpha'
SELECT @VariableTheSecond = tbl.SystemID WHERE myField = 'Beta'
SELECT @VariableTheThird = tbl.SystemID WHERE myField = 'Epsilon'

答案 1 :(得分:2)

分配后,前2个变量将重置为null。即当它达到Epsilon记录时,前两个变量被赋值为null,因为在CASE语句中没有任何东西可以阻止它。

所以,试试这个:

SELECT     
    @VariableTheFirst = 
        CASE
            WHEN Descriptor = 'Alpha' THEN tbl.SystemID
            ELSE @VariableTheFirst
        END,

    @VariableTheSecond = 
        CASE
            WHEN Descriptor = 'Beta' THEN tbl.SystemID
            ELSE @VariableTheSecond
        END,

    @VariableTheThird = 
        CASE
            WHEN Descriptor = 'Epsilon' THEN tbl.SystemID
            ELSE @VariableTheThird
        END
FROM GreekAlphabetastic tbl

答案 2 :(得分:0)

SELECT     
        CASE
            WHEN Descriptor = 'Alpha' THEN @VariableTheFirst = isnull(@VariableTheFirst,tbl.SystemID)
            WHEN Descriptor = 'Beta' THEN @VariableTheSecond = isnull(@VariableTheSecond,tbl.SystemID)
            WHEN Descriptor = 'Epsilon' THEN @VariableTheThird = isnull(@VariableTheThird,tbl.SystemID)
        END
FROM GreekAlphabetastic tbl