Created
March 16, 2018 13:03
-
-
Save richardbasile/e1a8cebdcaa0ba613e500ec2ced574d3 to your computer and use it in GitHub Desktop.
SQL Server - Rename Indexes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;WITH details AS( | |
select i.object_id | |
, upper(t.name) as table_name | |
, i.index_id | |
, i.name as index_name | |
, i.is_unique_constraint | |
, i.is_primary_key | |
, CASE is_primary_key WHEN 1 THEN 'PK_' | |
ELSE | |
CASE is_unique_constraint | |
WHEN 1 THEN 'UK_' ELSE 'IX_' | |
END | |
END AS prefix | |
, replace(( | |
select '_' + lower(cols.name) AS [data()] | |
from sys.index_columns ic | |
join sys.columns cols on cols.object_id = ic.object_id and cols.column_id = ic.column_id | |
where ic.object_id = i.object_id and ic.index_id = i.index_id | |
and ic.is_included_column = 0 | |
order by ic.index_column_id | |
for xml path ('') | |
), ' ', '') as column_list | |
, ( | |
select TOP 1 '_INCLUDE' | |
from sys.index_columns ic | |
join sys.columns cols on cols.object_id = ic.object_id and cols.column_id = ic.column_id | |
where ic.object_id = i.object_id and ic.index_id = i.index_id | |
and ic.is_included_column = 1 | |
) as include_columns | |
from sys.indexes i | |
join sys.tables t on t.object_id = i.object_id | |
where i.type_desc IN ('CLUSTERED','NONCLUSTERED') | |
and SCHEMA_NAME(t.schema_id) = 'dbo' | |
), build AS ( | |
select table_name | |
, index_name | |
, SUBSTRING( | |
prefix | |
+ table_name | |
+ CASE is_primary_key WHEN 0 THEN column_list ELSE '' END | |
+ CASE WHEN include_columns IS NULL THEN '' ELSE include_columns END | |
, 1, 128) new_index_name | |
from details | |
) | |
select index_name, new_index_name, 'EXEC sp_rename N''dbo.' + table_name + '.[' + index_name + ']'', N''' + new_index_name + ''', N''INDEX'';' cmd | |
from build | |
where index_name <> new_index_name | |
order by table_name, index_name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment