Created
May 6, 2013 17:11
-
-
Save GeorgeDellinger/5526474 to your computer and use it in GitHub Desktop.
Find unused Sql columns
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SET NOCOUNT ON | |
declare @tempTable table | |
( | |
TableSchema nvarchar(256), | |
TableName nvarchar(256), | |
ColumnName sysname | |
); | |
declare @sql nvarchar(4000); | |
declare @tableSchema nvarchar(256); | |
declare @tableName nvarchar(256); | |
declare @columnName sysname; | |
declare @cnt bigint; | |
declare @RowCount int; | |
declare columnCursor cursor for | |
select c.TABLE_SCHEMA, c.TABLE_NAME, c.COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS c | |
inner join | |
INFORMATION_SCHEMA.TABLES t on c.TABLE_NAME = t.TABLE_NAME | |
where c.IS_NULLABLE = 'YES' and t.TABLE_TYPE = 'BASE TABLE' and DATA_TYPE <> 'IMAGE' and DATA_TYPE <> 'NTEXT' and DATA_TYPE <> 'TEXT' --and t.TABLE_NAME = 'Users'; | |
open columnCursor; | |
fetch next from columnCursor into @tableSchema, @tableName, @columnName; | |
while @@FETCH_STATUS = 0 | |
begin | |
-- use dynamic sql to get count of records where column is not null | |
set @sql = 'select @cnt = COUNT([' + @columnName + ']) from [' + @tableSchema + '].[' + @tableName +'] having count([' + @columnName + ']) = 0; '; | |
--print @sql; --uncomment for debugging | |
exec sp_executesql @sql, N'@cnt bigint output', @cnt = @cnt output; | |
set @RowCount = @@RowCount | |
if (@RowCount = 1) | |
insert into @tempTable select @tableSchema, @tableName, @columnName; | |
fetch next from columnCursor into @tableSchema, @tableName, @columnName; | |
end; | |
close columnCursor; | |
deallocate columnCursor; | |
select * from @tempTable |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment