Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename primary key constraint in SQL Server

Tags:

I have a PK constraint on table Notes named PK_dbo.Notes and want to rename it to PK_Notes using SQL Server DDL, i.e. not by using SSMS rename menu option.

Mentioned in another question's answers queries don't work for me. That thread's answers are also helpful, but don't work too.

like image 786
pkuderov Avatar asked Jun 01 '16 19:06

pkuderov


People also ask

How do you rename a primary key in SQL Server?

In SQL Server, you can use the sp_rename stored procedure to rename a user created object in the current database, including a primary key. This can be handy if you've got a primary key that had its name automatically assigned, and you now want to give it a more readable name.

How do you rename a constraint in SQL Server?

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.

Can we rename primary key column name?

Show activity on this post. drop foreign keys from others tables pointing to the primary key you want to rename. rename the primary key. add the foreign column to other tables.

Can you rename a constraint?

It is not possible to rename a constraint for a column referenced by a view. For more details, see View Dependencies. Tip: This command can be combined with other ALTER TABLE commands in a single statement.


1 Answers

Sometimes you need to explicitly wrap names in square brackets, like this:

sp_rename @objname = N'[Notes].[PK_dbo.Notes]', @newname = N'PK_Notes' 

I think it's because of the dot in PK name.

Also, as you see, PK constraints don't need @objtype = 'OBJECT' to be specified.

like image 73
pkuderov Avatar answered Sep 20 '22 14:09

pkuderov