December 4, 2014 05:52 by
Peter
As the majority of you will know, an index can enhance the performance of the query most of the time ; internally sql server has to carry out lots of function to keep these indexes in SQL Server 2014. When I started a brand new occupation, I arrived to discover lots of indexes were developed for a few in our production tables. Thus I made a decision to get yourself a script which returns the indexes that’s not active.
Note : it uses the dmv’s so, this isn't a fairly accurate query. However you could use this like a start and apply reasonable just before running the drop index statement.
SELECT DB_NAME() AS database_name ,
S.name AS [schema_name] ,
O.name AS [object_name] ,
C.name AS column_name ,
I.name AS index_name ,
( CASE WHEN I.is_disabled = 1 THEN 'Yes'
ELSE 'No'
END ) AS [disabled] ,
( CASE WHEN I.is_hypothetical = 1 THEN 'Yes'
ELSE 'No'
END ) AS hypothetical ,
rows = (SELECT SUM(p.rows) FROM sys.partitions p WHERE p.index_id = i.index_id
AND p.object_id = i.object_id GROUP BY p.index_id, p.OBJECT_ID),
N'USE ' + DB_NAME() + N'; DROP INDEX ' + QUOTENAME(i.name) + ' ON ' + QUOTENAME(s.name) +
'.' + QUOTENAME(OBJECT_NAME(i.OBJECT_ID)) AS 'drop statement'
FROM [sys].[indexes] I
INNER JOIN [sys].[objects] O ON O.[object_id] = I.[object_id]
AND O.[type] = 'U'
AND O.is_ms_shipped = 0
AND O.name <> 'sysdiagrams'
INNER JOIN [sys].[tables] T ON T.[object_id] = I.[object_id]
INNER JOIN [sys].[schemas] S ON S.[schema_id] = T.[schema_id]
INNER JOIN [sys].[index_columns] IC ON IC.[object_id] = I.[object_id]
AND IC.index_id = I.index_id
INNER JOIN [sys].[columns] C ON C.[object_id] = IC.[object_id]
AND C.column_id = IC.column_id
WHERE I.[type] > 0
AND I.is_primary_key = 0
AND I.is_unique_constraint = 0
AND NOT EXISTS ( SELECT *
FROM [sys].[index_columns] XIC
INNER JOIN [sys].[foreign_key_columns] FKC ON FKC.parent_object_id =
IC.[object_id]
AND FKC.parent_column_id = XIC.column_id
WHERE XIC.[object_id] = I.[object_id]
AND XIC.index_id = I.index_id )
AND NOT EXISTS ( SELECT *
FROM [master].[sys].[dm_db_index_usage_stats] IUS
WHERE IUS.database_id = DB_ID(DB_NAME())
AND IUS.[object_id] = I.[object_id]
AND IUS.index_id = I.index_id )