删除多列为空

时间:2019-03-14 07:04:37

标签: sql sql-server tsql null where-clause

我有一个包含34列的表格。 前4列构成主键(因此它们中没有空),其余30列中的数据也为空。 我希望删除其他30列为空的所有行。 一种方法是-

delete from my_table
where column_30 is null
and columns_29 is null
and column_28 is null
and column_27 is null
...
...
...

有什么简单的方法可以不提及所有30个列名?

3 个答案:

答案 0 :(得分:2)

不,那是不可能的。您可以使用penalty in sargability来缩短代码长度,但要花coalesce

delete from my_table
where coalesce(column_30, column_29, column_28.....) is null

如Damien在他的评论中所写-仅当所有列都具有兼容类型时,这才起作用,这意味着SQL Server可以在它们之间进行隐式转换。

答案 1 :(得分:1)

coalesce接收一个表达式列表,并返回第一个非空表达式,如果全部为空,则返回null,因此您可以将其用作某种速记形式:

DELETE FROM mytable
WHERE  COALESCE(column_30, column_29, column_28, ...) IS NULL

答案 2 :(得分:0)

另一种方法。 (假设所有列的数据类型相同)

delete t 
from   my_table t 
where  (select top 1 1 as col 
        from   (values  (T.column_30), 
                        (T.columns_29), 
                        (T.columns_28 ), 
                        (T.columns_27 )) v(x) 
        where  x is null) = 1