0

I want to write a T-SQL query for below conditions.

If the user provides a value for the parameter, run the query with the where clause.

SELECT * 
FROM TestDB 
WHERE CustomerId = @customer_id

If the user doesn't provide a value for the parameter, I want to return all the data

SELECT * 
FROM TestDB

Can I make it work in a single query, for example using ISNULL() or an alternative, without going for a stored procedure.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Nipuna Dilhara
  • 424
  • 2
  • 6
  • 18

1 Answers1

2

Add a condition to the WHERE clause which admits all records in the event the user parameter be null:

SELECT *
FROM TestDB
WHERE CustomerId = @customer_id OR @customer_id IS NULL;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • 2
    I suggest one specify an `OPTION(RECOMPILE)` query hint with this technique in order to optimize the query for either use case. – Dan Guzman Sep 07 '21 at 11:37