1

技术人员——我正在粉碎一个 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)
4

1 回答 1

1

查看OUTPUT 子句。在插入 OrderSubHeader 时,除了要插入 OrderDetail 表的任何其他值之外,您还可以捕获 insert.OrderSubID。然后使用捕获的数据(在临时表或表变量中)插入 OrderDetail。

于 2012-10-08T17:28:47.650 回答