使用来自 SQL 服务器中另一个 table 的正确 table 模式将 XML 列转储到 table

Dump the XML column into a table with proper table schema from another table in SQL Server

我有一个客户订单 table,其中有一个 XML 列,其中包含他们的订单详细信息。我需要将 XML 转储到具有适当架构

的 table

Table 架构:

CREATE TABLE [dbo].[CustomerOrder]
(
    [Id] INT NOT NULL IDENTITY(1,1),
    [CustomerName] NVARCHAR(30),
    [OrderDate] DATETIME2 NOT NULL DEFAULT GETUTCDATE(),
    [Items] XML
    CONSTRAINT [PK_dbo_CustomerOrder] PRIMARY KEY CLUSTERED 
    (
        [Id] ASC
    ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
)

示例数据:

INSERT INTO [dbo].[CustomerOrder]([CustomerName], [Items])
VALUES (N'John', N'<Orders>
  <Order>
    <Item>
      <Id>8D267E8E-2B1E-4FBF-8EE3-52D03D25A4F5</Id>
      <Name>Tape</Name>
      <Quantity>1</Quantity>
      <Rate>25.00</Rate>
      <NetAmount>25.00</NetAmount>
    </Item>
    <Item>
      <Id>B661043F-3299-41CD-84A7-B16E824B3C8D</Id>
      <Name>Rope</Name>
      <Quantity>2</Quantity>
      <Rate>20.00</Rate>
      <NetAmount>40.00</NetAmount>
    </Item>
  </Order>
</Orders>')


INSERT INTO [dbo].[CustomerOrder]([CustomerName], [Items])
VALUES (N'Peter', N'<Orders>
  <Order>
    <Item>
      <Id>B661043F-3299-41CD-84A7-B16E824B3C8D</Id>
      <Name>Rope</Name>
      <Quantity>5</Quantity>
      <Rate>20.00</Rate>
      <NetAmount>100.00</NetAmount>
    </Item>
  </Order>
</Orders>')

我尝试将上述数据转储到具有以下 table 结构的临时 table

CustomerOrderId     Name     OrderDate                 ItemName     Quantity     Rate     NetAmount
____________________________________________________________________________________________________
1                   John     2021-08-11 06:05:42.020   Tape          1           25.00      25.00
1                   John     2021-09-10 08:11:30.490   Rope          2           20.00      40.00
2                   Peter    2021-10-05 09:30:10.850   Rope          5           20.00     100.00

请指导我如何从上面实现这个table [dbo].[CustomerOrder]

您可以像这样从 XML 数据中获取单个值:

SELECT
    CustomerOrderId = Id,
    Name = CustomerName,
    OrderDate,
    ItemName = xc.value('(Name/text())[1]', 'varchar(50)'),
    Quantity = xc.value('(Quantity/text())[1]', 'int'),
    Rate = xc.value('(Rate/text())[1]', 'decimal(20,2)'),
    NetAmount = xc.value('(NetAmount/text())[1]', 'decimal(20,2)')
FROM 
    dbo.CustomerOrder
CROSS APPLY
    Items.nodes('/Orders/Order/Item') as XT(XC)