SQL Server 会随着时间的推移自动将统计信息添加到表中,以便在解析查询和构建查询计划时使用。您必须删除统计信息才能更改列。例如:
drop statistics [dbo].[Tabl1].[_WA_Sys_Col1_5070F446]
_WA_Sys_Col1_5070F446
但是,您应该在删除之前使用 SSMS 查看统计信息中的列,以便重新创建它。像这样的东西:
create statistics [_WA_Sys_Col1_5070F446] on [dbo].[Tabl1]([Col1])
但是可能会有更多的列...,所以一定要在删除之前找出需要包含的列。
您可以运行此 SQL 来查找大多数依赖项,它不会报告统计依赖项,但它会捕获大多数其他依赖项:
SELECT OBJECT_NAME(d.object_id) AS SP_Or_Function, OBJECT_NAME(d.referenced_major_id) AS TableReferenced
FROM sys.sql_dependencies AS d INNER JOIN
sys.all_sql_modules AS m ON m.object_id = d.object_id
where OBJECT_ID(N'Tabl1') = d.referenced_major_id
GROUP BY OBJECT_NAME(d.object_id), OBJECT_NAME(d.referenced_major_id)
ORDER BY SP_Or_Function, TableReferenced
您可以使用此查询找到给定表使用的所有统计信息:
SELECT DISTINCT
OBJECT_NAME(s.[object_id]) AS TableName,
c.name AS ColumnName,
s.name AS StatName,
s.auto_created,
s.user_created,
s.no_recompute,
s.[object_id],
s.stats_id,
sc.stats_column_id,
sc.column_id,
STATS_DATE(s.[object_id], s.stats_id) AS LastUpdated
FROM sys.stats s JOIN sys.stats_columns sc ON sc.[object_id] = s.[object_id] AND sc.stats_id = s.stats_id
JOIN sys.columns c ON c.[object_id] = sc.[object_id] AND c.column_id = sc.column_id
JOIN sys.partitions par ON par.[object_id] = s.[object_id]
JOIN sys.objects obj ON par.[object_id] = obj.[object_id]
WHERE OBJECTPROPERTY(s.OBJECT_ID,'IsUserTable') = 1
AND (s.auto_created = 1 OR s.user_created = 1)
AND object_id(N'Tabl1') = s.[object_id]
感谢最后两个 SQL 查询的 SQLAuthority:
SQL SERVER – 获取对象依赖列表 – sp_depends 和 information_schema.routines 和 sys.dm_sql_referencing_entities(Gabriel 的帖子)
SQL SERVER – 查找整个数据库统计信息的详细信息 – DMV – T-SQL 脚本