在SQL Server 2016中,我需要从2个表中创建几乎完全相同的记录副本。唯一的区别是它们的主键,我要重置为零的另一列以及第二个表(这是我的第一个表的PK)中的外键。我可以很好地创建两个表的副本,但是我不知道如何为第二个表分配新的FK值,以正确反映第一个表中的新主键。
这是两个表中的当前记录:
表1:批处理
+-----------------------+-----------+----------------+------------+
| BatchID (pk identity) | StartDate | ProcessingStep | BatchCount |
+-----------------------+-----------+----------------+------------+
| 1 | 5/10/2019 | 2 | 8203 |
| 2 | 5/11/2019 | 2 | 345 |
| 3 | 5/12/2019 | 2 | 5014 |
+-----------------------+-----------+----------------+------------+
表2: ItemList
+--------------------------+---------+--------+-----------+-------------+
| ItemListID (pk identity) | BatchID | ItemID | Processed | ProcessDate |
+--------------------------+---------+--------+-----------+-------------+
| 1000 | 1 | 201 | 1 | 5/10/2019 |
| 1001 | 1 | 689 | 1 | 5/10/2019 |
| 1002 | 2 | 548 | 1 | 5/11/2019 |
| 1003 | 2 | 693 | 1 | 5/11/2019 |
| 1004 | 3 | 123 | 1 | 5/12/2019 |
| 1005 | 3 | 999 | 1 | 5/12/2019 |
+--------------------------+---------+--------+-----------+-------------+
我现在要创建这些记录的副本,但以下情况除外:
Batches.ProcessingStep
将设置为零ItemList
的{{1}}和Processed
分别重置为零和空值ProcessDate
以反映复制的ItemList.BatchID
记录的新PK(这是我遇到的问题)当前,我用于更新表的脚本如下:
Batches
这是我的最终结果:
表1:批处理
INSERT INTO Batches(StartDate, ProcessingStep, BatchCount)
SELECT StartDate, 0, BatchCount
FROM Batches
WHERE BatchID IN (1,2,3)
INSERT INTO ItemList(BatchID, ItemID, Processed, ProcessDate)
SELECT <<?? not sure ??>>, ItemID, 0, NULL
WHERE ItemListID BETWEEN 1000 AND 1005
表2: ItemList
+---------+-----------+----------------+------------+
| BatchID | StartDate | ProcessingStep | BatchCount |
+---------+-----------+----------------+------------+
| 1 | 5/10/2019 | 2 | 8203 |
| 2 | 5/11/2019 | 2 | 345 |
| 3 | 5/12/2019 | 2 | 5014 |
| 4 | 5/10/2019 | 0 | 8203 |
| 5 | 5/11/2019 | 0 | 345 |
| 6 | 5/12/2019 | 0 | 5014 |
+---------+-----------+----------------+------------+
我该如何正确填充+------------+---------+--------+-----------+-------------+
| ItemListID | BatchID | ItemID | Processed | ProcessDate |
+------------+---------+--------+-----------+-------------+
| 1000 | 1 | 201 | 1 | 5/10/2019 |
| 1001 | 1 | 689 | 1 | 5/10/2019 |
| 1002 | 2 | 548 | 1 | 5/11/2019 |
| 1003 | 2 | 693 | 1 | 5/11/2019 |
| 1004 | 3 | 123 | 1 | 5/12/2019 |
| 1005 | 3 | 999 | 1 | 5/12/2019 |
| 1006 | 4 | 201 | 0 | NULL |
| 1007 | 4 | 689 | 0 | NULL |
| 1008 | 5 | 548 | 0 | NULL |
| 1009 | 5 | 693 | 0 | NULL |
| 1010 | 6 | 123 | 0 | NULL |
| 1011 | 6 | 999 | 0 | NULL |
+------------+---------+--------+-----------+-------------+
外键?
谢谢。