日期:2014-05-17 浏览次数:20573 次
create table tbA
(col1 int,col2 int,col3 int,col4 int)
insert tbA
select 1,2,3,null union all
select 1,2,3,null union all
select 1,2,null,null union all
select 1,2,3,null union all
select 1,2,3,null union all
select 1,2,3,null
go
--col1和col2没有空值
declare @sql as nvarchar(4000)
set @sql=''
select @sql=@sql+'+case when not exists(select 1 from tbA where '+[name]+' is null) then '',' +[name]+''' else '''' end'
from sys.columns where [object_id]=object_id('tbA')
set @sql=' declare @sql2 as nvarchar(4000)'+
' set @sql2= '+stuff(@sql,1,1,'')+
' set @sql2=stuff(@sql2,1,1,'''') '+
' exec(''select ''+ @sql2+'' from tbA'')'
exec(@sql)
col1 col2
----------- -----------
1 2
1 2
1 2
1 2
1 2
1 2
(6 row(s) affected)
go
--col1、col2、col3不全为空
declare @sql as nvarchar(4000)
set @sql=''
select @sql=@sql+'+case when exists(select 1 from tbA where '+[name]+' is not null) then '',' +[name]+''' else '''' end'
from sys.columns where [object_id]=object_id('tbA')
set @sql=' declare @sql2 as nvarchar(4000)'+
' set @sql2= '+stuff(@sql,1,1,'')+
' set @sql2=stuff(@sql2,1,1,'''') '+