We have large MS SQL database with many tables and foreign keys. We need to index all foreign keys in our tables due to performances and we are trying to avoid do it manually. Is there any way to MS SQL do it automatically or with some tools?
MS SQL server used is MS SQL Server 2008 R2.
Thanks a lot.
Script below should help:
After selecting all foreign keys it creates indexes with name formated like 'IX_"schemaName""tableName"_"columnName"' and fillfactor = 80.
This will allow to find all the FKs and their associated columns. If one where so inclined they could write a script that tests cardinality of the tables involved and generate indexes
I'd steer you away from trying to do this automatically and encourage you to examine your system (Google missing index DMVs (SQL 2005 or later) for a good start) and create appropriate indexes instead. If you try to do this automatically, you could potentially introduce issues like:
Creating indexes on columns with low cardinality that will consume resources but never be used (e.g., a foreign key to a lookup table with a small number of possible values)
Introducing bookmark lookups because the indexes you created could have benefited from including additional columns.
I'm not saying your foreign keys should not be indexed, just that there should be some thought put into the creation of those indexes.