简体   繁体   English

TSQL 中的 XML:循环遍历每个子节点并插入它们

[英]XML in TSQL: looping through each child node and insert them

I have a SQL table receiving orders我有一张SQL表接单

<XMLGateway>
  <Header>
    ....
  </Header>
  <Body>
    <Orders>
      <Order>
        <ItemCode>315689</ItemCode>
        <ProductName>Item1</ProductName>
      </Order>
      <Order>
        <ItemCode>123456</ItemCode>
        <ProductName>Product 1</ProductName>
      </Order>
    </Orders>
  </Body>

I would then like to iterate through each order and insert them separately into my Orders table然后我想遍历每个订单并将它们分别插入到我的 Orders 表中

insert into orders (ItemCode,ProductName) as separate records作为单独的记录插入到订单(ItemCode、ProductName)中

Is there a simpler solution than a cursor?有比 cursor 更简单的解决方案吗?

You can try with this XQuery statement - no cursors needed for sure!您可以尝试使用这个 XQuery 语句 - 肯定不需要游标!

-- you have your XML in a SQL variable here 
DECLARE @input XML = '<XMLGateway>
  <Body>
    <Orders>
      <Order>
        <ItemCode>315689</ItemCode>
        <ProductName>Item1</ProductName>
      </Order>
      <Order>
        <ItemCode>123456</ItemCode>
        <ProductName>Product 1</ProductName>
      </Order>
    </Orders>
  </Body>
  </XMLGateway>'

-- Commented out the "INSERT" part, so you can try what the "SELECT" returns    
-- INSERT INTO dbo.Orders (ItemCode, ProductName)
SELECT
    -- pick out the "ItemCode" and "ProductName" subelements from the <Order> node
    ItemCode = XC.value('(ItemCode/text())[1]', 'int'),
    ProductName = XC.value('(ProductName/text())[1]', 'varchar(100)')
FROM
    -- get the "<Order>" XML nodes, as a list of XML fragments
    @input.nodes('/XMLGateway/Body/Orders/Order') AS XT(XC)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM