【发布时间】:2013-01-16 11:02:23
【问题描述】:
Source Table
TableSource
SOurceID Name ParentId
Target Table
TableTarget
RefId ParentRefId SourceId Name
-- RefId 是来自 TableReference 的外键
Table Reference
TableReference
RefID -- Auto increment IdentityCOlumn
场景
需要以这样的方式合并(插入/更新)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 --假设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
解决方案:
名称和 SourceID 的合并不是问题。当我们需要在 TableReference 中为每个插入 TableTarget 的新 RefID 插入一个新的 RefID,然后将其复制并将其插入到 tableTarget 时,问题就开始了。第二个问题是如何填充 ParentRefID。任何有关这方面的意见将不胜感激
* 最好的方法是什么 ** 我们需要游标吗?我们是否应该先用 RefID 加载它们并在加载它们之前处理 ParentRefId?*
【问题讨论】:
-
如果您使用的是 SQL Server 2008 或更高版本,您应该考虑使用 SQL 2008 和更新版本中新增的“Merge”语句。它解释了两个源何时在目标上匹配、在源上匹配、在两者上匹配、不匹配。它可以在单个语句中执行更新、删除和插入。听起来您的问题可能是一个很好的候选者,因为您可能同时做多项事情。您还可以获取此语句的输出条件,了解它对哪些列和引用做了什么。 msdn.microsoft.com/en-us/library/bb510625.aspx
标签: sql sql-server tsql ssis