使用Merge.輸出來獲得Sourcee.id和Target t.id之間的映射非常簡單,我有兩個表來源和目標(biāo)。declare @Source table (SourceID int identity(1,2), SourceName varchar(50))declare @Target table (TargetID int identity(2,2),
TargetName varchar(50))insert into @Source values ('Row 1'), ('Row 2')我想把所有的行從@Source到@Target并且知道TargetID每人SourceID因為還有表SourceChild和TargetChild這也需要復(fù)制,我需要添加新的TargetID進TargetChild.TargetIDFK柱對此有幾個解決方案。使用while循環(huán)或游標(biāo)一次插入一行(Rbar)并使用scope_identity()來填補.的FK.TargetChild.向@Target和插入SourceID..然后,您可以加入該列,以獲取TargetID為FK在TargetChild.SET IDENTITY_INSERT OFF為@Target自己來分配新的價值觀。你得到一個范圍,然后你用在TargetChild.TargetID.我一點也不喜歡他們。到目前為止我用的是游標(biāo)。我真正想做的是使用output插入語句的子句。insert into @Target(TargetName)output inserted.TargetID, S.SourceIDselect SourceNamefrom @Source as S但這是不可能的The multi-part identifier "S.SourceID" could not be bound.但合并是可能的。merge @Target as Tusing @Source as Son 0=1when not matched then
insert (TargetName) values (SourceName)output inserted.TargetID, S.SourceID;結(jié)果TargetID SourceID----------- -----------2 14 3我想知道你有沒有用過這個?如果你對解決方案有任何想法,或者看到有什么問題嗎?它在簡單的場景中運行良好,但是當(dāng)查詢計劃由于復(fù)雜的源查詢而變得非常復(fù)雜時,可能會發(fā)生一些丑陋的事情。最糟糕的情況是TargetID/SourceID對實際上不匹配。MSDN有關(guān)于from_table_name.的.輸出量條款。列前綴,它指定DELETE、UPDATE或Merge語句的FROM子句中包含的表,用于指定要更新或刪除的行。出于某種原因,他們沒有說“要插入、更新或刪除的行”,而是要更新或刪除的行。任何想法都是受歡迎的,完全不同的解決方案是非常感謝的。
使用Merge.輸出來獲得Sourcee.id和Target t.id之間的映射
RISEBY
2019-06-13 14:50:55