我有一个Microsoft SQL Server表,让我们说它有10列。这些列中的一个或多个可以包含ALL null值。我如何构造一个简单的SELECT *
查询来排除ALL值为null的列?
答案 0 :(得分:1)
我不相信有一个简单的“SELECT * FROM [TABLE]”查询会根据结果集中列中包含的所有值排除列。 select子句定义了要返回的数据,from子句告诉它..well from,以及where子句在行级提供过滤条件。
您正在谈论的查询几乎肯定会被写入,但从[table]中选择*不是一个简单的。
答案 1 :(得分:1)
我为一个有三列的表做了这个(我假设至少有一列确实有数据)。您可以根据需要将其扩展到尽可能多的列:
declare @strsql varchar(2500)
set @strsql = 'select '
set @strsql +=
(select case when (select COUNT(*) from #t1 where ean2 is null) <> (select count(*) from #t1) then 'ean2, ' else '' end)
set @strsql +=
(select case when (select COUNT(*) from #t1 where ean1 is null) <> (select count(*) from #t1) then 'ean1, ' else '' end)
set @strsql +=
(select case when (select COUNT(*) from #t1 where list_price is null) <> (select count(*) from #t1) then 'list_price, ' else '' end)
-- get rid of trailing ,
set @strsql = LEFT(@strsql,len(@strsql) -1)
--add table to select from
set @strsql += ' from #t1'
exec (@strsql)