SQL Script to create indexes for Foreign keys

http://stackoverflow.com/questions/278982/are-foreign-keys-indexed-automatically-in-sql-server

I’ve used SQL script similar to paul_nielsen’s to Create Indexes for Foreign Keys and added “if not exists” condition
DECLARE @SQL VARCHAR(max); SET @SQL = ''

SELECT @SQL = @SQL +
'if not exists (select * from sys.indexes
 where id=object_id(''' + TableName +''') and name=''Ix' + ForeignKeyName+''')
 CREATE INDEX Ix' + ForeignKeyName
    + ' ON ' + TableName + '(' + ColumnName + ');
    '
 FROM
…....

--SELECT @SQL
print @SQL
GO

At the end I would recommend to print @SQL to show all new lines correctl in messages ta of SSMS,
rather than SELECT @SQL or execute SQL

Another script can be found here(login is required): http://www.sqlservercentral.com/scripts/Index+Management/62069/

From http://msdn.microsoft.com/en-us/library/ms175464.aspx
Indexing FOREIGN KEY Constrains

Creating an index on a foreign key is often useful for the following reasons:

  • Changes to PRIMARY KEY constraints are checked with FOREIGN KEY constraints in related tables.
  • Foreign key columns are frequently used in join criteria when the data from related tables is combined in queries by matching the column or columns in the FOREIGN KEY constraint of one table with the primary or unique key column or columns in the other table. An index enables the Database Engine to quickly find related data in the foreign key table.
This article is part of the GWB Archives. Original Author: Michael Freidgeim

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.