2015-11-13 93 views
-1

我需要根據訪問天數從表中提取記錄。如何通過更正下面的查詢來實現這一點?它有語法錯誤(s)。我知道這個語法是不正確的,但它會讓你知道我想達到什麼。有多個條件的案例陳述

DECLARE @PatientByDate INT 
SET @PatientByDate = 30 
    SELECT * FROM Visits 
    WHERE 
    CASE 
      WHEN(@PatientByDate = 90) then DaysVisited > 90 
      WHEN(@PatientByDate = 60) then DaysVisited >= 60 AND DaysVisited < 90 
      WHEN(@PatientByDate = 30) then DaysVisited >= 30 AND DaysVisited < 60 
      WHEN(@PatientByDate = 25) then DaysVisited < 30 
      WHEN(@PatientByDate = 0) then -500 AND <= 5000000 
     END 
+0

檢查http://stackoverflow.com/questions/24254164/sql-case-when-and – MusicLovingIndianGirl

+2

'CASE'是**不是**聲明 - 它是一個**表達式**(它可以返回各種可能之一值)。你**不能**從「CASE」返回「代碼塊」或條件 - 只有一個原子值。 –

回答

3

做它直接與or結合斷言:

SELECT * FROM Visits 
WHERE 
    (@PatientByDate = 90 and DaysVisited > 90) or 
    (@PatientByDate = 60 and DaysVisited >= 60 and DaysVisited < 90) or 
    (@PatientByDate = 30 and DaysVisited >= 30 and DaysVisited < 60) or 
    (@PatientByDate = 25 and DaysVisited < 30) or 
    (@PatientByDate in(0, -500)) 
0

你必須將它們都移動到條款和與之相匹配的返回值(= 1):

DECLARE @PatientByDate INT 
SET @PatientByDate = 30 
SELECT * FROM Visits 
WHERE 1 = CASE 
    WHEN(@PatientByDate = 90) AND DaysVisited > 90 then 1 
    WHEN(@PatientByDate = 60) AND DaysVisited >= 60 AND DaysVisited < 90 then 1 
    WHEN(@PatientByDate = 30) AND DaysVisited >= 30 AND DaysVisited < 60 then 1 
    WHEN(@PatientByDate = 25) AND DaysVisited < 30 then 1 
    WHEN(@PatientByDate = 0) AND -500 AND <= 5000000 then 1 
END 

或簡單地做:

DECLARE @PatientByDate INT 
SET @PatientByDate = 30 
SELECT * FROM Visits 
WHERE 
    ((@PatientByDate = 90) AND DaysVisited > 90) OR 
    ((@PatientByDate = 60) AND DaysVisited >= 60 AND DaysVisited < 90) OR 
    ((@PatientByDate = 30) AND DaysVisited >= 30 AND DaysVisited < 60) OR 
    ((@PatientByDate = 25) AND DaysVisited < 30) OR 
    ((@PatientByDate = 0) AND -500 AND <= 5000000)