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.

0

1 Answer 1

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; 
Sign up to request clarification or add additional context in comments.

1 Comment

I suggest one specify an OPTION(RECOMPILE) query hint with this technique in order to optimize the query for either use case.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.