选择没有空值的行

时间:2012-08-17 07:03:07

标签: sql-server-2008 select

在sql数据库中我需要一个脚本来选择所有没有null值的行:

For all the rows in the database
     if row has no null values
         select it

列是动态的,我无法知道它们的编号或名称

谢谢你

2 个答案:

答案 0 :(得分:3)

这与此问题Test if any fields are NULL相反。

Martin Smith修改后找到没有空值的行的答案将如下所示。

;with xmlnamespaces('http://www.w3.org/2001/XMLSchema-instance' as ns)
select *
from YourTable as T
where
  (
    select T.*
    for xml path('row'), elements xsinil, type 
  ).exist('//*/@ns:nil') = 0

修改Aaron Bertrand提供的答案将是......

DECLARE @tb NVARCHAR(255) = N'YourTable';

DECLARE @sql NVARCHAR(MAX) = N'SELECT * FROM ' + @tb
    + ' WHERE 1 = 1';

SELECT @sql += N' AND ' + QUOTENAME(name) + ' IS NOT NULL'
    FROM sys.columns 
    WHERE [object_id] = OBJECT_ID(@tb);

EXEC sp_executesql @sql;

答案 1 :(得分:0)

方法:

  • 从sys.columns
  • 获取表的列名
  • 使用多个WHERE条件进行选择ANDed:WHERE ColA IS NOT NULL且ColB IS NOT NULL等等......
相关问题