2016-09-28 110 views
0

以下SQL查詢返回結果。CASE語句不適用於「IN」

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語句中包含兩個人員ID(如第二個查詢所示)。

+0

給出的答案基本上是你周圍的語法錯誤是如何得到的,但你仍然有因爲SQL不會分析變量中的文本......所以如果你想用非靜態值做這樣的事情,你需要使用動態SQL。另外,使用兩個單獨的變量,並有'IN(@ var1,@ var2)' – ZLK

+0

這將避免語法錯誤。但是不會返回任何結果集,儘管表中有這兩個人員ID的條目。任何想法爲什麼? – user3742125

+0

案例表達式,不是case語句。 (因爲它返回一個值!!!) – jarlh

回答

1
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) 
+0

你真的運行過嗎?看起來不正確。 –

+0

這將避免語法錯誤。但是不會返回任何結果集,儘管表中有這兩個人員ID的條目。任何想法爲什麼? – user3742125

1

您可以使用OR爲如下:如果person_id列包含整數值

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. 
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 
+0

這有點重,但它會解決你的問題嘗試並確認 – Shridhar

0

你的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 
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) 

您可能需要在「IN」數據格式正確