SQL Case when then 语句.

houzhenya 2008-09-18 06:53:26
例如一个表中有四个字段 a b c d
我想判断如果a为null则显示b,如果b也为null则显示c,如果c也为null则显示d,否则什么都不显示
 请问用SQL语句怎么实现?
请各位高手帮帮忙啊.
最好能使用case when then else end 语句实现
...全文
1964 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
houzhenya 2008-09-18
  • 打赏
  • 举报
回复
太感谢各位了
dobear_0922 2008-09-18
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 wuyi8808 的回复:]
向 dobear_0922 学习了。


SQL codeselect coalesce(a,b,c,isnull(d,0)) from @t
-- 可以改为:
select coalesce(a,b,c,d,0) from @t -- 如果 a,b,c,d为数值型
select coalesce(a,b,c,d,'') from @t -- 如果 a,b,c,d为字符型
[/Quote]

呵呵,互相学习,,,
wuyi8808 2008-09-18
  • 打赏
  • 举报
回复
dobear_0922 学习了。

select coalesce(a,b,c,isnull(d,0)) from @t
-- 可以改为:
select coalesce(a,b,c,d,0) from @t -- 如果 a,b,c,d为数值型
select coalesce(a,b,c,d,'') from @t -- 如果 a,b,c,d为字符型
houzhenya 2008-09-18
  • 打赏
  • 举报
回复
谢谢各位了
非常感谢
dobear_0922 2008-09-18
  • 打赏
  • 举报
回复
declare @t table(a int, b int,c int, d int)
insert @t(a) select 1
insert @t(b) select 2
insert @t(c) select 3
insert @t(d) select 4
insert @t default values

select * from @t
select coalesce(a,b,c,d) from @t
select coalesce(a,b,c,isnull(d,0)) from @t

/*
a b c d
----------- ----------- ----------- -----------
1 NULL NULL NULL
NULL 2 NULL NULL
NULL NULL 3 NULL
NULL NULL NULL 4
NULL NULL NULL NULL

(5 行受影响)


-----------
1
2
3
4
NULL

(5 行受影响)


-----------
1
2
3
4
0

(5 行受影响)
*/
wuyi8808 2008-09-18
  • 打赏
  • 举报
回复

-- 如果一定要用 case:
select
case
when a is not null then a
when b is not null then b
when c is not null then c
when d is not null then d
else ''
end
from ...
dobear_0922 2008-09-18
  • 打赏
  • 举报
回复
使用coalesce函数比isnull或case when都方便,,,
dobear_0922 2008-09-18
  • 打赏
  • 举报
回复
select coalesce(a,b,c,d) from tb
wuyi8808 2008-09-18
  • 打赏
  • 举报
回复
select isnull(a, isnull(b, isnull(c, isnull(d, '')))) from ...
mugua604 2008-09-18
  • 打赏
  • 举报
回复
select isnull(a,isnull(b,isnull(c,isnull(d,'')))) from tablename

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧