2012-05-24 95 views
15

我有很多帶有外鍵的表,有些表有索引,而有些表沒有。 所有外鍵名爲FK_<name of the foreign key>,索引名爲IX_<name of the foreign key>sql server:在必要時在外鍵上創建索引

是否有一些良好的做法,給定外鍵的列基數,以創建(或不)索引? 這可以作爲T-SQL命令腳本嗎?

+0

我想你需要澄清你的問題,請參見本觀察達倫的回答是:*「你的問題是有點曖昧,所以我不確定你是否也在問索引所有的外鍵是否可以。「* – Kev

回答

32

無論它們是通過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 

http://msdn.microsoft.com/en-us/library/ms188783.aspx

+0

我澄清了這個問題,我想用T-SQL腳本來做這件事 – psadac

+0

@psadac - 更新了我的文章。 –

+0

'爲了生成一個跨所有外鍵應用索引的腳本 - 那麼具有某種基數的外鍵呢? –

0

偉大的工作每個人,非常有幫助。

添加包含表模式的增強功能。您還可以排除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 
     '' 
)