我对SQL有点新意,所以请耐心等待。我试图编写一些查询,允许我遍历整个表并查找每列中出现空值的次数。通过输入以下内容很容易做到这一点:
Select
SUM(CASE COL_1 WHEN IS NULL THEN 1 ELSE 0 END) AS COL_1_NULLS
,SUM(CASE COL_2 WHEN IS NULL THEN 1 ELSE 0 END) AS COL_2_NULLS
FROM TABLE1
这很简单,但是如果你想为多个表执行此操作,或者如果一个表有很多列,则会变得很困难。
我正在寻找一种方法来编写一个将表名传递给它的查询,然后循环遍历定义表中的每一列(可能通过连接将列名称通过连接拉到元数据视图?)然后汇总列中的空值数。在任何人加入挑剔的行列之前,请记住,这个基本想法不仅可以用于查找空值。非常感谢您对此问题的任何帮助。
答案 0 :(得分:1)
您需要使用动态sql:
declare @custom_sql varchar(max)
set @custom_sql = 'SELECT null as first_row'
select
@custom_sql = @custom_sql + ', ' + 'SUM(CASE WHEN ' + COLUMN_NAME + ' IS NULL THEN 1 ELSE 0 END) as ' + COLUMN_NAME + '_NULLS'
from
INFORMATION_SCHEMA.COLUMNS where table_name = 'MYTABLE'
set @custom_sql = @custom_sql + ' FROM MYTABLE'
exec(@custom_sql)
您还可以使用COALESCE
字词(仅用于稍微不同的方法):
declare @custom_sql varchar(max)
select
@custom_sql = COALESCE(@custom_sql + ', ', '') + 'SUM(CASE WHEN ' + COLUMN_NAME + ' IS NULL THEN 1 ELSE 0 END) as ' + COLUMN_NAME + '_NULLS'
from
INFORMATION_SCHEMA.COLUMNS where table_name = 'users'
set @custom_sql = 'SELECT ' + @custom_sql
set @custom_sql = @custom_sql + ' FROM Users'
print @custom_sql
exec(@custom_sql)
答案 1 :(得分:0)
我不知道如何制作通用查询,但您始终可以像这样生成脚本
declare @sql nvarchar(max) = 'select 1 as dummy'
select @sql = @sql + '
, sum(case when [' + c.name + '] is null then 1 else 0 end) as [' + c.name + '_NULLS]'
from sys.columns c
join sys.tables t on t.object_id = c.object_id
where t.name = 'TABLE1'
set @sql = @sql + ' from TABLE1'
select @sql
然后你可以执行结果,例如。与exec sp_executesql @sql
答案 2 :(得分:0)
对于更酷的方法,您可以使用ISNULL跳过第一个逗号。
declare @sql nvarchar(max)
declare @tablename nvarchar(255) = 'xxxx'
Select @sql = ISNULL(@SQL + ',','') + ' ' + COLUMN_NAME + '_count = Sum(case when ' + COLUMN_NAME + ' is null then 1 else 0 end)' + char(13)
From information_schema.columns
where table_name = @tablename
set @sql = 'Select' + @sql + ' From ' + @tablename
print @sql
exec sp_executesql @sql