读书人

检索数据时判断某数据是否为空否则

发布时间: 2012-02-24 16:30:38 作者: rapoo

检索数据时,判断某数据是否为空,否则用另一字段的数据。
表 mytable 内有两个字段
col1,col2

我希望能够检索:如果某行的 col1 里无数据,则使用 col2 的数据。

这条SQL该如何编写?
select ??? from mytable




[解决办法]
select case col1 when null then col2 end
from mytable
[解决办法]
select case
when col1 is null then col2
else col1
end
from mytalbe


[解决办法]
如果你是字符型字段,还要考虑空字符串—— ' '的情况


select
case col1
when null then col2
when ' ' then col2
end
from mytable
[解决办法]
select case when col1 is null then col2 else col1 end as col1 from mytable

[解决办法]
--如果只考虑到null情况 用下面的就可以了

select isnull(col1,col2) from mytable

读书人网 >SQL Server

热点推荐