I need to move some values based on expiration date, but unfortunately because the tables are not one to one in number of records I receive an error message when my query is run. I need SQL to be able to assign it's own primary key value because I believe that is where the conflict is coming from.
The error message is:
Msg 2627, Level 14, State 1, Line 3 Violation of PRIMARY KEY constraint 'PK_ClerkDogHistory'. Cannot insert duplicate key in object 'dbo.ClerkDogHistory'. The duplicate key value is (10595).
SET IDENTITY_INSERT [Table_records_are_being_moved_TO] ON
BEGIN TRANSACTION;
INSERT INTO [Table_records_are_being_moved_TO] (column1, column2,column3...)
SELECT *
FROM [Table_records_are_being_moved_FROM]
WHERE [expiration_date] between '2013-01-01' and '2013-12-31';
DELETE FROM [Table_records_are_being_moved_FROM]
WHERE [expiration_date] between '2013-01-01' and '2013-12-31';
COMMIT;
SET IDENTITY_INSERT [Table_records_are_being_moved_TO] OFF
IDENTITY_INSERTin the posted code. The problem is that the source query is trying to insert additional data that would violate the primary key constraint of the target table.SQL to be able to assign it's own primary key value- hence they need identity insert to be off not on.SELECT *." This is another reason why. Op needs to specify all of the columns, except for the identity column, when selecting/inserting the data.