2

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?

1

5 Answers 5

4

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 !=.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

just use is not null

if @name_belongs_to != 'John' or @name_belongs_to is not  null
begin
  --doing some operation
end

Comments

0

By default any comparison to null returns false

null = null is false
null = 'value' is false

so you need to add

OR @name_belongs_to IS NULL

Comments

0

I have used below statement to resolve my issue,

if isnull(@name_belongs_to,'') != 'John'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.