4

I have a sample query like this:

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)

When I execute the query an error pops up indicating:

Incorrect syntax near the keyword 'is'.

Any idea for a work around for this guys?

Thanks!

The purpose of this query is to get the null rows in the table and the non-null rows depending on the value passed on parameter @qualified.

4
  • What are trying to achieve by using case when? You placed is null and is not null incorrectly in your query. Commented Feb 13, 2013 at 8:53
  • If the parameter @qualified has a value of two I would like to get all the null rows in table2 and if it has a value of three I would like to get all the non null rows in table2 Commented Feb 13, 2013 at 8:57
  • Please explain the purpose of this query as it is not a correct query. Commented Feb 13, 2013 at 8:57
  • CASE in T-SQL can only return a single, atomic value - not an expression / code block. Commented Feb 13, 2013 at 10:43

4 Answers 4

6

Try with this:

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)

I believe this syntax represents the conditional expression that you were trying to implement. However, such WHERE clause might result in a performance issues. If that would happen you should use:

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
Sign up to request clarification or add additional context in comments.

Comments

0

Try this (Untested)

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 

Comments

0

Syntax is not correct: Please look at http://msdn.microsoft.com/en-IN/library/ms181765.aspx

Also post you exact requirement so that its easy to suggest how you can use CASE.

Comments

0

Please try:

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)=@qualified 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.