开发者

Create Duplicate records with autonumber foreign keys

(using SS2008) Within a sql server database, I'd like to copy all the data of one client for a new client. In开发者_开发百科 other words, generate exact duplicates of all records that pertain to client #1, except now the client ID field of the new records refer to client #2. This is all inside the same database.

Normally I would do this with a series of INSERT commands on the relevant tables selecting the client #1 records. However, some of the tables have autonumber ID columns, and these IDs are referenced as foreign keys in child tables. So when generating the child table records, I'd need to know and refer to the newly created autonumber Ids.

What is the cleanest way to go about this? Can it be done with SQL Server replication? My knowledge of SQL Server is pretty moderate.


I would do something like this:

-- 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

Now if we need to deal with thousands of records, this could work:

-- 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜