【问题标题】:XML in TSQL: looping through each child node and insert themSQL中的XML:遍历每个子节点并插入它们
【发布时间】:2022-08-04 00:41:02
【问题描述】:

我有一个接收订单的 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>

然后我想遍历每个订单并将它们分别插入到我的 Orders 表中

作为单独的记录插入到订单(ItemCode、ProductName)中

有比游标更简单的解决方案吗?

  • cross apply table.xmlcolumn.nodes(\'XMLGateway/Body/Orders/Order\')dbfiddle.uk/…

标签: sql-server xml tsql cursor


【解决方案1】:

您可以尝试使用这个 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)

【讨论】:

  • (ItemCode/text())[1] 是一个更好的主意,它更高效
  • @Charlieface:一直在忘记我的记忆-但是,是的,您完全正确-更新了我的回复,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-20
  • 1970-01-01
  • 2021-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-25
相关资源
最近更新 更多