CASE语句不适用于“IN”

时间:2016-09-28 05:16:04

标签: sql sql-server

以下SQL查询返回结果。

declare @flag bit = 0

select * 
from file_table fd 
where fd.person_id = case @flag 
                        when 0 then 10349196 
                        else fd.person_id 
                     end

但我想更改上面的查询以包含两个person_ids,如下所示。

declare @flag bit = 0
declare @person_ids varchar(100) = '(1001,1002)'

select * 
from file_table fd 
where fd.person_id in case @flag 
                          when 0 then @person_ids 
                          else fd.person_id 
                      end

但是这个查询会抛出错误

  

关键字'case'附近的语法不正确

任何人都可以帮我解决这个问题吗?我的意图是我想在case语句中包含两个人ID(如第二个查询中所示)。

5 个答案:

答案 0 :(得分:1)

{{1}}

答案 1 :(得分:1)

您可以使用OR,如下所示:

declare @flag bit = 0
declare @person_ids varchar(100) = ',1001,1002,' -- You need ',' at beginning and end

select * 
from file_table fd 
where 
    @flag  != 0 OR
    @person_ids LIKE '%,' + fd.person_id + ',%' -- Type of fd.person_id must be varchar. 
                                                -- If not Convert to varchar.

答案 2 :(得分:0)

declare @flag bit =0
--declare @person_ids varchar(100) = '(1001,1002)'

--drop table #person_ids
create table #person_ids (name varchar(30))
insert into #person_ids   values('1001')
insert into #person_ids   values('1002')

 select * from file_table fd ,#person_ids where fd.person_id in  
(select case  when @flag=0 then   name  else fd.person_id end)

drop table #person_ids

答案 3 :(得分:0)

如果person_id列包含整数值,则您的case语句将不起作用。尝试使用以下脚本。

DECLARE @flag bit = 0
DECLRAE @person_ids varchar(100) = '1,2'

;WITH cte_1
AS
(SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS SplitValues
FROM
(SELECT CAST('<XMLRoot><RowData>' + REPLACE(@person_ids,',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML)AS x)t
CROSS APPLY x.nodes('/XMLRoot/RowData')m(n))
SELECT *
FROM file_table  c
 LEFT JOIN cte_1 c1 ON c.person_id=c1.SplitValues
WHERE c.person_id=CASE  WHEN  @flag=0 THEN  c1.SplitValues ELSE c.person_id END

答案 4 :(得分:0)

您可以使用以下查询

declare @flag bit = 0
select *  from file_table fd 
where fd.person_id = case @flag when 1 then  fd.person_id end 
OR fd.person_id IN(1001,1002) 

您可能需要在&#39; IN&#39;

中使用正确的格式数据