我有以下查询:
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'.
我怎样才能让它发挥作用?如果参数为“活动”,则返回具有以下条件的记录?
答案 0 :(得分: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 :(得分: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
答案 2 :(得分:1)
为什么不添加OR条件?像
SELECT... WHERE ...
AND ((@ActiveInactive = 'Active' AND o.[orderactivedate] > o.[orderinactivedate]) OR
(@ActiveInactive = 'Inactive' AND o.[orderactivedate] < o.[orderinactivedate]))
答案 3 :(得分:1)
您不能在CASE中使用比较表达式
我会考虑将此比较更改为正常表达式
...
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