【www.gdgbn.com--页面特效】

sql null值的处理方法

sqlserver 中isnull的用法一例

数据库教程中有一列记录文章的访问次数。我现在要实现的功能是,每刷新一次页面。 访问次数+1。sql语句,art_count为访问次数,int类型。
update article set art_count="(art_count+1) where art_id="3 但如果art_count为null,则不起作用。
如果是oracle用decode可以很容易的实现此功能。sqlserver中如何实现类似的功能呢?
sqlserver中有一个函数isnull,此函数有两个参数isnull(p1,p2)其用法是如果p1为null,则用p2代替。
此函数类似oracle的nvl。例如
select avg(isnull(price, $10.00)) from titles 受到此函数的启发我这样写的sql语句
update article set art_count="(isnull(vote_count,0)+1) where art_id="3 "

 


-判断某些字段是否为空
--case
select case when "字段名" is null then "n" else convert(varchar(20),"字段名") end as "newname"
select case when null is null then "n" else convert(varchar(20),null) end as "newname"

--sql server 2005:coalesce
select coalesce("字符串类型字段","n") as "newname"
select coalesce(convert(varchar(20),"非字符串类型字段"),"n") as "newname"
select coalesce(convert(varchar(20),null),"n") as "newname"

--coalesce,返回其参数中的第一个非空表达式
select coalesce(null,null,1,2,null)union
select coalesce(null,11,12,13,null)union
select coalesce(111,112,113,114,null)


null值也不是对所有的统计函数都有影响。一般来说。统计平均值(avg)时, null值是一定会有影响的;统计最小值(min)时, null值是可能会对 min 有影响,在我认为是有点随机性质;统计最大值(max)或统计和(null)时,null值是对其完全没有影响的。

所以又有一种说法是:null值不参加统计,不参加计算,只能用is判断。

判断null值语句:select * from 表 where 字段 is null;

转换null值语句:select 字段1,字段2,字段3,is null(字段3,’某个值’) from 表;

总之,我们要认真对待 null值,最好在使用统计函数时,都加上 is null,以防意外出现

本文来源:http://www.gdgbn.com/wangyetexiao/28426/