How to detect and remove a column that contains only null values?

后端 未结 6 2490
说谎
说谎 2020-12-30 14:50

In my table table1 there are 6 columns Locations,a,b,c,d,e.

Locations [a]   [b]   [c]  [d]   [e]

[1]       10.00 Null  Null 20.00 Null

[2]         


        
6条回答
  •  孤独总比滥情好
    2020-12-30 15:13

    Try this stored procedure with your table name as input.

    alter proc USP_DropEmptyColumns 
    
    @TableName varchar(255)
    as
    begin
    
    Declare @col varchar(255), @cmd varchar(max)
    
    DECLARE getinfo cursor for
    SELECT c.name FROM sys.tables t JOIN sys.columns c ON t.Object_ID = c.Object_ID
    WHERE t.Name = @TableName
    
    OPEN getinfo
    
    FETCH NEXT FROM getinfo into @col
    
    WHILE @@FETCH_STATUS = 0
    BEGIN
        SELECT @cmd = 'IF NOT EXISTS (SELECT top 1 * FROM [' + @TableName + '] WHERE [' + @col + '] IS NOT NULL) 
    
                            BEGIN 
                            ALTER TABLE [' + @TableName + ']  DROP Column [' + @col + ']
                            end'
        EXEC(@cmd)
    
        FETCH NEXT FROM getinfo into @col
    END
    
    CLOSE getinfo
    DEALLOCATE getinfo
    
    end
    

提交回复
热议问题