复杂表合并包含3个表和自引用的场景

时间:2013-01-16 11:02:23

标签: sql sql-server tsql ssis

Source Table 

TableSource

SOurceID  Name   ParentId


Target Table

TableTarget

RefId ParentRefId SourceId  Name  

- RefId是来自TableReference的外键

Table Reference 

TableReference

RefID -- Auto increment IdentityCOlumn

方案

需要以SUch的方式合并(插入/更新)TableSource和TableTArget

1. On Each insert into TableTarget, it should insert a new RefId into TableReference and then Copy that RefId into TableTarget's RefId Column. 

2.ParentRefId also needs to be populated on the basis of ParentID in TableSource I-E

TableSource --Suppose TableSource在开头的

中有以下记录
SOurceID  Name         ParentId
1A         Group1       NULL
2B         GROUP2       NULL
3C         Department1   1A
4D         Department2   2B
5E         Section1      3C
6F         Section2      4D


-- I want to see TableTarget as following

RefId     SourceId     Name                ParentRefId 

1         1A           Group1              NULL as Group1 doesn't has a parent
2         2B           GROUP2              NULL as Group1 doesn't has a parent
3         3C           Department1         1 -- SourceID 3C's Parent is 1A and RefID of   1A is 1
4         4D           Department2         2 -- SourceID 4D's Parent in TableSOurce is   2B so we need to find the RefId of 2B in TableTarget to insert it here. That's 2
5         5E           Section1            3 -- PArent of 5E is 3C and RefId of 3C is 3
6         6F           Section2            4 -- PArent of 6F is 4D and RefID of 4D is 4

解决方案:

合并Name和SourceID不是问题。当我们需要在T​​ableReference中为TableTarget中的每个插入插入一个新的RefID然后复制并将其插入tableTarget时,问题就开始了。第二个问题是如何填充ParentRefID。关于此的任何意见都将受到高度赞赏

*最好的方法是什么** 我们需要游标吗?我们应该首先使用RefID加载它们并在加载之前处理ParentRefId吗?*

1 个答案:

答案 0 :(得分:0)

我建议使用两遍解决方案,在第一遍中将ParentRefID保留为null。除了通过RBAR方法之外,单个传递中无法使用tableTarget表中的刚刚插入的数据来“查找”父级的引用ID。

所以:

插入参考:

insert into tblReference select * from tblSource /* or whatever columns you want */

使用新的RefID插入目标,将parentRefID保留为null:

insert into tblTarget select tblReference.refID, tblSource.SourceID, tblSource.Name, NULL as parentRefID from tblSource inner join tblReference on <-- whatever columns link reference and source tables -->

使用parentRefIDs批量更新目标:

更新     tblTarget 组     parentRefID = target_parent.refID 从     tblSource     target_parent.sourceID = tblSource.parentID上的内连接tblTarget target_parent     tblTarget.sourceid = tblSource.sourceID

上的内连接tblTarget

不,你不能只使用MERGE,因为你不能在MERGE批处理中使用新插入的数据来传递给后续的插入/更新。