views:

83

answers:

2

I need to check if this index not exist in specific table name not in all tables because this select statement select all indexes under this condition.

IF NOT EXISTS (SELECT name from sysindexes WHERE name = 'IDX_InsuranceID')

CREATE NONCLUSTERED INDEX [IDX_InsuranceID] ON [dbo].[QuoteInsurances] 
(
    [InsuranceID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 80) ON [PRIMARY]
GO

Thanks,

+2  A: 

Your check is okay, I would change two things:

  • use the sys.indexes system catalog view (if you're on SQL Server 2005 or newer) instead of the older, deprecated sysindexes system table

  • add a check to the object_id (the link to the table) to your query

Something like this:

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'IDX_InsuranceID' 
               AND object_id = OBJECT_ID('your-table-name-here'))
   -- do whatever you need to do here.....
marc_s
+1, but it's worth schema-scoping the OBJECT_ID check - i.e. OBJECT_ID('[schema-name].[table-name]')
Matt Whitfield
A: 

If I understand correctly no 2 indexes in the entire database can have the same name, so I think you're safe. If you think I'm incorrect, try to create two indexes on different tables with the same name and see what happens...

Jeremy
I think u aren't right because u can make two indexes under same name in the entire database one for each table. because of that i asked that question.
Amr Elnashar
You are correct. I learned something today. What I was thinking of was constraints (http://msdn.microsoft.com/en-us/library/aa258255(SQL.80).aspx). They are unique to the database, but index names are unique to the table. (http://msdn.microsoft.com/en-us/library/aa258260(SQL.80).aspx)
Jeremy