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

后端 未结 6 2514
说谎
说谎 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:26

    SQL is more about working on rows rather than columns.

    If you're talking about deleting rows where c is null, use:

    delete from table1 where c is null
    

    If you're talking about dropping a column when all rows have null for that column, I would just find a time where you could lock out the DB from users and execute one of:

    select c from table1 group by c
    select distinct c from table1
    select count(c) from table1 where c is not null
    

    Then, if you only get back just NULL (or 0 for that last one), weave your magic (the SQL Server command may be different):

    alter table table1 drop column c
    

    Do this for whatever columns you want.

    You really need to be careful if you're deleting columns. Even though they may be full of nulls, there may be SQL queries out there that use that column. Dropping the column will break those queries.

提交回复
热议问题