Count number of NULL values in each column in SQL

前端 未结 4 403
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: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
    

提交回复
热议问题