我遇到了表格过宽的数据库。 (600列以上)甚至要求没有参数的前100行需要4秒。我想稍微减少这些表格。计算每列中的空值数
要确定哪些列最容易移动到新表中或完全删除,我想知道每列中有多少个空值。这应该告诉我哪些信息可能是最不重要的。
我该如何编写一个查询,可以查找所有列并计算这些列内的空值?
编辑的DB在SQL Server 2008。我真的希望不单独键入每个列。它看起来像sys.columns可以帮助这个?
编辑2列是所有不同的类型。
我遇到了表格过宽的数据库。 (600列以上)甚至要求没有参数的前100行需要4秒。我想稍微减少这些表格。计算每列中的空值数
要确定哪些列最容易移动到新表中或完全删除,我想知道每列中有多少个空值。这应该告诉我哪些信息可能是最不重要的。
我该如何编写一个查询,可以查找所有列并计算这些列内的空值?
编辑的DB在SQL Server 2008。我真的希望不单独键入每个列。它看起来像sys.columns可以帮助这个?
编辑2列是所有不同的类型。
尝试此
declare @Table_Name nvarchar(max), @Columns nvarchar(max), @stmt nvarchar(max)
declare table_cursor cursor local fast_forward for
select
s.name,
stuff(
(
select
', count(case when ' + name +
' is null then 1 else null end) as count_' + name
from sys.columns as c
where c.object_id = s.object_id
for xml path(''), type
).value('data(.)', 'nvarchar(max)')
, 1, 2, '')
from sys.tables as s
open table_cursor
fetch table_cursor into @Table_Name, @Columns
while @@FETCH_STATUS = 0
begin
select @stmt = 'select ''' + @Table_Name + ''' as Table_Name, ' + @Columns + ' from ' + @Table_Name
exec sp_executesql
@stmt = @stmt
fetch table_cursor into @Table_Name, @Columns
end
close table_cursor
deallocate table_cursor
select count(case when Column1 is null then 1 end) as Column1NullCount,
count(case when Column2 is null then 1 end) as Column2NullCount,
count(case when Column3 is null then 1 end) as Column3NullCount,
...
from MyTable
例如你想找到全是空的列,所以你可以放下它们?痛苦的,但'从某些列中选择count(*),其中somecolumn是空的'一次只能做一次。 –
列是否都具有相同的数据类型? –
它们不是同一类型。数据是非常不匹配的,从驾驶执照号码到地址字段,到现金价值,到“做出的承诺”,无论如何。 – Drigan