Count the Null columns in a row in SQL

后端 未结 13 775
小蘑菇
小蘑菇 2020-11-30 04:36

I was wondering about the possibility to count the null columns of row in SQL, I have a table Customer that has nullable values, simply I want a query that return an int of

13条回答
  •  无人及你
    2020-11-30 05:15

    My answer builds on Drew Chapin's answer, but with changes to get the result using a single script:

    use ;
    Declare @val Varchar(MAX); 
    
    Select @val = COALESCE(@val + str, str) From 
        (SELECT
        '(CASE WHEN '+COLUMN_NAME+' IS NULL THEN 1 ELSE 0 END) +' str
        FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ''
        ) t1 -- getting column names and adding the case when to replace NULLs for zeros or ones
        
    Select @val = SUBSTRING(@val,1,LEN(@val) - 1) -- removing trailling add sign
        
    Select @val = 'SELECT , ' + @val + ' AS NullCount FROM ' -- adding the 'select' for the column identity, the 'alias' for the null count column, and the 'from'
    
    EXEC (@val) --executing the resulting sql
    

提交回复
热议问题