ОК, так что это довольно сложный набор генерации динамического SQL, который даст вам то, что вы ищете. Вы должны вставить это в хранимую процедуру, если хотите ее использовать.
FilterColTest - это тестовая таблица, которую я использовал для тестирования. Я оставлю определение и т. Д. В запросе, чтобы вы могли внести соответствующие изменения в вашу таблицу / столбцы.
/*
create table FilterColTest (
a int, b int, c int, d int, e int, f int, g int, h int, i int, j int)
insert into FilterColTest
select null,1,null,null,1,0,null,1,null,null
union select null,null,null,null,0,0,null,null,null,null
union select null,1,null,null,1,0,null,1,null,1
union select null,1,null,null,1,1,null,1,null,null
union select 1,1,0,null,1,0,null,1,null,null
--select * from FilterColTest
go
*/
declare @ColumnList table (ID int identity, colName varchar(max))
insert into @ColumnList(colName)
select column_name
from information_schema.columns
where table_name = 'FilterColTest'
declare
@id int, @maxid int, @count int,
@cols varchar(max), @sql nvarchar(max)
select @id = 1, @maxid = max(ID)
from @ColumnList
while @id <= @maxid
begin
select @sql = 'select @count = count(*) from FilterColTest where ' +
colName + ' is not null'
from @ColumnList
where ID = @id
exec sp_executesql @sql, N'@count int output', @count output
select @cols = isnull(@cols + ', ' + colName, colName)
from @ColumnList
where ID = @id and @count > 0
set @id = @id + 1
end
select @sql = 'select ' + @cols + ' from FilterColTest'
exec sp_executesql @sql
go
/*
drop table FilterColTest
go
*/