Find fields that aren't used (have all nulls)

前端 未结 3 608
一生所求
一生所求 2020-12-22 10:21

I\'ve inherited a legacy database, and many, many fields are no longer being used. I can tell by querying on the last couple of years and seeing which fields are null, to at

相关标签:
3条回答
  • 2020-12-22 11:06

    This gives you the count of all records with NULL fields which you can compare to the count of all the records

    SELECT COUNT(*)
    FROM Table1
    WHERE COALESCE (Field1, Field2, etc) IS NULL
    
    0 讨论(0)
  • 2020-12-22 11:13

    Is this what you need?

      SELECT count(*)
      FROM table
      WHERE field IS NULL
    

    or of course

     SELECT SUM(CASE WHEN field IS NULL THEN 1 ELSE 0 END) AS [field is null count]
            COUNT(*) as [total count]
     FROM table
    

    also works and you can do it for a bunch of fields at once.


    Stealing Aaron Bertrand's template:

    DECLARE @tableName NVARCHAR(512)
    
    SET @tableName = N'dbo.tablename';
    
    DECLARE @sql NVARCHAR(MAX);
    
    SELECT @sql = N'';
    
    SELECT @sql = @sql + N' SUM(CASE WHEN ' + QUOTENAME(name) + ' IS NULL THEN 1 ELSE 0 END) AS ['+name+' null count], '
    FROM sys.columns
    WHERE object_id = OBJECT_ID(@tableName) AND is_nullable = 1;
    
    SELECT @sql = 'SELECT ' + @sql + ' Total_Count = COUNT(*)
    FROM ' + @tableName + ';';
    
    EXEC sp_executesql @sql;
    
    0 讨论(0)
  • 2020-12-22 11:19
    DECLARE @table NVARCHAR(512);
    SET @table = N'dbo.tablename';
    
    DECLARE @sql NVARCHAR(MAX);
    
    SELECT @sql = N'';
    
    SELECT @sql = @sql + QUOTENAME(name) 
         + ' = SUM(CASE WHEN ' + QUOTENAME(name) + ' IS NULL THEN 1 ELSE 0 END),'
      FROM sys.columns
      WHERE object_id = OBJECT_ID(@table)
      AND is_nullable = 1;
    
    SELECT @sql = 'SELECT ' + @sql + ' Total_Count = COUNT(*)
      FROM ' + @table + ';';
    
    EXEC sp_executesql @sql;
    

    Any columns that come out 0 have all nulls (unless the Total_Count column also comes out 0, in which case the table is empty). Note that this query will be pretty expensive on a large table.

    0 讨论(0)
提交回复
热议问题