日期:2014-05-17 浏览次数:20493 次
--动态的
create table test(A int,B int,C int,D int)
insert into test
select 2,3,NULL,4
union all select 1,NULL,3,2
union all select null,5,null,20
go
declare @s varchar(1000)
select @s=''
select @s=@s+',['+a.name+']=case when ['+a.name+'] is null then ['+b.name+'] else ['+a.name+'] end'
from syscolumns a
left join syscolumns b on a.colid=b.colid+1
where a.id=OBJECT_ID('test') and b.id=OBJECT_ID('test')
order by a.colid
exec ('select A'+@s+' from test')
drop table test
/*
A B C D
2 3 3 4
1 1 3 2
NULL 5 5 20 -->如果第一列为空,那只能取原值 了
*/
if object_id('tb') is not null
drop table tb
go
create table tb(A int,B int,C int,D int)
insert into tb
select 2,3,NULL,4
union all select 1,NULL,3,2
union all select null,5,null,20
go
declare @sql varchar(1000)
select @sql=''
select @sql=@sql+',case when ['+d.name
+'] is null then '+c.name+' else ['+d.name+'] end as '+d.name
from sys.tables t
inner join sys.columns c
on t.object_id = c.object_id
inner join sys.columns d
on d.column_id = c.column_id + 1
and t.object_id = d.object_id
where t.name = 'tb'
order by c.column_id
set @sql ='select A'+ @sql +' from tb'
--输出动态语句
select @sql
/*
select A,
case when [B] is null then A else [B] end as B,
case when [C] is null then B else [C] end as C,
case when [D] is null