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
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