I have written SQL Server procedure like below,
if @name_belongs_to != 'John'
begin
--doing some operation
end
If the name is not 'John', it is working fine. However if it is NULL, it is not executing if part.
How to handle this?
I have written SQL Server procedure like below,
if @name_belongs_to != 'John'
begin
--doing some operation
end
If the name is not 'John', it is working fine. However if it is NULL, it is not executing if part.
How to handle this?
One option would be to use COALESECE() on the name:
if coalesce(@name_belongs_to, '') != 'John'
begin
--doing some operation
end
You cannot compare NULL values in SQL Server (and most other RDBMS) using the equals operator. Instead, you need to use IS NULL or IS NOT NULL. Using COALESCE() here is a trick which will convert a NULL value to a string for comparison with !=.
This is also valid:
if @name_belongs_to != 'John' OR @name_belongs_to IS NULL
begin
--doing some operation
end
This MSDN article explains how Three-Valued Logic works.