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

為{幸葍}努か 提交于 2019-12-07 09:48:39

问题


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.


回答1:


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;



回答2:


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.



来源:https://stackoverflow.com/questions/7530103/how-to-drop-all-of-the-indexes-except-primary-keys-with-single-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!