I am modifying an existing stored procedure in SQL server and trying to come up with a query that should take a conditional WHERE depending on whether one of the input parameters is null or has value.
The stored procedure takes three input parameters
@FromDate
@ToDate
@PersonnelNo
@FromDate and @ToDate will always have value and will be part of the WHERE condition but @PersonnelNo can be null or can hold value.
When @PersonnelNo is null I want all users for the given @FromDate and to @ToDate date but when the parameter @PersonnelNo has a value then I want the stored procedure to return data for that user only.
I’ve tried the below two approaches but it only works (gives one user record correctly) when I input value for @PersonnelNo. It doesn’t return any record if I input @PersonnelNo as null, rather I want all users.
Any idea where I’m going wrong or is that possible at all with the current approach I am taking?
SELECT FirstName,
LastName,
PersonnelNum,
RecCreatedOn
FROM [test].Person
WHERE RecCreatedOn BETWEEN @FromDate AND @ToDate
AND (
(ISNULL(@PersonnelNo, 0) != 0 AND PersonnelNum = @PersonnelNo)
)
and a slightly different WHERE clause
WHERE RecCreatedOn BETWEEN @FromDate AND @ToDate
AND ((@PersonnelNo IS NOT NULL) AND PersonnelNum = @PersonnelNo)