使用CASE表达式设置变量

时间:2012-06-28 20:59:50

标签: sql-server tsql

我的查询如下:

SELECT  LossCost, CoverageID                
FROM BGILossCost] 
WHERE CoverageID IN (1, 2) AND
      StateID = @StateID AND
      ConstructionID = @ConstructionID AND
      PropertyClassCodeID = @PropertyClassCodeID AND
      (BGIDistrictID = @BGIDistrictID OR BGIDistrictID IS NULL)           

并返回以下数据,这是正确的:

LossCost                                CoverageID
--------------------------------------- -----------
0.012                                   1
0.034                                   2

但我想要做的是设置两个变量,具体取决于CoverageID

的值

这是pseudeo代码:

SELECT  @Var1 = CASE CoverageID = 1 THEN LossCost END,
  @Var2 = CASE CoverageID = 2 THEN LossCost END             
FROM BGILossCost] 
WHERE CoverageID IN (1, 2) AND
      StateID = @StateID AND
      ConstructionID = @ConstructionID AND
      PropertyClassCodeID = @PropertyClassCodeID AND
      (BGIDistrictID = @BGIDistrictID OR BGIDistrictID IS NULL) 

我总是可以在下面做,但我希望由于性能原因,我不必两次加入同一张桌子

SELECT  @Var1 = LossCost                    
FROM BGILossCost] 
WHERE CoverageID = 1 AND
      StateID = @StateID AND
      ConstructionID = @ConstructionID AND
      PropertyClassCodeID = @PropertyClassCodeID AND
      (BGIDistrictID = @BGIDistrictID OR BGIDistrictID IS NULL) 

SELECT  @Var2 = LossCost                    
FROM BGILossCost] 
WHERE CoverageID = 2 AND
      StateID = @StateID AND
      ConstructionID = @ConstructionID AND
      PropertyClassCodeID = @PropertyClassCodeID AND
      (BGIDistrictID = @BGIDistrictID OR BGIDistrictID IS NULL) 

任何建议都会有所帮助。

1 个答案:

答案 0 :(得分:2)

你非常接近,这不起作用:

SELECT
  @Var1 = MAX(CASE WHEN CoverageID = 1 THEN LossCost END),
  @Var2 = MAX(CASE WHEN CoverageID = 2 THEN LossCost END)  
FROM BGILossCost
WHERE CoverageID IN (1, 2) AND
      StateID = @StateID AND
      ConstructionID = @ConstructionID AND
      PropertyClassCodeID = @PropertyClassCodeID AND
      (BGIDistrictID = @BGIDistrictID OR BGIDistrictID IS NULL);