You can use the sp_rename
system stored procedure to rename a foreign key constraint in SQL Server.
The purpose of this stored procedure is to allow you to rename user-created objects in the current database, so you can also rename other objects such as tables, columns, alias data types, etc.
Syntax
The syntax of sp_rename
goes like this:
sp_rename [ @objname = ] 'object_name' , [ @newname = ] 'new_name' [ , [ @objtype = ] 'object_type' ]
So your code could go something like this:
sp_rename 'schema_name.old_fk_name', 'new_fk_name';
Note that the Microsoft documentation states that when renaming constraints (such as foreign keys) you must qualify the existing name with the schema name.
You may or may not get an error if you omit the schema, but it’s probably a good idea to follow Microsoft’s advice on this one.
The following example shows me renaming a foreign key.
Example 1 – Review All Foreign Keys
First, I’ll take a look at the foreign keys in the database (so I can decide which one to rename).
SELECT name AS 'Foreign Key', SCHEMA_NAME(schema_id) AS 'Schema', OBJECT_NAME(parent_object_id) AS 'Table', OBJECT_NAME(referenced_object_id) AS 'Referenced Table' FROM sys.foreign_keys;
Result:
+--------------------------------+----------+---------+--------------------+ | Foreign Key | Schema | Table | Referenced Table | |--------------------------------+----------+---------+--------------------| | FK_Albums_Artists | dbo | Albums | Artists | | FK_Albums_Genres | dbo | Albums | Genres | | FK__Artists__Country__4AB81AF0 | dbo | Artists | Country | +--------------------------------+----------+---------+--------------------+
The third foreign key (FK__Artists__Country__4AB81AF0) has been named by the system. The system named it because I forgot to provide a name when I created it.
Let’s give this foreign key a more concise name.
Example 2 – Rename the Foreign Key
Here’s the bit that renames the foreign key.
sp_rename 'dbo.FK__Artists__Country__4AB81AF0', 'FK_Artists_Country';
As mentioned, the old (existing) name comes first, then the new name.
So now if I select all foreign keys, I get the following result.
SELECT name AS 'Foreign Key', SCHEMA_NAME(schema_id) AS 'Schema', OBJECT_NAME(parent_object_id) AS 'Table', OBJECT_NAME(referenced_object_id) AS 'Referenced Table' FROM sys.foreign_keys;
Result:
+--------------------+----------+---------+--------------------+ | Foreign Key | Schema | Table | Referenced Table | |--------------------+----------+---------+--------------------| | FK_Albums_Artists | dbo | Albums | Artists | | FK_Albums_Genres | dbo | Albums | Genres | | FK_Artists_Country | dbo | Artists | Country | +--------------------+----------+---------+--------------------+
I have successfully renamed the foreign key.