3

What I want is when @AddressCode is null then simply execute

SELECT
    *
FROM
    Addresses
WHERE
    1= 1

If @AddressCode is not NULL then execute

SELECT
    *
FROM
    Addresses
WHERE
    1= 1 AND @AddressCode=Addresses.AddressCode

How can I achieve this ... I tried query below and its not working for Address with NULL value or when @AddressCode is NULL .... (Addresses is just an imaginary table name)

Declare @AddressCode varchar(20)
Set @AddressCode=NULL

SELECT
    *
FROM
    Addresses
WHERE
    1= 1
    AND
    CASE @AddressCode
        WHEN NULL
        THEN Addresses.AddressCode
        ELSE @AddressCode
    END =Addresses.AddressCode

I tried hard but am not able to make it ... I know i can write IF statement and write individual select statement but don't want to do that as i have lots of such criteria as @AddressCode :(

1
  • ISNULL is your friend here... Commented Dec 11, 2014 at 21:53

2 Answers 2

11
SELECT *
FROM
    Addresses
WHERE
    (@AddressCode IS NULL OR Addresses.AddressCode = @AddressCode)
Sign up to request clarification or add additional context in comments.

2 Comments

If address code is indexed you would need to use RECOMPILE with this to prevent an unnecessary scan in the case that @AddressCode IS NOT NULL
Thanks it works Simply great :) Initially i missed that () in where so was messed up and i fixed it.
4

You are using CASE improperly in this case (comparing with null). The right way is

CASE
  WHEN @AddressCode IS NULL THEN Addresses.AddressCode
  ELSE  @AddressCode
 END

The problem with your query is that CASE a WHEN b THEN c... tests if a=b which turns into FALSE(NULL) if one of the operands is null.
Another question is if you really need CASE here...

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.