Is it possible to rename a constraint in SQL Server? I don't want to have to delete and create a new one because this constraint affects other already existing constraints and I will have to recreate/alter those.
7 Answers
After some more digging, I found that it actually has to be in this form:
EXEC sp_rename N'schema.MyIOldConstraint', N'MyNewConstraint', N'OBJECT'
-
7This is the more precise answer. The other forms only work because most people dump all their tables into the default schema (usually "dbo:) and you can omit the default schema. But if you use multiple schemas, this is correct (and you can always state the "dbo").– GodekeFeb 27, 2017 at 17:19
-
From the source, doesn't look like you need the N'OBJECT' reference Aug 5, 2020 at 13:18
You can rename using sp_rename using @objtype = 'OBJECT'
This works on objects listed in sys.objects which includes constraints
-
16Just in case you can't get this to work, it says in MSDN - "When renaming a constraint, the schema to which the constraint belongs must be specified." Oct 11, 2013 at 10:41
-
1For PK constraints there's no need for
@objtype = 'OBJECT'
to be specified. Just specify old name and new name.– pkuderovFeb 27, 2017 at 23:08
You can use sp_rename.
sp_rename 'CK_Ax', 'CK_Ax1'
-
3+1 This is what SSMS uses when renaming constraints. For a PK constraint it passes
INDEX
as object type. Jan 3, 2012 at 13:24 -
3It's also important to note that CHECK constraints, unlike PKs, do not require a table prefix on the first
sp_rename
parameter, and will fail if you use one.– mattmc3Jan 10, 2017 at 16:52
answer is true :
exec sp_rename
@objname = 'Old_Constraint',
@newname = 'New_Constraint',
@objtype = 'object'
I know this is an old question, but I just found the following to be very helpful, in addition to the other great answers:
If the constraint to be renamed has a period in it (dot), then you need to enclose it in square brackets, like so:
sp_rename 'schema.[Name.With.Period.In.It]', 'New.Name.With.Period.In.It'
-
3And also: do not put the square brackets in the new name. Otherwise you might end up with a name containing brackets Jul 30, 2020 at 9:46
-
You can also use
QUOTENAME()
. E.g.:sp_rename 'schema.' + QUOTENAME('Name.With.Period.In.It'), 'New.Name.With.Period.In.It'
. Useful for when the object's name is in a variable rather than manually typed out.– br3ntSep 20, 2022 at 23:48
What about this?:
ALTER TABLE schema.table_name RENAME CONSTRAINT old_fk1 TO new_fk11;
If you having problem when run query to create table with error message "constraint already exist" like me, may be the cause is also like mine.
When our team updating db structure to production environment, we stuck because one new table cannot be create.
We found out that the table is actually an old table that has been renamed, thus the table already exist in production with the old name.
So your option is to rename the table in production.. Or delete it then create new table.