我有很多带外键的表,有些表有索引,有些表没有。
所有外键都名为FK_<name of the foreign key>
,索引名为IX_<name of the foreign key>
。
考虑到外键的列基数,创建(或不创建)索引是否有一些好的做法? 这可以作为T-SQL命令编写脚本吗?
答案 0 :(得分:37)
它们是通过T-SQL脚本还是通过Designer创建的并不重要。你的问题有点含糊不清,所以我不确定你是否也在询问是否可以索引所有的外键。但是,如果是,则应在查询中经常引用的列上创建索引,并且可以执行以下操作以提高性能:
运行数据库调优向导,该向导将提供改进摘要和推荐索引。
索引所有外键并运行执行计划(查看查询执行速度是否更快或更慢)。
通过T-SQL
创建索引:
CREATE INDEX IX_INDEX_NAME
ON Table (FieldName);
获取所有外键的列表:
SELECT f.name AS ForeignKey,
OBJECT_NAME(f.parent_object_id) AS TableName,
COL_NAME(fc.parent_object_id, fc.parent_column_id) AS ColumnName,
OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,
COL_NAME(fc.referenced_object_id, fc.referenced_column_id) AS ReferenceColumnName
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id
要生成一个跨所有外键应用索引的脚本,您可以这样做:
SELECT 'CREATE INDEX [IX_' + f.name + '] ON ' + OBJECT_NAME(f.parent_object_id) + '(' + COL_NAME(fc.parent_object_id, fc.parent_column_id) + ')]'
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id
答案 1 :(得分:2)
每个人都很出色,非常有帮助。
添加包含表架构的增强功能。如果您愿意,也可以排除FK名称(我倾向于不在小表上添加索引)
SELECT
*
FROM
(
SELECT TOP 99 PERCENT
f.name AS ForeignKeyName
, s.name
+ '.'
+ OBJECT_NAME(f.parent_object_id)
+ '.'
+ COL_NAME(fc.parent_object_id, fc.parent_column_id)
ParentTable
, referencedSchema.name
+ '.'
+ OBJECT_NAME (f.referenced_object_id)
+ '.'
+ COL_NAME(fc.referenced_object_id, fc.referenced_column_id)
ReferencedTable
, 'CREATE INDEX [IX_' + f.name + ']'
+ ' ON '
+ '[' + referencedSchema.name + ']'
+ '.'
+ '[' + OBJECT_NAME(f.parent_object_id) + ']'
+ '('
+ COL_NAME(fc.parent_object_id, fc.parent_column_id)
+ ')'
CreateIndexSql
FROM
sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id
inner join sys.schemas s on f.schema_id = s.schema_id
inner join sys.tables referencedTable on f.referenced_object_id = referencedTable.object_id
inner join sys.schemas referencedSchema on referencedTable.schema_id = referencedSchema.schema_id
ORDER BY
2, 3, 1
) a
where a.ParentTable not in (
-- Add any exclusions here so you can forget about them
''
)