此sql正常工作:
DECLARE @check bit = 1
SELECT * FROM [TABLE]
WHERE [STATUS] = 1
AND [TYPE] =
CASE WHEN @check = 0 THEN 'typeA'
ELSE 'typeB'
END
但是当我尝试将表达式与'OR'一起使用时,出现错误:
DECLARE @check bit = 1
SELECT * FROM [TABLE]
WHERE [STATUS] = 1
AND [TYPE] =
CASE WHEN @check = 0 THEN 'typeA'
ELSE ('typeB' OR 'typeC')
END
例如,我希望有:
If(@check = 0) -> ... WHERE [Type] = sth OR sth
答案 0 :(得分:1)
这是您要完成的事情吗? (为提高可读性而扩展)
SELECT *
FROM [TABLE]
WHERE [STATUS] = 1
AND
(
(
@check = 0
AND [TYPE] = 'typeA'
)
OR
(
@check = 1
AND [TYPE] IN ('typeB', 'typeC')
)
)
答案 1 :(得分:1)
开关盒不能那样工作。如果没有其他过滤器提供解决方案,则ELSE子句基本上是默认值。 CASE只不过是一系列IF语句。因此,您基本上已经编写了以下内容:
if the value of @check is 0 then return 'typeA'
otherwise return ('typeB' OR 'typeC')
但是SQL如何返回多个值?您很可能应该像下面那样更改CASE语句。除了检查@check之外,您还应该检查具有多个选项的元素。下面的查询将返回@check为0时TYPE为typeA或typeB的记录。
DECLARE @check bit = 1
SELECT * FROM @table
WHERE [STATUS] = 1
AND CASE [TYPE] WHEN 'typeA' THEN 0 WHEN 'typeB' THEN 0 WHEN 'typeC' THEN 1 END = 0 AND @check = 0