簡體   English   中英

刪除空列 SQL 服務器

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM