After large redesigning of DB I need to remove all indices from it, and set new indices.
I found good scrpipt to get all indices and remove but I have problem – I cannot remove indices created by PRIMARY KEY constraint. (maybe there are also other kind of indices that I cannot remove).
My question is: how to change code below to remove all indices except indices created for primary keys or other that I cannot remove manually.
DECLARE @indexName VARCHAR(128)
DECLARE @tableName VARCHAR(128)
DECLARE [indexes] CURSOR FOR
SELECT [sysindexes].[name] AS [Index], [sysobjects].[name] AS [Table]
FROM [sysindexes]
INNER JOIN [sysobjects] ON [sysindexes].[id] = [sysobjects].[id]
WHERE [sysindexes].[name] IS NOT NULL AND [sysobjects].[type] = 'U'
OPEN [indexes]
FETCH NEXT FROM [indexes] INTO @indexName, @tableName
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC ('DROP INDEX [' + @indexName + '] ON [' + @tableName + ']')
FETCH NEXT FROM [indexes] INTO @indexName, @tableName
END
CLOSE [indexes]
DEALLOCATE [indexes]
Based on Marc_s answer I found correct version of script:
Checking if object_Id is greater than 255 isn’t sufficient:
– we had to use OBJECTPROPERTY(object_id, ‘IsMSShipped’) = 0, because some system tables like queue_messages have very high id
– also we have to check if index is created by unique constraint : is_unique_constraint = 0
After those improvements it’ll remove all indices created by user.