How to compare Null values from the database colum

2019-01-28 02:56发布

This question already has an answer here:

I have record in my table where Name column has Null value.. and I want to update that record using below query.. My sql query is:

set @Name=NUll;

update emp set name="gaurav" where name=@Name

When I run this query.. It will not update the record.. It does not compare the value Null to column value

How can this be done?

5条回答
霸刀☆藐视天下
2楼-- · 2019-01-28 03:14
SET @Name = NULL;

UPDATE emp
SET name="gaurav"
WHERE    (@Name IS NULL     AND name IS NULL)
      OR (@Name IS NOT NULL AND name = @Name)
查看更多
小情绪 Triste *
3楼-- · 2019-01-28 03:15

Try this UPDATE emp SET name = "gaurav" WHERE (@name IS NULL AND name IS NULL)

查看更多
趁早两清
4楼-- · 2019-01-28 03:22

Also you can use following condition with ISNULL()

SET @Name = NULL;

UPDATE emp SET name='gaurav' WHERE ISNULL(@Name,'XXXXXXX')=ISNULL(Name,'XXXXXXX'); 

Where 'XXXXXXX' is a unique string constant which can't exist in EMP table;

查看更多
仙女界的扛把子
5楼-- · 2019-01-28 03:29

Tests with null values are always false in SQL, except IS NULL or IS NOT NULL. you should add a IS NULL clause to your WHERE:

WHERE name = @name
**OR (name IS NULL and @name IS NULL)**
查看更多
ら.Afraid
6楼-- · 2019-01-28 03:31

As per my SQL Knowledge u can store NULL in a variable, but can't use it for comparing

update emp set name="gaurav" where name is Null
查看更多
登录 后发表回答