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)
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,734 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,552 questions
{count} votes

Accepted answer
  1. Viorel 112.2K 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