2013-02-13 2 views
4

나는이 같은 샘플 쿼리가있을 때 CASE를 사용 : 나는 쿼리를 실행하면SQL 서버 THEN 문

select t1.name,t1.bday,t2.address,t2.contactnum 
from table1 as t1 
left join table2 as t2 on t1.p_id = t2.p_id 
where (case when @qualified = '2' then t2.role is null 
     case when @qualified = '3' then t2.role is not null` end) 

오류가 나타내는 팝업 :

잘못된 구문을 키워드 근처를 '입니다 '.

이 사람에 대한 해결 방법은 없습니까?

감사합니다.

이 쿼리의 목적은 테이블에 null 행을 가져오고 null이 아닌 행을 매개 변수 @qualified에 전달 된 값에 따라 가져 오는 것입니다.

+0

을 달성하려고하는 어떤 '경우 when'를 사용하여? 쿼리에서'is null' 및'not null '을 잘못 배치했습니다. –

+0

@qualified 매개 변수 값이 2 인 경우 table2의 모든 null 행을 가져오고 싶습니다. 값이 3 인 경우 table2에 null이 아닌 모든 행을 가져오고 싶습니다. – jr17

+0

이 쿼리의 목적을 설명해주세요. 올바른 쿼리가 아니기 때문입니다. – Joshi

답변

5

이 함께 시도 :

select t1.name,t1.bday,t2.address,t2.contactnum 
from table1 as t1 
left join table2 as t2 on t1.p_id = t2.p_id 
where (@qualified = '2' AND t2.role is null) OR (@qualified = '3' AND t2.role is not null) 

나는이 구문은 당신이 구현하려고 한 조건식을 나타냅니다 생각합니다. 그러나 WHERE 절을 사용하면 성능 문제가 발생할 수 있습니다. 그렇게한다면 당신은 사용해야합니다

IF @qualified = '2' THEN 
BEGIN 
    select t1.name,t1.bday,t2.address,t2.contactnum 
    from table1 as t1 
    left join table2 as t2 on t1.p_id = t2.p_id 
    where t2.role is null 
END 

IF @qualified = '3' THEN 
BEGIN 
    select t1.name,t1.bday,t2.address,t2.contactnum 
    from table1 as t1 
    left join table2 as t2 on t1.p_id = t2.p_id 
    where t2.role is not null 
END 
0

SELECT t1.name,t1.bday,t2.address,t2.contactnum 
FROM table1 as t1 
LEFT JOIN table2 AS t2 ON t1.p_id = t2.p_id 
WHERE 
    CASE @qualified 
     WHEN '2' THEN t2.role is null 
     WHEN '3' THEN t2.role is not null 
    END 
0

구문이 올바르지 않습니다이 (테스트되지 않은)를보십시오 : 이 http://msdn.microsoft.com/en-IN/library/ms181765.aspx

제발 봐 또한 당신에게 정확한 요구 사항을 게시 쉬운 있도록 CASE를 사용하는 방법을 제안합니다.

0

시도하십시오 :

select t1.name,t1.bday,t2.address,t2.contactnum 
from table1 as t1 
left join table2 as t2 on t1.p_id = t2.p_id 
where (case when t2.role is null then '2' else '3' end)[email protected]