Checking an input param if not Null and using it in where in SQL Server

后端 未结 8 1545
暖寄归人
暖寄归人 2020-12-23 14:05

What is the best way to include an input param in the WHERE clause but exclude it if it is null?

There are a number of ways I believe, but I can\'t seem

8条回答
  •  天涯浪人
    2020-12-23 14:12

    This question really helped me with a similar issue that had a few of us scratching our heads for a bit. I only write it up in case somebody else tries the same approach and cannot figure out why it does not work.

    I was trying to only evaluate a part of a multipart WHERE clause if the @Parameter was not null. I tried to do this as below but always had no rows returned if @Parameter was null.

    DECLARE @Parameter int = null;
    
    SELECT  *  FROM  TABLE
    WHERE   [AlternateID] is not null 
            AND (@Parameter is not null AND [AlternateID] = @Parameter)
    

    I incorrectly thought that (@Parameter is not null AND [AlternateID] = @Parameter) would simply not form part of the full WHERE clause is @Parameter was null. However it was making the entire WHERE clause return false. The remedy was to add an OR 1=1 as below:

    WHERE   [AlternateID] is not null 
            AND (@Parameter is not null AND [AlternateID] = @Parameter OR 1=1)
    

    Of course the approach outlined by Ali (not enough reputation to upvote) solves this more efficiently.

    WHERE   [AlternateID] is not null 
            AND [Partner_Customer_ID] = ISNULL(@Parameter, [Partner_Customer_ID])    
    

提交回复
热议问题