I have the following query (SQL server):
DECLARE @UserId INT;
SET @UserId = //... set by dynamic variable
SELECT *
FROM Users
WHERE userId = @UserId
My issue is that if the @UserId
is null the query will not evaluate correctly.
How can I write this query to evaluate correctly if the variable is null or not null?
EDIT:
There have been many suggestions to use the following:
WHERE (@UserId IS NULL OR userId = @UserId)
OR similar.
In this case, if there is a table of 3 entries, with userId of 1,2 and 3 the variable '@UserId' IS NULL, this query will return all 3 entries. What I actually need it to return is no entries, as none of them have a userId of NULL