1

Let's assume we have a table in database with the following structure:

id (int32), parentId (int32), nodeName, nodeBodyText, ...

Of course some kind of "tree" is stored there.

User exports some branch of the tree to csv/xml/etc file.

When this file is being imported to another db (with a different nodes of course) there often may happen id's conflicts.

1) Records with the same id's may exist already

2) Db has the id column with the auto-incrementing enabled (so you can't explicitly specify id for newly created record)

How this problem is usually solved? Especially in case nodeBodyText also may contain text with relations to other nodes (using hardcoded ids from a previous db)

P.S. Usage of guid's is not acceptable for us.

0

1 Answer 1

0

Assuming that the imported subtree has parent references confined to that subtree only and you are inserting the nodes only, not updating. In SQL server you can do this:

You need a mapping table to store new and old ids.

declare @idmap table
(
old_id int, new_id int
)

Then insert imported nodes using MERGE command

MERGE [target] as t 
USING [source] as s ON 1=0  -- don't match anythig, all nodes are new
WHEN NOT MATCHED 
THEN INSERT(parentid,nodename) VALUES(s.parentid,s.nodename)
OUTPUT s.id, inserted.id INTO @idmap; -- store new and old id in mapping table

Finally re-map target table's parent ids

update t
set parentid = x.new_id
from [target] t
inner join @idmap x on x.old_id = t.parentid
where t.parentid is not null
and -- only the newly inserted nodes
exists(select * from @idmap where new_id = t.id); 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.