Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
denis_the_thief
Aged Yak Warrior
596 Posts |
Posted - 2009-11-17 : 09:17:03
|
| Does anyone have a query that will return all Columns which are Foreign Keys, which are not indexed? Or some other means of determining these Columns? We're having a few speed issues and sometimes we spend all this time tracing and then find out there is a missing index on a Foreign Key.In any event, I'm going to start working on it and if I come up with something, I'll post it. |
|
|
tkizer
Almighty SQL Goddess
38200 Posts |
Posted - 2009-11-17 : 13:08:13
|
Here's what I have in my toolbox:--Create non clustered indexes for all foreign key references in the databaseSELECT 'CREATE NONCLUSTERED INDEX [IX_' + tablename + '_' + columnname +'] ON [dbo].[' + tablename + '] ( [' + columnname + '] ASC)'FROM ( --Script all foreign key columns that are not already an index -- SELECT-- o.name AS tablename, cols.name AS columnName FROM sys.foreign_key_columns fc-- inner join sys.objects o on fc.parent_object_id = o.object_id-- inner join sys.columns cols on cols.object_id = o.object_id and fc.parent_column_id = cols.column_id-- EXCEPT SELECT o.name AS tablename, cols.name AS columnName FROM sys.index_columns icols inner join sys.objects o on icols.object_Id = o.object_id inner join sys.columns cols on cols.object_id = o.object_id and icols.column_id = cols.column_id where icols.index_column_id = 1) T ORDER BY tablename, columnname Tara KizerMicrosoft MVP for Windows Server System - SQL Serverhttp://weblogs.sqlteam.com/tarad/Subscribe to my blog"Let's begin with the premise that everything you've done up until this point is wrong." |
 |
|
|
denis_the_thief
Aged Yak Warrior
596 Posts |
Posted - 2009-11-18 : 13:58:50
|
| Thankyou.By giving me the create statments as well, I got even more than what I asked for. |
 |
|
|
Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)
7020 Posts |
Posted - 2009-11-18 : 14:29:14
|
| That problem is a bit harder to solve if your foreign keys are made up of multiple columns because you need to make sure that you have an index that exactly matches each column in the FK in the same order, column by column.CODO ERGO SUM |
 |
|
|
tkizer
Almighty SQL Goddess
38200 Posts |
|
|
|
|
|