How to Execute AND clause only if param is not NULL

Brian collins 141 Reputation points
2021-01-29T18:02:04.507+00:00

Hi,

I have a sql statement something like below but I want the AND condition to be executed only when the @param1 is not NULL, else I want all the record to be retuned for ID 123. Can you please advise on how to accomplish this task?

Declare @param1 varchar(255) = NULL
SET @param1='B1, B2'

SELECT C.* FROM Customer C
WHERE C.ID = 123
AND C.Degree IN ISNULL(@param1, C.Degree)
Developer technologies Transact-SQL
SQL Server Other
{count} votes

Accepted answer
  1. Viorel 122.5K Reputation points
    2021-01-29T18:12:21.5+00:00

    This will work in certain circumstances:

    SELECT * 
    FROM Customer
    WHERE ID = 123
    AND ( @param1 is null or Degree IN (select trim(value) from string_split(@param1, ',')) )
    option (recompile)    
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.