我需要根据到期日期移动一些值,但不幸的是,由于表的记录数量不是一对一的,所以在运行查询时我收到一条错误消息。我需要 SQL 能够分配它自己的主键值,因为我相信这就是冲突的来源。
错误信息是:
消息 2627,第 14 级,状态 1,第 3 行 违反主键约束“PK_ClerkDogHistory”。无法在对象“dbo.ClerkDogHistory”中插入重复的键。重复的键值为(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_INSERT ON, OFF 子句。并且不要将 Identity 列放入查询中。 你的最终查询看起来像这样。
BEGIN TRANSACTION;
INSERT INTO [Table_records_are_being_moved_TO] (column1, column2,column3...)
SELECT column1, column2,column3... 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;