Reputation: 3903
I'm new to development. In sql I have written a stored procedure and it is working correctly but I just wanted to make sure it is done the correct way.
Here I am using an IF statement in sp to check whether date column in a table is NULL or not:
if ((select sdate
from tbla
where id='3') = Null)
begin
some query
end
Will this work for all cases or do I need to check for ''(empty) also?
Upvotes: 2
Views: 1604
Reputation: 38392
If you want to display some other expression whenever something is null, Coalesce may be what you want.
Select CASE When (null = null) Then 1 Else 0 END
Result: 0
Select CASE When (null is null) Then 1 Else 0 END
Result: 1
Select null + 'soemthing'
Result: null
Select Coalesce(null, 'DefaultValueIfNull')
Result: DefaultValueIfNull
Append a space and last name only if lastname is not null:
select FirstName + coalesce(' ' + LastName, '') From People
Append a space and last name only if lastname is not null, with handling for empty LastName:
select FirstName + coalesce(' ' + CASE LastName When '' Then null Else LastName END, '') From People
Upvotes: 3
Reputation: 2476
Empty and NULL are not the same thing, so you will need to check for an empty string separately. You also should use is null
rather than = null
to check if a column is null.
Upvotes: 4
Reputation: 727067
In SQL null is not equal to anything, including other nulls. You need to use is null
instead of the =
operation.
Upvotes: 11