从 XML 导入

Importing from XML

DECLARE @index int 
DECLARE @XMLdoc varchar(8000)
SET @XMLdoc ='<Sales>
<Company>101</Company>
<Warehouse>S001</Warehouse>
<InvoiceNumber>1001</InvoiceNumber>
<Amount>1000.0000</Amount>
<CreateDate>20180527</CreateDate>
<Company>101</Company>
<Warehouse>S002</Warehouse>
<InvoiceNumber>1002</InvoiceNumber>
<Amount>2000.0000</Amount>
<CreateDate>20180527</CreateDate>
</Sales>'
EXEC sp_xml_preparedocument @index OUTPUT, @XMLdoc
SELECT * FROM OPENXML (@index, 'Sales',2)
WITH (Company int,Warehouse nvarchar(20),InvoiceNumber nvarchar(40),Amount 
nvarchar(10),CreateDate nvarchar(20))
EXEC sp_xml_removedocument @index

即使 XML 格式化数据包含两行,上述查询也只返回单行 data.I 希望这两行作为此查询的结果。

首先:FROM OPENXML连同相应的SP准备和删除文件已经过时,不应该再使用了。而是使用原生 XML 类型的方法。

假设两行意味着两个<Sales>我想建议:

DECLARE @XMLdoc XML=
N'<Sales>
  <Company>101</Company>
  <Warehouse>S001</Warehouse>
  <InvoiceNumber>1001</InvoiceNumber>
  <Amount>1000.0000</Amount>
  <CreateDate>20180527</CreateDate>
  <Company>101</Company>
  <Warehouse>S002</Warehouse>
  <InvoiceNumber>1002</InvoiceNumber>
  <Amount>2000.0000</Amount>
  <CreateDate>20180527</CreateDate>
</Sales>
<Sales>
  <Company>999</Company>
  <Warehouse>999</Warehouse>
  <InvoiceNumber>999</InvoiceNumber>
  <Amount>1000.0000</Amount>
  <CreateDate>20180527</CreateDate>
  <Company>101</Company>
  <Warehouse>S002</Warehouse>
  <InvoiceNumber>1002</InvoiceNumber>
  <Amount>2000.0000</Amount>
  <CreateDate>20180527</CreateDate>
</Sales>';

SELECT s.value(N'(Company/text())[1]',N'int') AS Company
      ,s.value(N'(Warehouse/text())[1]',N'nvarchar(max)') AS Warehouse
      ,s.value(N'(InvoiceNumber/text())[1]',N'int') AS InvoiceNumber
      ,s.value(N'(Amount/text())[1]',N'decimal(14,6)') AS Amount
      --and so on
FROM @XMLdoc.nodes(N'/Sales') AS A(s) 

更新(请避免跟进问题!)

您要求属性的评论指向如下内容:

SELECT 101 AS [@Company]
      ,Warehouse
      --more elements
FROM SomeWhere
FOR XML PATH('Idocs'),ROOT('Sales');