[英]Drop empty column SQL Server
我需要删除给定表的所有空列。
就像任何表格一样,我不知道列的名称。
例如输入表为table1:
ID | 值 1 | 值2 | 值3 | 值4 |
---|---|---|---|---|
1个 | 单元格 2 | NULL | 单元格 2 | NULL |
2个 | 单元格 4 | NULL | 单元格 4 | NULL |
output 表应该是:
ID | 值 1 | 值3 |
---|---|---|
1个 | 单元格 2 | 单元格 2 |
2个 | 单元格 4 | 单元格 4 |
你可以试试看。
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;
nullif 子句检查是否有任何严格为空的字段,如果要包含 null 值,则必须删除 nullif。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.