我会做这样的事情:
-- Set up a placeholder for the new id
DECLARE @NewID INT;
-- INSERT parent record
INSERT INTO myTable (field1, field2)
SELECT field1, field2 FROM myTable WHERE ID = 1
-- Get the new ID
SET @NewID = (SELECT SCOPE_IDENTITY());
-- Insert child records with new id
INSERT INTO OtherTable (fkid, field1, field2)
SELECT @NewID, field1, field2 FROM OtherTable WHERE ID = 1
现在,如果我们需要处理数千条记录,这可能会起作用:
-- Add a new column in the database to manage where the record came from
ALTER TABLE myTable ADD ParentID int NULL
-- INSERT parent record
INSERT INTO myTable (field1, field2, ParentID)
SELECT
field1
, field2
, ID
FROM myTable
WHERE SomeCondition IS True
-- Insert child records with new id
INSERT INTO OtherTable (fkid, field1, field2)
SELECT
myTable.ID
, OtherTable.field1
, OtherTable.field2
FROM
OtherTable
INNER JOIN myTable ON OtherTable.FKID = myTable.ParentID
-- Once unneeded, drop the temporary column
-- ALTER TABLE myTable DROP COLUMN ParentID