2015-10-15 80 views
2

我知道一個如果條件可以使用CASE語句來實現:如何在SQL Server的視圖中使用else-if條件?

CASE 
    WHEN <condition> 
     x 
    ELSE 
     z 
END 

,但如何做到這一點對於其他,如果條件?

像這樣(僞代碼):

CASE 
    WHEN <condition> 
     x 
    ELSE-IF <condition> 
     y 
    ELSE 
     z 
END 

我截至目前代碼:

CREATE VIEW [dbo].[v_myview1] 
AS 
    SELECT 
     ci.aDate, ci.Currency, ci.lim, ci.LimitUS, 
     pa.Date as AmtDate, 
     pa.Payment as AmtPayment, 
     CASE 
      WHEN (ci.aDate - pa.Date) < 0 THEN ci.LimitUS 
      --ELSE IF 
      --WHEN (ci.lim - pa.Payment) < 0 THEN 'a' 
      ELSE 'b' 
     END AS Estimate, 
    FROM 
     dbo.Amt pa 
    JOIN 
     dbo.CrInfo ci ON ci.pr_key = pa.pr_key 
    JOIN 
     dbo.rates tr ON rt.Currency = ci.Currency 
    WHERE 
     ci.mk = 2 

回答

7

您可以使用第二種情況是這樣的:

CASE 
WHEN (ci.aDate - pa.Date) < 0 THEN ci.LimitUS 
WHEN (ci.lim - pa.Payment) < 0 THEN 'a' 
ELSE 'b' 
+1

由於拉胡爾有指出,case語句不會在T-SQL中級聯,並且語句將在匹配的第一個子句上終止。即所有'WHEN'語句都等同於'ELSE IF' – Wibbler