I assume that you want to copy a subset of the data in the table hierarchy. By hierarchy, I mean tables that are interconnected through foreign keys in the obvious sense of the word. For example, Customers
will be the root table, Orders
child and OrderDetails
another child (at 3rd level).
First, we copy the root table of the hierarchy:
MERGE RootTable as target USING ( SELECT * FROM RootTable WHERE SomeCondition ) AS src ON 1=2
Now we have a 1 to 1 mapping of the copy source and copying the target identifiers of the root table to #RootTableMapping
. In addition, all root lines were copied.
Now we need to copy all the child tables. Here's a statement for one:
MERGE ChildTable as target USING ( SELECT *,
Here we get for each child row the identifier of the cloned row of the root table so that we can bind the hierarchy. For this we use #RootTableMapping
. We copy all unmodified columns, with the exception of the parent ID, which we substitute using NewID
.
You will need one such MERGE
for each child table. The concept also extends to hierarchies with more than two levels by adding additional joins. All levels, except the lower level, must record the mapping of the identifiers of the source code of the copy to the identifiers of the copy, so that the next level below can receive new identifiers.
Feel free to ask additional questions if I don't make everything clear enough. I know this is a rough sketch.
source share