Source Table
TableSource
SOurceID Name ParentId
Target Table
TableTarget
RefId ParentRefId SourceId Name
複雜的表合併方案 - REFID是一個外鍵從TableReference涉及3個表和自參考
未來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 --Suppose TableSource has following Rec在開始時ORDS
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中爲每個插入插入一個新的RefID到TableTarget,然後複製並將其插入到tableTarget時,問題就開始了。第二個問題是如何填充ParentRefID。任何有關這方面的意見將不勝感激
*什麼是最好的辦法做到這一點** 我們需要光標?我們是否應該首先加載RefID並在加載之前處理ParentRefId?*
如果您使用的是SQL Server 2008或更高版本,則應該考慮使用SQL 2008和更新版本中新增的「合併」語句。它在兩個源匹配的時候佔到源,匹配源,兩者匹配,不匹配。它可以執行更新,刪除和插入一條語句。這聽起來像你的問題可能是一個很好的候選人,因爲你一次做多件事。你也可以得到這個語句的輸出條件,也就是它對什麼列和參考做了什麼。 http://msdn.microsoft.com/en-us/library/bb510625.aspx – djangojazz