3

(使用 SS2008)在 sql server 数据库中,我想将一个客户端的所有数据复制给一个新客户端。换句话说,生成与客户端 #1 相关的所有记录的完全相同的副本,但现在新记录的客户端 ID 字段引用客户端 #2。这都在同一个数据库中。

通常,我会在选择客户端#1 记录的相关表上使用一系列 INSERT 命令来执行此操作。但是,某些表具有自动编号 ID 列,并且这些 ID 在子表中被引用为外键。因此,在生成子表记录时,我需要知道并参考新创建的自动编号 ID。

最干净的方法是什么?可以通过 SQL Server 复制来完成吗?我对 SQL Server 的了解相当适中。

4

1 回答 1

5

我会做这样的事情:

-- 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
于 2011-09-16T18:28:41.267 回答