Last active
January 21, 2020 10:41
-
-
Save eegeeZA/2520aff68dc22b23edbf0f5697494cde to your computer and use it in GitHub Desktop.
Helper scripts to rename different types of T-SQL constraint names. Especially useful for fixing generated names across environments.
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
-- rename DEFAULT constraints -- | |
DECLARE @sql NVARCHAR(MAX) = N'' | |
SELECT @sql += | |
-- SELECT | |
N'exec sp_rename ' + QUOTENAME(schemas.name + '.' + sys.default_constraints.name) + ', ''DF_' + sys.tables.name + '_' + | |
sys.all_columns.name + ''';' | |
FROM sys.all_columns | |
INNER JOIN sys.tables ON all_columns.object_id = tables.object_id | |
INNER JOIN sys.schemas ON tables.schema_id = schemas.schema_id | |
INNER JOIN sys.default_constraints ON all_columns.default_object_id = default_constraints.object_id | |
WHERE schemas.name = 'YOUR-SCHEMA-NAME' | |
AND sys.all_columns.default_object_id = default_constraints.object_id | |
EXEC sp_executesql @sql | |
GO | |
-- rename PRIMARY KEY constraints -- | |
DECLARE @sql NVARCHAR(MAX) = N'' | |
SELECT @sql += | |
-- SELECT | |
N'exec sp_rename ' + QUOTENAME(table_schema + '.' + CONSTRAINT_NAME) + ', ''PK_' + TABLE_NAME + ''';' | |
FROM information_schema.table_constraints | |
WHERE constraint_type = 'PRIMARY KEY' | |
AND table_schema = 'YOUR-SCHEMA-NAME' | |
EXEC sp_executesql @sql | |
GO | |
-- rename FOREIGN KEY constraints -- | |
DECLARE @sql NVARCHAR(MAX) = N'' | |
SELECT @sql += | |
-- SELECT | |
N'exec sp_rename ' + QUOTENAME(s.name + '.' + fk.name) + ', ''FK_' + parent_tables.name + '_' + referenced_tables.name + '_' + | |
parent_columns.name + ''';' | |
FROM sys.foreign_keys fk | |
JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id | |
JOIN sys.tables parent_tables ON fk.parent_object_id = parent_tables.object_id | |
JOIN sys.tables referenced_tables ON fk.referenced_object_id = referenced_tables.object_id | |
JOIN sys.columns parent_columns ON fkc.parent_object_id = parent_columns.object_id AND fkc.parent_column_id = parent_columns.column_id | |
JOIN sys.schemas s ON s.schema_id = fk.schema_id | |
WHERE s.name = 'YOUR-SCHEMA-NAME' | |
EXEC sp_executesql @sql | |
GO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment