Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

CASE WHEN in WHERE condition logic

I have query like below

SELECT name, address, phone
FROM users
WHERE
    CASE @ViewType
    WHEN 'AR' THEN phone IS NULL
    WHEN 'PO' THEN phone IS NOT NULL
    ELSE 1=1 END

ViewType is parameter, but I received an error in my SQL.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You want boolean logic:

select name, address, phone 
from users 
where
    (@viewtype = 'AR' and phone is null)
 or (@viewtype = 'PO' and phone is not null)
 or @viewtype not in ('AR', 'PO')

If 'AR' and 'PR' are the only possible values of the parameter, then the last predicate can be removed.

For performance with such parameterized query, consider using option(recompile), so that a new plan is generated for the current value value of the parameter.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading