如何仅选择没有数据的列?

时间:2016-07-18 15:12:54

标签: sql sql-server

我试图只返回没有数据的列(所有NULL值)。使用select语句有一种简单快捷的方法吗?

谢谢,

1 个答案:

答案 0 :(得分:-1)

根据回复进行编辑

这将返回所有列的列表以及其中的记录数。 您所要做的就是将输出过滤为non_null

declare @table_name as varchar(128) = ''; -- your table name here
declare @column_name as varchar(128);
declare @sql as nvarchar(4000);
declare @count_column int;
declare @tmp_table_result as table (
    id int identity(1,1),
    table_object_id bigint,
    column_name varchar(128),
    non_null_records int
    );
declare csr cursor for 
select name
from sys.columns where object_id = OBJECT_ID(@table_name);
open csr;
fetch next from csr into @column_name;
WHILE @@FETCH_STATUS = 0 
BEGIN
set @sql = 'select @cnt_col = count(' + @column_name + ') from ' + @table_name;
print @sql
execute sp_executesql @sql, N'@cnt_col int output', @cnt_col=@count_column OUTPUT;

insert into @tmp_table_result (table_object_id, column_name, non_null_records)
values (
    object_id(@table_name),
    @column_name,
    @count_column
    );
fetch next from csr into @column_name;
END
close csr;
deallocate csr;
select * 
from @tmp_table_result