计算SQL中每列中的NULL值数

时间:2014-06-25 14:17:53

标签: sql sql-server

我正在尝试编写一个脚本,该脚本将显示每列中的非空值的数量以及表中的总行数。

我找到了几种方法:

SELECT sum(case my_column when null then 1 else 0) "Null Values", sum(case my_column when null then 0 else 1) "Non-Null Values" FROM my_table;

SELECT count(*) FROM my_table WHERE my_column IS NULL UNION ALL SELECT count(*) FROM my_table WHERE my_column IS NOT NULL

但这些要求我手动输入每个列名。有没有办法为每个列执行此操作而不列出它们?

4 个答案:

答案 0 :(得分:8)

您应该使用execute

DECLARE @t nvarchar(max)
SET @t = N'SELECT '

SELECT @t = @t + 'sum(case when ' + c.name + ' is null then 1 else 0 end) "Null Values for ' + c.name + '",
                sum(case when ' + c.name + ' is null then 0 else 1 end) "Non-Null Values for ' + c.name + '",'
FROM sys.columns c 
WHERE c.object_id = object_id('my_table');

SET @t = SUBSTRING(@t, 1, LEN(@t) - 1) + ' FROM my_table;'

EXEC sp_executesql @t

答案 1 :(得分:2)

可能是这个作品

select count(case when Column1 is null then 1 end) as Column1NullCount,
    count(case when Column2 is null then 1 end) as Column2NullCount,
    count(case when Column3 is null then 1 end) as Column3NullCount
    ...
from My_Table

答案 2 :(得分:1)

你可以使用动态的sql和sys表 根据您使用的sql版本,语法会略有变化,但这些步骤如下:
- list the columns读取sys.columns并将列表保存在临时表或表变量中 - 在临时表中循环并使用您手动应用的相同逻辑构建sql - 使用sp_executesql

执行上一步构建的动态sql

答案 3 :(得分:1)

正如Paolo所说,但这是一个例子:

DECLARE @TableName VARCHAR(512) = 'invoiceTbl';
DECLARE @SQL VARCHAR(1024);
WITH SQLText AS (
    SELECT 
        ROW_NUMBER() OVER (ORDER BY c.Name) AS RowNum,
        'SELECT ''' + c.name + ''', SUM(CASE WHEN ' + c.Name + ' IS NULL THEN 1 ELSE 0 END) AS NullValues FROM ' + @TableName AS SQLRow
    FROM 
        sys.tables t 
        INNER JOIN sys.columns c ON c.object_id = t.object_id
    WHERE 
        t.name = @TableName),
Recur AS (
    SELECT
        RowNum,
        CONVERT(VARCHAR(MAX), SQLRow) AS SQLRow
    FROM
        SQLText
    WHERE
        RowNum = 1
    UNION ALL
    SELECT
        t.RowNum,
        CONVERT(VARCHAR(MAX), r.SQLRow + ' UNION ALL ' + t.SQLRow)
    FROM
        SQLText t
        INNER JOIN Recur r ON t.RowNum = r.RowNum + 1
    )
SELECT @SQL = SQLRow FROM Recur WHERE RowNum = (SELECT MAX(RowNum) FROM Recur);
EXEC(@SQL);