我正在尝试创建以下WHERE子句:
AND CASE @SomePRarmeter
WHEN 'this' THEN
user_id IN (SELECT * FROM dbo.func_Id1(@User))
WHEN 'that' THEN
user_id IN (SELECT user_id from dbo.func_Ids2(@OrgsForReporter)
END
但是我收到一个错误:关键字“IN”附近的语法不正确(在第一个条件中),尽管这两个条件都有效。使这样的陈述有效的正确方法是什么?
谢谢!
答案 0 :(得分:11)
尝试
AND (
(@SomePRarmeter = 'this' AND user_id IN (SELECT * FROM dbo.func_Id1(@User)))
OR
(@SomePRarmeter = 'that' AND user_id IN user_id IN (SELECT user_id from dbo.func_Ids2(@OrgsForReporter)))
)
答案 1 :(得分:2)
您正在子查询中执行select *。您只需要返回一列:
(SELECT * FROM dbo.func_Id1(@User))
到此:
(SELECT YOUR_USER_ID_COLUMN FROM dbo.func_Id1(@User))
答案 2 :(得分:1)
case语句必须产生值,而不是表达式。所以这不起作用:
select case when 1=1 then 1 in (1,2,3) end
但这会奏效;
select case when 1=1 then 1 end
该值可以是子查询的结果。因此,一种解决方案是重写where
子句,如:
CASE @SomePRarmeter
WHEN 'this' THEN
(SELECT count() FROM dbo.func_Id1(@User) f where f.user_id = t.user_id))
WHEN 'that' THEN
(SELECT count() from dbo.func_Ids2(@OrgsForReporter) f where f.user_id = t.user_id))
END > 1
现在返回匹配行数。然后,您可以使用case ... end > 1
进行过滤。
答案 3 :(得分:0)
我打破了这个:
IF 'this'
SELECT
...
WHERE user_id IN (SELECT * FROM dbo.func_Id1(@User))
ELSE IF 'that'
SELECT
...
WHERE user_id IN (SELECT user_id from dbo.func_Ids2(@OrgsForReporter))
答案 4 :(得分:0)
CASE ... END
返回一个表达式,而不是一段文字SQL代码。而不是:
AND CASE foo WHEN bar THEN bla=ble END -- Wrong
...你必须使用它:
AND bla = CASE foo WHEN bar THEN ble END -- Right
在你的情况下,你可以在这一行上做点什么:
-- Untested
AND (
(@SomePRarmeter='this' AND user_id IN (SELECT * FROM dbo.func_Id1(@User)))
OR (@SomePRarmeter='that' AND user_id IN (SELECT user_id from bo.func_Ids2(@OrgsForReporter))
)