SQL Primary Key Exception

落爺英雄遲暮 提交于 2019-12-12 16:19:16

问题


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.


回答1:


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]


来源:https://stackoverflow.com/questions/30129644/sql-primary-key-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!