简体   繁体   English

在 where 子句的 case 语句中使用子查询

[英]Using a subquery in a case statement in a where clause

I want to select different results (from a temp table) based on what a certain parameter is set to in the query.我想根据查询中设置的某个参数来 select 不同的结果(来自临时表)。 I want to exclude certain inventory SKUs if a particular warehouse is selected.如果选择了特定仓库,我想排除某些库存 SKU。 I am getting this error, unfortunately.不幸的是,我收到了这个错误。

Msg 512, Level 16, State 1, Line 310 Subquery returned more than 1 value.消息 512,级别 16,State 1,第 310 行子查询返回超过 1 个值。 This is not permitted when the subquery follows =, ,=, <, <=, >.当子查询跟随 =, ,=, <, <=, > 时,这是不允许的。 >= or when the subquery is used as an expression. >= 或当子查询用作表达式时。

Here is a simplified temp table I am selecting from for example...这是我从中选择的简化临时表,例如...

InvtID邀请ID
C-123 C-123
C-789 C-789
C-20042 C-20042
12345 12345
56789 56789
35353 35353
declare @siteid VARCHAR(10) = 'CF'

select *
from #temptable
where InvtID in (Case when @siteid='CF' then (
                                                select I.InvtID
                                                from dbo.Inventory I
                                                where I.InvtID not like 'C-%'
                                                union all
                                                select 'C-20042')
                        else (select I.InvtID from dbo.Inventory I) end)

expected result预期结果

InvtID邀请ID
C-20042 C-20042
12345 12345
56789 56789
35353 35353

Is there a better way to accomplish my task, or is there a way to fix my current attempted solution?有没有更好的方法来完成我的任务,或者有没有办法修复我当前尝试的解决方案?

select *
from #temptable FT
where (@siteid='CF' and (FT.InvtID not like 'C-%' or FT.InvtID='C-20042'))
or @siteid<>'CF'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM