Skip to content

Instantly share code, notes, and snippets.

@gabrielribeiro
Created February 3, 2015 19:22
Show Gist options
  • Save gabrielribeiro/bd42861904f35397d37e to your computer and use it in GitHub Desktop.
Save gabrielribeiro/bd42861904f35397d37e to your computer and use it in GitHub Desktop.
--'sp_rename ''' + obj.name + ''', ''FK_' + tab1.name + '_' + tab2.name + '_' + col2.name + '''',
SELECT
'sp_rename ''' + obj.name + ''', ''FK_' + tab1.name + '_' + tab2.name + '_' + col2.name + '''' AS [PROC],
'FK_' + tab1.name + '_' + tab2.name + '_' + col2.name + '''' AS EXPECTED_NAME,
obj.name AS FK_NAME,
tab1.name AS [table],
tab2.name AS [referenced_table],
col2.name AS [referenced_column]
FROM sys.foreign_key_columns fkc
INNER JOIN sys.objects obj
ON obj.object_id = fkc.constraint_object_id
INNER JOIN sys.tables tab1
ON tab1.object_id = fkc.parent_object_id
INNER JOIN sys.schemas sch
ON tab1.schema_id = sch.schema_id
INNER JOIN sys.columns col1
ON col1.column_id = parent_column_id AND col1.object_id = tab1.object_id
INNER JOIN sys.tables tab2
ON tab2.object_id = fkc.referenced_object_id
INNER JOIN sys.columns col2
ON col2.column_id = referenced_column_id AND col2.object_id = tab2.object_id
WHERE 'FK_' + tab1.name + '_' + tab2.name + '_' + col2.name <> obj.name
ORDER BY [table], FK_NAME
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment