我必须编写一个SQL脚本来比较SQL Server上两个表的索引之间的差异。如何通过SQL查询获取表的索引结构?
答案 0 :(得分:4)
如果两个数据库位于同一服务器上,那么您可以执行一系列外部连接两个数据库上的sys.indexes和sys.index_columns表的查询。您还需要查看sys.index_columns以检查列是否相同(同时检查相同的顺序 - 这将影响查询计划)。
如果两个数据库都在不同的服务器上,则需要将sys.indexes和sys.index_columns的内容复制到另一台服务器上,并对表的副本执行类似的查询。
此类查询的示例可能如下所示(如果要查看单个表,请将适当的数据库替换为FOO和BAR,并为各个查询添加适当的过滤器):
select *
from
(select s1.name as SchemaName
,t1.name as TableName
,c1.name as ColumnName
,i1.name as IndexName
,i1.index_id
,c1.column_id
,c1.system_type_id
,c1.user_type_id
,ty1.name as ColumnType
,c1.collation_name -- Note this is nullable
,c1.is_nullable
,c1.max_length
,c1.[precision]
,c1.scale
,ic1.index_column_id
,ic1.key_ordinal
,ic1.partition_ordinal
,ic1.is_descending_key
,ic1.is_included_column
from [FOO].sys.schemas s1
join [FOO].sys.tables t1
on t1.schema_id = s1.schema_id
join [FOO].sys.columns c1
on t1.object_id = c1.object_id
join [FOO].sys.types ty1
on ty1.system_type_id = c1.system_type_id
and ty1.user_type_id = c1.user_type_id
join [FOO].sys.index_columns ic1
on ic1.object_id = c1.object_id
and ic1.column_id = c1.column_id
join [FOO].sys.indexes i1
on i1.object_id = ic1.object_id
and i1.index_id = ic1.index_id) r1
full outer join
(select s1.name as SchemaName
,t1.name as TableName
,c1.name as ColumnName
,i1.name as IndexName
,i1.index_id
,c1.column_id
,c1.system_type_id
,c1.user_type_id
,ty1.name as ColumnType
,c1.collation_name -- Note this is nullable
,c1.is_nullable
,c1.max_length
,c1.[precision]
,c1.scale
,ic1.index_column_id
,ic1.key_ordinal
,ic1.partition_ordinal
,ic1.is_descending_key
,ic1.is_included_column
from [BAR].sys.schemas s1
join [BAR].sys.tables t1
on t1.schema_id = s1.schema_id
join [BAR].sys.columns c1
on t1.object_id = c1.object_id
join [BAR].sys.types ty1
on ty1.system_type_id = c1.system_type_id
and ty1.user_type_id = c1.user_type_id
join [BAR].sys.index_columns ic1
on ic1.object_id = c1.object_id
and ic1.column_id = c1.column_id
join [BAR].sys.indexes i1
on i1.object_id = ic1.object_id
and i1.index_id = ic1.index_id) r2
on r1.SchemaName = r2.SchemaName
and r1.TableName = r2.TableName
and r1.ColumnName = r2.ColumnName
and r1.IndexName = r2.IndexName
答案 1 :(得分:1)
sys.indexes保存有关给定数据库上索引的所有信息。
答案 2 :(得分:0)
如果您想要的只是结构,则可以使用此procedure生成脚本。
然后,您可以比较两个数据库之间的文件。