Count the Null columns in a row in SQL

后端 未结 13 757
小蘑菇
小蘑菇 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 Michael Berkowski's answer, but to avoid having to type out hundreds of column names, what I did was this:

    Step 1: Get a list of all of the columns in your table

    SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'myTable';
    

    Step 2: Paste the list in Notepad++ (any editor that supports regular expression replacement will work). Then use this replacement pattern

    • Search:

      ^(.*)$
      
    • Replace:

      \(CASE WHEN \1 IS NULL THEN 1 ELSE 0 END\) +
      

    Step 3: Prepend SELECT identityColumnName, and change the very last + to AS NullCount FROM myTable and optionally add an ORDER BY...

    SELECT 
        identityColumnName, 
        (CASE WHEN column001 IS NULL THEN 1 ELSE 0 END) +
        -- ...
        (CASE WHEN column200 IS NULL THEN 1 ELSE 0 END) AS NullCount
    FROM
        myTable
    ORDER BY 
        NullCount DESC
    

提交回复
热议问题