3

I have a Mircrosoft Sql Server database made up of about 8 tables that are all related that I am trying to update. To do this I create a number of temporary tables

"CREATE TABLE [vehicle_data].[dbo].[temp_MAINTENANCE_EVENT] (" +
                       "[maintenance_event_id] int," +
                       "[maintenance_computer_code_id] int," +
                       "[veh_eng_maintenance_id] int," +
                       "CONSTRAINT [PK_maintenance_event_id"] PRIMARY KEY CLUSTERED ([maintenance_event_id] ASC))";

Then after all the temporary tables have been created I drop the existing tables, rename the temporary tables, and add foreign keys and indexing to the new tables to speed up joins and querying.

The issue I'm having is the original primary key references are remaining. So when I go to update again I get

Exception: There is already an object named 'PK_maintenance_event_id' in the database. Could not create constraint.

I'm wondering what is the best course of action is? Should I not set the primary key when I create the temporary table and instead add it to the table after it has been renamed? Or is there a way to rename constraints so that when I rename the table I can change the name of the primary key constraint.

After the original tables have been dropped I want there to be as little downtime as possible, but anything that happens before the tables have been dropped can take a really long time and it won't matter.

nastassiar
  • 1,545
  • 2
  • 24
  • 43

1 Answers1

3

If your temp tables need that constraint

When create use

CONSTRAINT [PK_maintenance_event_id_temp"]

instead of

CONSTRAINT [PK_maintenance_event_id]

when you rename temp back to real table

exec sp_rename [PK_maintenance_event_id_temp], [PK_maintenance_event_id]
Ray Krungkaew
  • 6,652
  • 1
  • 17
  • 28