从XML导入

时间:2018-06-13 08:14:24

标签: sql xml tsql openxml-sdk

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格式的数据包含两行数据。我希望这两行都是此查询的结果。

1 个答案:

答案 0 :(得分:0)

首先:FROM OPENXML以及相应的SP准备和删除文档已经过时,不应再使用了。而是使用原生XML类型的mehtods。

假设两行意味着两个<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');