select isnull(a, isnull(b, isnull(c, isnull(d, '')))) from ...
select coalesce(a,b,c,d) from tb
使用coalesce函数比isnull或case when都方便,,,
-- 如果一定要用 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 ...
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 valuesselect * 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 行受影响) */
向 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为字符型
-- 如果一定要用 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 ...
insert @t(a) select 1
insert @t(b) select 2
insert @t(c) select 3
insert @t(d) select 4
insert @t default valuesselect * 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 行受影响)
*/
-- 可以改为:
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为字符型