我在SQL Server中有一个包含369列的表。
在这369个列中,127列的类型为date
,其中127个日期列中的一些列在所有行中都有null
个值。
如何获取所有行中包含date
值的NULL
列的列表?
答案 0 :(得分:0)
这可能是非常耗费资源的操作,具体取决于表的大小,但这应该这样做:
生成一些SQL:
select
TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, column_name, DATA_TYPE, IS_NULLABLE,
cmd = 'case when count(*)=sum(case when [' + COLUMN_NAME + '] is null then 1 else 0 end) then 1 else 0 end as [' + COLUMN_NAME + '__isAllNulls],'
from information_schema.columns
where 1=1
and DATA_TYPE like '%date%'
and TABLE_NAME = '<yourtablename>'
然后写下选择:
select
<paste CMD from above results>
from <yourtablename>
EDIT2:粘贴生成的CMD列后的样本最终查询将如下所示:
select
case when count(*)=sum(case when [DateAdded] is not null then 1 else 0 end) then 1 else 0 end as [DateAdded__isAllNulls],
case when count(*)=sum(case when [DateModified] is null then 1 else 0 end) then 1 else 0 end as [DateModified__isAllNulls],
case when count(*)=sum(case when [DateClosed] is null then 1 else 0 end) then 1 else 0 end as [DateClosed__isAllNulls]
from yourtable
结果应该是这样的:
DateAdded__isAllNulls DateModified__isAllNulls DateClosed__isAllNulls
1 0 0
编辑:简单min()
或max()
会比我的case when count(*)=sum(case ...
好,正如@Damien_the_Unbeliever在评论中所建议的那样,但您仍然可以使用我的代码来生成sql。