Delete all indexes of specific database

人走茶凉 提交于 2019-12-23 02:41:01

问题


How to delete all indexes from one database, whether clustered or nonclustered?

I need do that with script, not over GUI.

EDITED

Database has 7 tables, some of them are lookups, some are related over foreign keys. Every table has minimal one index, created in time the primary key was created, so automatically was created constraint. When deleting such indexes over an GUI, I got an error that indexes cannot be deleted because of dependency on other keys.

So, I need to first delete an indexes keys that are foreign keys, and then an indexes created over primary keys.


回答1:


Slightly different variation of dynamic SQL, however it drops foreign keys first, then primary keys, then indexes (non-clustered indexes first so that you don't convert to a heap (which can affect all the non-clustered indexes)).

USE specific_database;
GO

First, delete all foreign keys:

DECLARE @sql NVARCHAR(MAX);

SET @sql = N'';

SELECT @sql = @sql + N'ALTER TABLE ' 
  + QUOTENAME(OBJECT_SCHEMA_NAME([parent_object_id]))
  + '.' + QUOTENAME(OBJECT_NAME([parent_object_id])) 
  + ' DROP CONSTRAINT ' + QUOTENAME(name) + ';
'
FROM sys.foreign_keys
WHERE OBJECTPROPERTY([parent_object_id], 'IsMsShipped') = 0;

EXEC sp_executesql @sql;

Now drop primary keys:

DECLARE @sql NVARCHAR(MAX);

SET @sql = N'';

SELECT @sql = @sql + N'ALTER TABLE '
  + QUOTENAME(OBJECT_SCHEMA_NAME([parent_object_id]))
  + '.' + QUOTENAME(OBJECT_NAME([parent_object_id])) 
  + ' DROP CONSTRAINT ' + QUOTENAME(name) + ';
'
FROM sys.key_constraints 
WHERE [type] = 'PK'
AND OBJECTPROPERTY([parent_object_id], 'IsMsShipped') = 0;

EXEC sp_executesql @sql;

And finally, indexes, non-clustered first:

DECLARE @sql NVARCHAR(MAX);

SET @sql = N'';

SELECT @sql = @sql + N'DROP INDEX ' 
  + QUOTENAME(name) + ' ON '
  + QUOTENAME(OBJECT_SCHEMA_NAME([object_id]))
  + '.' + QUOTENAME(OBJECT_NAME([object_id])) + ';
'
FROM sys.indexes 
WHERE index_id > 0
AND OBJECTPROPERTY([object_id], 'IsMsShipped') = 0
ORDER BY [object_id], index_id DESC;

EXEC sp_executesql @sql;

Note that the database engine tuning advisor will recommend a bunch of these indexes (and depending on the workload you present it, may miss some, and may suggest redundant and nearly duplicate indexes). However it is not going to recommend any of the data integrity stuff you just deleted (PK, FK, unique constraints).




回答2:


create a Dynamic SQL

DECLARE @qry nvarchar(max);
SELECT @qry =  (SELECT  'DROP INDEX ' + ix.name + ' ON ' + OBJECT_NAME(ID) + '; '
                FROM  sysindexes ix
                WHERE   ix.Name IS NOT NULL AND 
                        ix.Name LIKE '%prefix_%'
                FOR XML PATH(''));
EXEC sp_executesql @qry
  • Drop All Indexes and Stats in one Script


来源:https://stackoverflow.com/questions/14741054/delete-all-indexes-of-specific-database

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