使用插入语句提取XML

时间:2018-12-18 04:24:29

标签: sql-server xml xml-parsing

我正在慢慢地建立自己的SQL和XML提取知识,并且遇到了一个障碍,很明显,我的理解尚不明确,因为我假设下面的代码会将XML提取到了两个单独的表中,但是发生了什么是它仅被成功放入第一个,而完全丢失了第二个Insert语句-您能否让我知道我做错了什么

DECLARE @XMLData XML

delete from [dbo].[XMLCustomerDetails]
delete from [dbo].[XMLOrderDetails]


SELECT @xmldata = [XMLData] FROM [OPENXML];
--First of all we declare the default namespace (xmlns="Some URI")
WITH XMLNAMESPACES(DEFAULT 'http://www.adventure-works.com') 
------------------------------------------------------------------------------------------------------
insert into [dbo].[XMLCustomerDetails]
([CustomerID],[CompanyName],[ContactName],[ContactTitle],[Phone],[Address])

SELECT pd.value('(@CustomerID)[1]','nvarchar(max)') AS CustomerID
      ,pd.value('(CompanyName/text())[1]','nvarchar(max)') AS CompanyName
      ,pd.value('(ContactName/text())[1]','nvarchar(max)') AS ContactName
      ,pd.value('(ContactTitle/text())[1]','nvarchar(max)') AS ContactTitle
      ,pd.value('(Phone/text())[1]','nvarchar(max)') AS Phone
      ,pd.value('(FullAddress/Address/text())[1]','nvarchar(max)') AS Address
      --,td.value('(@CustomerID)[1]','nvarchar(max)') AS CustomerID
FROM @xmldata.nodes('//Root') as A(c)
cross apply @xmlData.nodes('//Root/Customers/Customer') as i(pd)

-------------------------------------------------------------------------------------------------------

insert into [dbo].[XMLOrderDetails]
([CustomerID]
,[EmployeeID],[OrderDate],[RequiredDate],[ShipVia]
,[Feight],[ShipName],[ShipAddress],[ShipCity],[ShipRegion],[ShipPostalCode],[ShipCountry]
)

SELECT td.value('(CustomerID/text())[1]','nvarchar(max)') AS CustomerID,
       td.value('(EmployeeID/text())[1]','nvarchar(max)') AS EmployeeID,
       td.value('(OrderDate/text())[1]','nvarchar(max)') AS OrderDate,
       td.value('(RequiredDate/text())[1]','nvarchar(max)')AS RequiredDate,
       td.value('(ShipInfo/ShipVia/text())[1]','nvarchar(max)') AS ShipVia,
       td.value('(ShipInfo/Freight/text())[1]','nvarchar(max)') AS Freight,
       td.value('(ShipInfo/ShipName/text())[1]','nvarchar(max)') AS ShipName,
       td.value('(ShipInfo/ShipAddress/text())[1]','nvarchar(max)') AS ShipAddress,
       td.value('(ShipInfo/ShipCity/text())[1]','nvarchar(max)') AS ShipCity,
       td.value('(ShipInfo/ShipRegion/text())[1]','nvarchar(max)') AS ShipRegion,
       td.value('(ShipInfo/ShipPostalCode/text())[1]','nvarchar(max)') AS ShipPostalCode,
       td.value('(ShipInfo/ShipCountry/text())[1]','nvarchar(max)') AS ShipCountry
from @xmldata.nodes('//Root') B(c)
cross apply @xmlData.nodes('//Root/Orders/Order') as o(td)

0 个答案:

没有答案