我遇到过一个数据库,其表太宽。 (600+ 列)即使在没有参数的情况下询问前 100 行也需要 4 秒。我想把这些桌子缩小一点。
为了弄清楚哪些列可以最容易地移动到新表或完全删除,我想知道每列中有多少个空值。这应该告诉我哪些信息可能最不重要。
我将如何编写一个查询来查找所有列并计算这些列中的空值?
Edit数据库是 SQL Server 2008。我是really希望不要单独键入每一列。看起来 sys.columns 可以帮助解决这个问题?
Edit2这些列都是不同类型的。
Try this
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)