2011-05-09 156 views
3

我有以下查詢:where子句中的SQL Case語句指定條件?

SELECT * 
FROM dbo.tblOrders o 
WHERE o.OrderId IN (SELECT [Value] FROM [dbo].[udf_GenerateVarcharTableFromStringList](@OrderId, ',')) 
AND 
@ActiveInactive = 
CASE 
WHEN 'Active' THEN (o.[orderactivedate] > o.[orderinactivedate]) 
WHEN 'Inactive' THEN (o.[orderactivedate] < o.[orderinactivedate]) 
END 

這將返回

An expression of non-boolean type specified in a context where a condition is expected, near 'THEN'. 

我將如何得到這個工作?說如果該參數是'活動',然後按照以下標準返回記錄?

+2

作爲旁白...您需要關閉那個'Active'然後聲明的parens。 – DKnight 2011-05-09 15:54:35

+0

添加了關閉的零部件 – davmos 2014-02-26 07:39:33

回答

7

你可以做的另一種方法:

SELECT * 
FROM dbo.tblOrders o 
WHERE o.OrderId IN (SELECT [Value] FROM [dbo].[udf_GenerateVarcharTableFromStringList](@OrderId, ',')) 
AND ((@ActiveInactive = 'Active' AND o.[orderactivedate] > o.[orderinactivedate]) 
OR (@ActiveInactive = 'Inactive' AND o.[orderactivedate] < o.[orderinactivedate])) 
1

你爲什麼不添加OR條件?像

SELECT... WHERE ... 
AND ((@ActiveInactive = 'Active' AND o.[orderactivedate] > o.[orderinactivedate]) OR 
    (@ActiveInactive = 'Inactive' AND o.[orderactivedate] < o.[orderinactivedate])) 
1

你不能有一個比較表達式在這樣的

一個情況下,我會考慮這個選項,比較更改爲正常表達

... 
AND 
CASE @ActiveInactive 
WHEN 'Active' THEN DATEDIFF(day, o.[orderinactivedate], o.[orderactivedate]) 
WHEN 'Inactive' THEN DATEDIFF(day, o.[orderactivedate], o.[orderinactivedate]) 
END > 0 

或者這一點,您可以在SIGN()表達有一個計算列

SIGN(DATEDIFF(day, o.[orderinactivedate], o.[orderactivedate])) = 
       CASE WHEN @ActiveInactive WHEN 'Active' THEN 1 WHEN 'InActive' THEN -1 END 
2
SELECT * 
FROM dbo.tblOrders o 
WHERE o.OrderId IN (SELECT [Value] FROM [dbo].[udf_GenerateVarcharTableFromStringList](@OrderId, ',')) 
AND 
@ActiveInactive = 
CASE 
WHEN (o.[orderactivedate] > o.[orderinactivedate]) then 'Active' 
WHEN (o.[orderactivedate] < o.[orderinactivedate]) THEN 'Inactive' 
END 
+0

請使用大括號按鈕來格式化代碼{}。否則,好想法 – gbn 2011-05-09 16:06:55