嵌入在In子句中的SQL Server案例语句

时间:2015-08-13 09:15:09

标签: sql sql-server-2008

我在case子句中编写了IN语句。我收到以下错误:

  

子查询返回的值超过1。这是不允许的   子查询跟随=,!=,<,< =,>,> =或当子查询用作   表达。

以下是代码:

declare @Consultant as bigint
set @Consultant=0

select * from tProject where 
 tProject.ID in 
( 
Case
When @Consultant=0 then (select #t1.ProjectID from #t1)
else  (select #t1.ProjectID from #t1 inner join #t2 on #t1.ProjectID=#t2.ProjectID)
end
)

1 个答案:

答案 0 :(得分:0)

试试这个

declare @Consultant as bigint
set @Consultant=0

select * from tProject where 
( tProject.ID in (select #t1.ProjectID from #t1) and @Consultant=0)

or

(tProject.ID in 
(select #t1.ProjectID from #t1 inner join #t2 on 
#t1.ProjectID=#t2.ProjectID) and @Consultant<>0
)

或使用IF

declare @Consultant as bigint
set @Consultant=0

If @Consultant=0 then
select * from tProject where 
tProject.ID in (select #t1.ProjectID from #t1)

else

select * from tProject where 
tProject.ID in 
(select #t1.ProjectID from #t1 inner join #t2 on 
#t1.ProjectID=#t2.ProjectID)