如何检查SQL Server 2005中是否存在非聚集索引


Answers:


156
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

1
+1运作良好。是否应该关注表架构?
gotqn

10
@gotqn-要考虑架构,您可以将其作为两部分名称包含在OBJECT_ID调用中,例如OBJECT_ID('myschema.tablename')
AdaTheDev 2013年

谢谢您的解释:-]
gotqn 2013年

17

尝试这个:

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE Name = 'MyTableIndex')
   -- put your CREATE INDEX statement here

6
我建议还检查object_id(根据AdaTheDev的回答),因为索引名称不是唯一的。
mcNux 2015年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.