【问题标题】:Export / import tree (id's conflicts)导出/导入树(id 的冲突)
【发布时间】:2014-02-04 01:50:07
【问题描述】:

假设我们在数据库中有一个具有以下结构的表:

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

当然,某种“树”存储在那里。

用户将树的某些分支导出到 csv/xml/etc 文件。

当这个文件被导入另一个数据库时(当然有不同的节点),经常会发生 id 的冲突。

1) 可能已经存在具有相同 id 的记录

2) Db 的 id 列启用了自动递增 (因此您不能为新创建的记录明确指定 id)

这个问题通常是如何解决的? 特别是在 nodeBodyText 也可能包含与其他节点有关系的文本的情况下 (使用以前数据库中的硬编码 id)

附: 我们不接受使用 guid。

【问题讨论】:

    标签: sql import tree export


    【解决方案1】:

    假设导入的子树的父引用仅限于该子树,并且您只插入节点,而不是更新。在 SQL Server 中,您可以这样做:

    您需要一个映射表来存储新旧 id。

    declare @idmap table
    (
    old_id int, new_id int
    )
    

    然后使用 MERGE 命令插入导入的节点

    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
    

    最后重新映射目标表的父ID

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

    【讨论】:

      猜你喜欢
      • 2021-06-06
      • 2013-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-18
      • 2018-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多