[英]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 ![]() |
Value1![]() |
Value2![]() |
Value3![]() |
Value4![]() |
---|---|---|---|---|
1 ![]() |
Cell 2![]() |
NULL ![]() |
Cell 2![]() |
NULL ![]() |
2 ![]() |
Cell 4![]() |
NULL ![]() |
Cell 4![]() |
NULL ![]() |
The output table should be: output 表应该是:
Id ![]() |
Value1![]() |
Value3![]() |
---|---|---|
1 ![]() |
Cell 2![]() |
Cell 2![]() |
2 ![]() |
Cell 4![]() |
Cell 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.