Count number of NULL values in each column in SQL

前端 未结 4 397
Happy的楠姐
Happy的楠姐 2020-12-10 08:07

I am trying to write a script that will show the number of non-null values in each column as well as the total number of rows in the table.

I have found a couple wa

相关标签:
4条回答
  • 2020-12-10 08:10

    you can go with dynamic sql and sys tables.
    depending on the version of sql you are using the syntax will change slightly but these are the steps:
    - list the columns reading sys.columns and save the list in a temp table or table variable
    - make a loop through that temp table and build the sql using the same logic you would apply manually
    - execute the dynamic sql built on previous step with sp_executesql

    0 讨论(0)
  • 2020-12-10 08:14

    You should use 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
    
    0 讨论(0)
  • 2020-12-10 08:30

    may be this works

    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
    
    0 讨论(0)
  • 2020-12-10 08:34

    As Paolo said, but here is an example:

    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);
    
    0 讨论(0)
提交回复
热议问题