As you know null never equals null in SQL.
Let’s pretend we have a query like this:
declare @LastName varchar(50) = 'Nixon';
select * from Users
where LastName = @LastName;
If I want to allow the variable to be null, I do this:
declare @LastName varchar(50) = 'Nixon';
select * from Users
where LastName = IsNull(@LastName, LastName);
But what if LastName is null? I must do this:
declare @Null varchar(50) = '!{-[~]-}!'; -- any-ole gibberish
declare @LastName varchar(50) = 'Nixon';
select * from Users
where IsNull(LastName, @Null) = Coalesce(@LastName, LastName, @Null);
This works just fine, and I see many similar approaches out there.
But my question is: is this really the best approach? It seems to me that this is a kludge, but I have thought about it a lot and simply cannot come up with anything better.
EDIT but this seems best:
declare @LastName varchar(50) = 'Nixon';
select * from Users
where (@LastName is null) or (@LastName = LastName);
Wouldn’t it be simpler to do this?