Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何仅选择其中没有数据的列?_Sql_Sql Server - Fatal编程技术网

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

Sql 如何仅选择其中没有数据的列?,sql,sql-server,Sql,Sql Server,我试图只返回没有数据的列(所有空值)。使用select语句有没有简单快捷的方法 谢谢,根据回复进行编辑 这将返回所有列的列表以及其中的记录数。 您所要做的就是将输出过滤为非空 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;

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


谢谢,

根据回复进行编辑

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

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

其中列为空如果您有多个相关列,则应该考虑规范化模型。创建另一个表,该表在每个记录中存储一个值,并通过外键与主表相关。然后可以使用此查询:
SELECT t1.Identifier,t2.Value,t2.Name FROM MainTable t1 internal JOIN ValueTable t2 ON t1.Identifier=t2.ForeignKeyColumn其中t2.Value为NULL
此查询的可能副本将仅返回我在查询中指定的列。我真正想要的是返回所有为空的列。谢谢,根据您的回复进行编辑。