简体   繁体   English

删除空列 SQL 服务器

[英]Drop empty column SQL Server

I need to remove all the empty column for a given table.我需要删除给定表的所有空列。
As it could by any table, I do not know the name of the columns.就像任何表格一样,我不知道列的名称。

For example, the input table is table1:例如输入表为table1:

Id ID Value1值 1 Value2值2 Value3值3 Value4值4
1 1个 Cell 2单元格 2 NULL NULL Cell 2单元格 2 NULL NULL
2 2个 Cell 4单元格 4 NULL NULL Cell 4单元格 4 NULL NULL

The output table should be: output 表应该是:

Id ID Value1值 1 Value3值3
1 1个 Cell 2单元格 2 Cell 2单元格 2
2 2个 Cell 4单元格 4 Cell 4单元格 4

You can try that.你可以试试看。

set @sql = null;

select concat_ws(', ',
    case when count(nullif(ID, ''))       > 0 then 'ID'       end,
    case when count(nullif(Value1, '')) > 0 then 'Value1' end,
    case when count(nullif(Value2, ''))    > 0 then 'Value2'    end,
    case when count(nullif(Value3, ''))         > 0 then 'Value3'         end,
    case when count(nullif(Value4, ''))    > 0 then 'Value4'    end
) into @sql
from table1 ;

set @sql = concat('select ', @sql, ' from imported_data where',
                 (
                    SELECT INSERT( GROUP_CONCAT('OR `', `COLUMN_NAME`, '`  != \'\' ' SEPARATOR ' '), 1, 3, '')
                    FROM `information_schema`.`COLUMNS`
                    WHERE `TABLE_SCHEMA` = 'mydb'
                        AND `TABLE_NAME` = 'table1'
                )
);  
prepare stmt from @sql;
execute stmt;
deallocate prepare stmt;

The nullif clause checks if there are any strictly empty fields, if you want to include null values you will have to remove the nullif. nullif 子句检查是否有任何严格为空的字段,如果要包含 null 值,则必须删除 nullif。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM