Sample Header Ad - 728x90

best and quickest way to rename the primary key of a table

0 votes
1 answer
3301 views
when I need to rename a table and consequently its primary key (and all other constraints) as well I use the following simple example script: if object_id('dbo.Radhe1',N'U') is not null drop table dbo.radhe1 create table dbo.Radhe1 ( id int identity(-1008,-1) not null, name nvarchar(50) null , constraint pk_Radhe1 primary key clustered (Id) ); insert into dbo.Radhe1(name)values('Krishna') go 1008 select count(*) from dbo.radhe1 exec sp_rename N'dbo.Radhe1.pk_Radhe1', N'pk__Radhe_to_be_removed'; exec sp_rename N'dbo.Radhe1', N'Radhe1_to_be_removed' select count(*) from dbo.Radhe1_to_be_removed what I have seen is that when I table is over a million rows or any substantial size, or the server is a busy one, people tend to do is rename the table, then drop and re-create the primary key, which I understand to be a lot of work, very intense on resources. for example (names unrelated to the previous example): /* rename existing tables */ EXEC sp_rename 'dbo.DocumentDetailSearchTags', 'dbo.DocumentDetailSearchTags_TOBEDROPPED' EXEC sp_rename 'dbo.SearchTags', 'dbo.SearchTags_TOBEDROPPED' /* update pk constraint names */ ALTER TABLE dbo.DocumentDetailSearchTags_TOBEDROPPED DROP CONSTRAINT PK_DocumentDetailSearchTags ALTER TABLE dbo.DocumentDetailSearchTags_TOBEDROPPED ADD CONSTRAINT PK_DocumentDetailSearchTags_TOBEDROPPED PRIMARY KEY CLUSTERED ( [documentDetailId] ASC, [searchTagId] ASC ) Now I don't know what would the sp_rename be doing behind the scenes and I havent had the chance to test this on a busy live server. the question is: on a busy live server, sp_rename to rename the primary key of a table would work better than alter table drop and add constraint ?
Asked by Marcello Miorelli (17274 rep)
Dec 13, 2022, 06:43 PM
Last activity: Dec 14, 2022, 04:04 AM