SSMS Tools Custom Script For Index Information
Posted by Josh | Posted in SQL Server | Posted on 14-01-2011
Tags: indexes, SQL Server, t-sql tuning, tools
2
The other day I was having a chat with a developer around our SQL coding standards, specifically the naming conventions. He made an interesting point: the name shouldn’t matter, because it’s the metadata ( what table its on, the index key columns, included columns, etc) that matters. My response was that while that’s true, it’s helpful as a production DBA to have the name, which is readily available via a few clicks in SSMS, be a meaningful one that gives you some inkling of what the index is. This is especially true at 3AM when you’re troubleshooting issues. His response: write a script that you can run to give the information and use that instead of the GUI.
And while I’m not switching my position on naming standards (Have you seen SSMS’s default naming for indexes? Ugh…), I’m up for any challenge, so write a script I did. I actually use this with SSMS Tool‘s “Custom Script” functionality so when I right-click a table, it is easily run.
SELECT 'Index Information'
SELECT i.name [Index Name],
i.type_desc [Index Type],
CASE i.is_primary_key
WHEN 1 THEN 'Yes'
ELSE 'No'
END [Is Primary Key],
(
SELECT c2.name + ', '
FROM sys.index_columns ikc
JOIN sys.columns c2
ON ikc.column_id = c2.column_id
AND ikc.object_id = c2.object_id
AND ikc.is_included_column = 0
WHERE ikc.index_id = i.index_id
AND ikc.object_id = i.object_id
ORDER BY ikc.index_column_id ASC
FOR XML PATH('')
) [Index Columns],
(
SELECT c1.name + ', '
FROM sys.index_columns ikc
JOIN sys.columns c1
ON ikc.column_id = c1.column_id
AND ikc.object_id = c1.object_id
AND ikc.is_included_column = 1
WHERE ikc.index_id = i.index_id
ORDER BY ikc.index_column_id ASC
FOR XML PATH('')
) [Included Columns]
FROM sys.indexes i
JOIN sys.objects o
ON i.object_id = o.object_id
JOIN sys.schemas s
ON o.schema_id = s.schema_id
WHERE o.name = '|ObjectName|'
AND s.name = '|SchemaName|'
It returns some basic metadata about the index definition, such as the name, type, and columns (both included and key). I’ll be trying this out and undoubtedly adding more columns in the coming weeks, but wanted to share it.
What useful SSMS ToolPack custom scripts do you have?
