有没有办法在IN()语句中嵌套CASE-WHEN语句,以便其中一个WHEN或ELSE返回一个子查询。对我来说,这不应该是一个问题,但不知何故我得到错误:
“子查询返回的值超过1。”
IN()
应该处理多个值!
以下是重现错误的一个小例子:
-- tblA will be searched for values
Declare @tblA table (i int)
insert @tblA
select 1
union select 2
union select 3
--tblB: its values will be searched in tblA
Declare @tblB table (i int)
insert @tblB
select 2
union select 3
union select 1
--@c used by the CASE statement to match
declare @c varchar(50)
set @c = 'Match'
select *
from @tblA
where i IN ( -- IN statement should accept subquery in it
case @c
when 'Dont Match' then 2 --If it had matched, then the single value 2 would have been returned and TSQL would be happy
else (
select i from @tblB --TSQL not happy and causing error when more than one values returned from the subquery
)
end
)
答案 0 :(得分:2)
尝试
select *
from @tblA A
WHERE (@c = 'Dont Match' AND i = 2) OR
(@c <> 'Dont Match' AND EXISTS (SELECT * FROM @tblB WHERE i = A.i)
答案 1 :(得分:1)
您的问题不在于IN子句,而在于CASE。
CASE无法处理多个值。
的有效强>
DECLARE @TBLA TABLE (I INT)
INSERT INTO @TBLA
( [I] )
SELECT 0
SELECT [Result]=CASE WHEN 1=2 THEN
(SELECT I FROM @TBLA T)
ELSE
(SELECT I FROM @TBLA T)
END
无效,因为表变量包含两个记录。
DECLARE @TBLA TABLE (I INT)
INSERT INTO @TBLA
( [I] )
SELECT 0
UNION
SELECT 1
SELECT [Result]=CASE WHEN 1=2 THEN
(SELECT I FROM @TBLA T)
ELSE
(SELECT I FROM @TBLA T)
END
答案 2 :(得分:0)
IN() is supposed to handle more than one values!
是的,实际上是。如果以这种方式修改查询,就可以看到它
select *
from @tblA
where i IN ( select i from @tblB )
此查询将无错误地执行。
该错误是由CASE
语句生成的,因为它不能在THEN
或ELSE
子句中获得超过1的值。