如何获取表中具有空值并且也没有任何列名的行?

时间:2018-12-14 09:18:28

标签: sql-server-2008

我有一张桌子,如下表

create table col(id int,name varchar(max))
insert into col values(1,'n1'),(2,'n2'),(3,'n3'),(4,null)

我需要第四行的输出,该行具有空值。但是我不知道表中的列名,我只知道表名。

您能帮忙解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

这是奇怪的情况。为什么根本需要这样做?但是无论如何,您可以从sys.syscolumns表中获取列的名称,并构造一个动态查询来检查每列是否为空,如下所示:

select * from col where 1=2 or id is null or name is null

整个查询可能如下:

create table col(id int,name varchar(max))
insert into col values(1,'n1'),(2,'n2'),(3,'n3'),(4,null)

declare @TableName sysname = N'col'

declare @sql nvarchar(max) = N'select * from ' + @TableName + ' where 1=2';

select @sql += ' or ' + name + ' is null'
from sys.syscolumns
where id = object_id(@TableName) and isnullable = 1

-- print @sql
exec sp_executesql @sql