Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I rename my constraints

Tags:

I renamed a table in my database with

EXEC sp_rename 'tblOldAndBusted', 'tblNewAndShiny' 

and all the foreign key constraints were updated to the new table name, but they're still named based on the old table name. For example, I now have FK_tblOldAndBusted_tblTastyData but I'd like to have FK_tblNewAndShiny_tblTastyData.

Is there an easy way to script this?

Also, am I being too anal? I know the database works fine with the old table name in the constraints, but it feels like broken windows.

like image 655
Matt Casto Avatar asked Sep 16 '10 17:09

Matt Casto


People also ask

How do I rename a constraint in SQL?

sp_rename automatically renames the associated index whenever a PRIMARY KEY or UNIQUE constraint is renamed. If a renamed index is tied to a PRIMARY KEY constraint, the PRIMARY KEY constraint is also automatically renamed by sp_rename . sp_rename can be used to rename primary and secondary XML indexes.

How do you rename a constraint in Oracle?

You can use the following SQL query, to get the name of the constraints which are created by the Oracle server on the TEST11 table. SELECT CONSTRAINT_NAME, COLUMN_NAME FROM USER_CONS_COLUMNS WHERE TABLE_NAME='TEST11'; SELECT CONSTRAINT_NAME, COLUMN_NAME FROM USER_CONS_COLUMNS WHERE TABLE_NAME='TEST11';

How do you change existing constraints?

An existing constraint cannot be modified. To define another column, or set of columns, as the primary key, the existing primary key definition must first be dropped, and then re-created.


1 Answers

Try:

exec sp_rename 'FK_tblOldAndBusted_tblTastyData', 'FK_tblNewAndShiny_tblTastyData', 'object' 

Also, there is a bug regarding renaming such things when you deal with non-default schema.

Cannot rename a default constraint for a table in a schema which is not dbo by rsocol @Microsoft Connect

like image 196
Denis Valeev Avatar answered Oct 29 '22 12:10

Denis Valeev