删除许多列为null

问题描述 投票:1回答:3

我有一个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个列名称有什么简单的方法吗?

sql sql-server tsql null where-clause
3个回答
2
投票

不,那是不可能的。您可以缩短代码,但需要支付penalty in sargability - 使用coalesce

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

正如Damien在他的评论中所写 - 这只有在所有列都是兼容类型时才有效,这意味着SQL Server可以隐式地在它们之间进行转换。


1
投票

coalesce接收表达式列表并返回第一个非空表达式,如果它们都是,则返回null,因此您可以将它用作某种简写:

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

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 
© www.soinside.com 2019 - 2024. All rights reserved.