TSQL - Find All Empty Columns in a Database


/ Published in: SQL
Save to your folder(s)

I found this and simply want to store it. It was done by Valentino Vranken


Copy this code and paste it in your HTML
  1. -- Returns a list of all columns in current database
  2. -- where the column's value is null for all records.
  3. DECLARE @tempTable TABLE
  4. (
  5. TableSchema nvarchar(256),
  6. TableName nvarchar(256),
  7. ColumnName sysname,
  8. NotNullCnt BIGINT
  9. );
  10.  
  11. DECLARE @SQL nvarchar(4000);
  12. DECLARE @tableSchema nvarchar(256);
  13. DECLARE @tableName nvarchar(256);
  14. DECLARE @columnName sysname;
  15. DECLARE @cnt BIGINT;
  16.  
  17. DECLARE columnCursor cursor FOR
  18. SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
  19. WHERE IS_NULLABLE = 'YES';
  20.  
  21. OPEN columnCursor;
  22.  
  23. fetch NEXT FROM columnCursor INTO @tableSchema, @tableName, @columnName;
  24.  
  25. while @@FETCH_STATUS = 0
  26. BEGIN
  27. -- use dynamic sql to get count of records where column is not null
  28. SET @SQL = 'select @cnt = COUNT(*) from [' + @tableSchema + '].[' + @tableName +
  29. '] where [' + @columnName + '] is not null';
  30. -- print @sql; --uncomment for debugging
  31. EXEC sp_executesql @SQL, N'@cnt bigint output', @cnt = @cnt output;
  32.  
  33. INSERT INTO @tempTable SELECT @tableSchema, @tableName, @columnName, @cnt;
  34.  
  35. fetch NEXT FROM columnCursor INTO @tableSchema, @tableName, @columnName;
  36. END
  37.  
  38. close columnCursor;
  39. deallocate columnCursor;
  40.  
  41. SELECT * FROM @tempTable WHERE NotNullCnt = 0;

URL: http://blog.hoegaerden.be/2009/02/15/script-find-all-empty-columns-in-database/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.