2016-09-28 3 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 문 안에 두 번째 ids (두 번째 쿼리에 표시된대로)를 포함하고자합니다.

+0

주어진 대답은 기본적으로 'IN'에 적절한 형식의 데이터를해야 할 수도 있습니다 우는 소리 쿼리를 사용할 수 있지만, 당신은 여전히있을 것이다 SQL은 변수의 텍스트를 구문 분석하지 않으므로 오류가 발생합니다 ... 정적이 아닌 값으로 이와 같은 작업을 수행하려면 동적 SQL을 사용해야합니다. 또는 두 개의 별도 변수를 사용하고 'IN (@ var1, @ var2)'을 사용하십시오. – ZLK

+0

이것은 구문 오류를 해결합니다. 그러나 테이블에는이 두 사람 ID에 대한 항목이 있지만 결과 세트는 반환되지 않습니다. 왜 그런가? – user3742125

+0

대소 문자를 구분하지 않고 대소 문자를 구분합니다. (값을 반환하기 때문에 !!!) – 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

귀하의 경우 문이 작동하지 않습니다. 아래 스크립트를 사용해보십시오.

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) 

당신은 구문 오류를 해결하기 방법

관련 문제