82

我有以下内容:

CREATE NONCLUSTERED INDEX [MyTableIndex]
ON [dbo].[tablename] ([tablename_ID],[tablename_Field1])
INCLUDE ([Tablename_Field2],[Tablename_Field3])

我想创建一个 if 语句来检查它是否存在。我该怎么做呢?

4

2 回答 2

183
IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'MyTableIndex' AND object_id = OBJECT_ID('tablename'))
    BEGIN
        -- Index with this name, on this table does NOT exist
    END
于 2011-05-03T14:35:28.347 回答
18

尝试这个:

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE Name = 'MyTableIndex')
   -- put your CREATE INDEX statement here
于 2011-05-03T14:35:05.167 回答