Null column values in select query equality check

  • Hi,

    I have this sproc, @age parameter is passed in to this sproc and it returns all the rows from the Users table that matches with the age parameter. @age is an optional parameter, so if the parameter is null, all the rows are to be returned.

    SELECT name, age FROM users WHERE age = ISNULL(@age, age)

    It works fine when an integer value is passed, i.e @age is not null. But when @age is null, the query does not return all the rows from the table. It returns only the rows which has some value for the age column. All the rows where age is NULL is not returned.

    Is there an easy solution to deal with this? There are quite a few other parameters in this sproc and most of them can be null. Any suggestions?

    Thanks.

  • try SELECT name, age FROM users WHERE ISNULL(age,0) = ISNULL(@age, 0)

    Lowell


    --help us help you! If you post a question, make sure you include a CREATE TABLE... statement and INSERT INTO... statement into that table to give the volunteers here representative data. with your description of the problem, we can provide a tested, verifiable solution to your question! asking the question the right way gets you a tested answer the fastest way possible!

  • WHERE (age = @age OR @age IS NULL)

    _____________
    Code for TallyGenerator

  • Hi,

    I would suggest to stay out of the Three-State-Logic with NULL's involved.

    This could be very complicated when working with complex database solutions.

    A simple idea could be;

    Create Procedure s_ProductTest

    @parm1 int = 9999999,

    @parm2 int = 9999999

    As

    Begin

     Select * from Producttest Where (product = @Parm1 or @Parm1 = 9999999)

    End

    exec s_productTest 123

     

     

    Cheers

    Arthur

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply