2010-03-26 76 views
0

我想通過使用具有多個CASE語句的單個SELECT將查找表中包含的值分配給多個變量。使用單個SELECT語句和CASE將表值賦給多個變量?

該表有兩列像這樣的查詢表:

[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 

然而,當我檢查變量,這個語句的執行,我希望每個被賦予適當的值,但是隻有最後的具有分配的值。

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

Results: 

    First Second Third 
    NULL  NULL  3 

我在做什麼錯?

回答

2

第2個變量被重置的安排,爲空。即當它碰到Epsilon記錄時,前2個變量被分配爲空,因爲在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 
+1

這個工作,但如果表是大三從使用WHERE(和索引)會更快。 – 2010-03-26 16:47:18

+0

@AdaTheDev:謝謝,我現在明白出了什麼問題! :) @KM:幸運的是,這只是一張只有少量記錄的查找表,不管怎樣,它在不久的將來都不會添加更多的附加記錄。 – 2010-03-26 18:04:37

3

當從SELECT中分配局部變量時,只有最後一行處理會影響變量。對於第三行,CASE myField = 'Alpha'CASE myField = 'Beta'是錯誤的,變量設置爲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' 
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 
+2

THEN後不允許使用語句(如賦值語句),只允許使用表達式。 – DyingCactus 2010-03-26 17:03:51

相關問題