1
Techies-- 我正在通過一個Xml對象進行粉碎,沒有任何問題,無法爲正確的節點拾取正確的元素,但是我需要正確更新細節標識符,這是堅持一個單一的價值,當我真正需要它做的是刷新它的價值,它剛剛寫的價值。我喜歡當前粉碎過程的效率 - 所以我不想因爲提出一個愚蠢的解決方案而失去這種效果。請告訴我關於如何解決這一邏輯的最佳方法。T-SQL:scope_identity()在xml節點分析時錯誤分配
這裏發生的事情:
-- Given:
-- @OrderXml is an incoming, populated order containg the header,
-- subheaders and detail records
-- This logic succeeds
-- step #1: write the header row in the header table
insert into [order].OrderHeader
(col.cone,
col.ctwo)
select
Order.detail.value('(cone/text())[1]','varchar(2)'),
Order.detail.value('(ctwo/text()) [1]','varchar(2)')
from @OrderXml.nodes('/Order') as Order(detail)
select @OrderId = scope_identity()
-- This logic succeeds
-- step #2: write the subheader rows in the subheader table
insert into [order].OrderSubHeader
(col.OrderId,
col.xone,
col.xtwo)
select
@OrderId, -- this works, because no matter how many subheader rows
-- get generated, the same order id needs to be associated with it.
OrderSub.detail.value('(xone/text())[1]','varchar(2)'),
OrderSub.detail.value('(xtwo/text()) [1]','varchar(2)')
from @OrderXml.nodes('/Order/SubHeader'') as OrderSub(detail)
SELECT @OrderSubId = SCOPE_IDENTITY()
-- This logic FAILS
-- step #3: write the detail rows in the detail table
insert into [order].OrderDetail
(col.OrderId,
col.OrderSubId,
col.yone,
col.ytwo)
select
@OrderId, -- this is correct
@OrderSubId, -- this is WRONG when there are multiples
OrderDet.detail.value('(yone/text())[1]','varchar(2)'),
OrderDet.detail.value('(ytwo/text()) [1]','varchar(2)')
from @OrderXml.nodes('/Order/SubHeader/Detail'') as OrderDet(detail)
您使用的是哪個版本的SQL Server? –
@Mikael,mssql2008r2 – plditallo
這聽起來像你可以使用'合併'和'輸出'描述[這裏](http://stackoverflow.com/questions/5365629/using-merge-output-to-get-mapping -between源-ID-和目標ID)。 –