簡體   English   中英

CASE語句不適用於“ IN”

[英]CASE statement is not working with “IN”

下面的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_id。

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(如第二個查詢所示)。

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

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

您可以使用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.
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

如果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

您可以使用以下查詢

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) 

您可能需要在“ IN”中輸入正確的格式數據

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM