Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find all columns that are filled with 100% nulls in my SQL Server database schema?

Is there a SQL way to find out which columns in my schema are completely full of null values? There are some fields in a couple of tables that I know are not used by the application and will be dropped, but I wanted to see if there was an automated way/script to find this out across the whole database to find candidates for code review/possible removal.

Running SQL Server 2005 on x86 if it matters.

Thanks in advance!

like image 514
Mark A Avatar asked Oct 20 '10 15:10

Mark A


1 Answers

create table #SuspectColumns (
    TABLE_SCHEMA sysname,
    TABLE_NAME sysname,
    COLUMN_NAME sysname
)

declare csrColumns cursor fast_forward for
    select TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME
        from INFORMATION_SCHEMA.COLUMNS
        where IS_NULLABLE = 'YES'

declare @TABLE_SCHEMA sysname,
        @TABLE_NAME sysname,
        @COLUMN_NAME sysname,
        @sql nvarchar(max)  

open csrColumns

while (1=1) begin
    fetch next
        from csrColumns
        into @TABLE_SCHEMA, @TABLE_NAME, @COLUMN_NAME

    if @@FETCH_STATUS<>0 break

    set @sql = N'if not exists(select 1 from ' + QUOTENAME(@TABLE_SCHEMA) + N'.' + QUOTENAME(@TABLE_NAME) + N' where ' + QUOTENAME(@COLUMN_NAME) + N'is not null)
                     insert into #SuspectColumns values (''' + @TABLE_SCHEMA + N''',''' + @TABLE_NAME + N''',''' + @COLUMN_NAME + N''')'

    exec sp_executesql @sql
end /* while */

close csrColumns
deallocate csrColumns

select * from #SuspectColumns

drop table #SuspectColumns
like image 155
Joe Stefanelli Avatar answered Sep 27 '22 22:09

Joe Stefanelli