我在数据库中有几个表.我想找到哪些列(在哪些表中)没有任何值(列中的所有NULL).我在下面的例子中,结果应该是
TestTable1 --> Var2 TestTable2 --> Variable1
我不知道如何创建这种查询.非常感谢您的帮助!
--create first table create table dbo.TestTable1 ( sur_id int identity(1,1) not null primary key,var1 int null,var2 int null ) go --insert some values insert into dbo.TestTable1 (var1) select 1 union all select 2 union all select 3 --create second table create table dbo.TestTable2 ( sur_id int identity(1,variable1 int null,variable2 int null ) --and insert some values insert into dbo.TestTable2 (variable2) select 1 union all select 2 union all select 3
解决方法
对于单个列,count(ColumnName)返回ColumName不为null的行数:
select count(TheColumn) from YourTable
您可以为所有列生成查询.根据Martin的建议,您可以使用is_nullable = 1排除不能为null的列.例如:
select 'count(' + name + ') as ' + name + ',' from sys.columns where object_id = object_id('YourTable') and is_nullable = 1
如果表的数量很大,您可以以类似的方式为所有表生成查询.所有表的列表都在sys.tables中.