Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to drop all of the indexes except primary keys with single query

I am planning to drop all of the indexes except the primary keys. I made the primary keys myself but all other indexes was suggestion of SQL Server.

After dropping all indexes which are not primary keys, planning to use SQL Server profiler tuning template for database tuning advisor and create indexes.

With this way planning to not have unused indexes or performance degrading indexes.

How logical is this ? Thank you.

like image 349
MonsterMMORPG Avatar asked Sep 23 '11 13:09

MonsterMMORPG


2 Answers

DECLARE @sql NVARCHAR(MAX) = N'';

SELECT @sql += N'DROP INDEX ' 
    + QUOTENAME(SCHEMA_NAME(o.[schema_id]))
    + '.' + QUOTENAME(o.name) 
    + '.' + QUOTENAME(i.name) + ';'
    FROM sys.indexes AS i
    INNER JOIN sys.tables AS o
    ON i.[object_id] = o.[object_id]
WHERE i.is_primary_key = 0
AND i.index_id <> 0
AND o.is_ms_shipped = 0;

PRINT @sql;
-- EXEC sp_executesql @sql;
like image 86
Aaron Bertrand Avatar answered Nov 15 '22 06:11

Aaron Bertrand


The easiest way is probably this: run this query which will output a list of DROP INDEX ..... statements.

SELECT 
   'DROP INDEX ' + name + ' ON ' + 
   OBJECT_SCHEMA_NAME(object_id) + '.' + OBJECT_NAME(object_Id) 
FROM sys.indexes
WHERE is_primary_key = 0
AND name IS NOT NULL
AND OBJECT_SCHEMA_NAME(object_id) <> 'sys'

Copy those DROP statements from the results grid to a new query window, check them, maybe tweak them, and then run them to actually drop the indices.

like image 31
marc_s Avatar answered Nov 15 '22 07:11

marc_s