2010-01-18 60 views
8

捕获NULL值我想用一些新值替换Adventureworks数据库的Person.Contact中的值。下面的查询语句对其他值工作正常,但我无法更改那些值为NULL的值。我正在使用SQL Server。任何帮助表示赞赏。如何在此查询中使用case语句

 
select contactid,Title,FirstName,MiddleName, 
case MiddleName 
when 'R.' then 'Robert' 
when 'B.' then 'Bids' 
when 'J.' then 'John' 
when is null then 'New Name' 
else 'No Name' 
end, LastName from Person.Contact 

回答

10

我会使用ISNULL函数 - 如果该字段为空,它将返回给定的值:

select contactid,Title,FirstName,MiddleName, 
case ISNULL(MiddleName, 'NULLVALUE') 
when 'R.' then 'Robert' 
when 'B.' then 'Bids' 
when 'J.' then 'John' 
when 'NULLVALUE' then 'New Name' 
else 'No Name' 
end, LastName from Person.Contact 
+0

错误的NULL情况下。 – 2010-01-18 09:59:10

+0

@Johan:我的错 - 修好了。现在它应该可以正常工作。 – 2010-01-18 10:03:11

+6

我同意。我们只希望没有人有'NULLVALUE'作为中间名。 – 2010-01-18 10:06:42

15
case 
when MiddleName is null then ... 
when MiddleName = 'R' then ... 
end 
2

对不起7年后发布的,但我一直在努力为Interbase/Firebird寻找解决方案,这篇文章不断出现。这里没有解决方案,因为没有ISNULL,所以我想我会帮助其他人谁可能来这里寻找:

select contactid,Title,FirstName,MiddleName, 
case COALESCE(MiddleName, 'NULLVALUE') 
when 'R.' then 'Robert' 
when 'B.' then 'Bids' 
when 'J.' then 'John' 
when 'NULLVALUE' then 'New Name' 
else 'No Name' 
end, LastName from Person.Contact 
+2

Firebird也没有['is null'](http://stackoverflow.com/a/2085129/11683)(与'isnull'相反)? – GSerg 2017-01-12 18:50:18

+1

非常感谢。如果使用Interbase时遇到同样的问题,那就是没有ISNULL,但代码正常工作! – SovereignSun 2017-01-18 10:56:59

+0

@GSerg Firebird可能,但我在InterBase工作...... Firebird似乎有更多的功能,但任何在InterBase中工作的东西都应该在Firebird中工作,而不是相反。 此外,我看到了各种链接来为ISNULL设置自己的UDF,但这似乎超出了我所需要做的。 – eromrab 2017-01-20 15:35:08