Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2008 Check if an index exists [duplicate]

Possible Duplicate:
List of all index & index columns in SQL Server DB

I would like to know if there is a way to verify if an index exists in a SQL Server database for a specific table based on the columns name:

Let's say I run the following script:

  CREATE NONCLUSTERED INDEX [MyIndexName]
  ON [dbo].[MyTable] ([CustomerId])
  INCLUDE ([Id],[ModificationDate],[ProductId])
  GO

Now I would like to check if the index exists based on the table name and columns (and the columns in the include clause), not the actual index name.

(SQL Server 2008 R2)

Thanks

like image 977
Baral Avatar asked Nov 13 '12 14:11

Baral


1 Answers

Try this query:

if exists(
           SELECT 1 
           FROM sys.indexes 
           WHERE name = 'INDEX' 
           AND object_id = OBJECT_ID('TABLENAME')
          )
 begin
 ....
 end
like image 143
Robert Avatar answered Nov 03 '22 01:11

Robert