使用带有XMLNS的OPENXML命令将XML导入SQL服务器

时间:2016-10-22 13:52:42

标签: sql sql-server xml

我有以下代码将xml导入SQL

DECLARE @XML AS XML, @hDoc AS INT, @SQL NVARCHAR (MAX)

SELECT @XML = XMLData FROM XMLwithOpenXML

EXEC sp_xml_preparedocument @hDoc OUTPUT, @XML

SELECT rid, uid
FROM OPENXML(@hDoc, '/PportTimetable/Journey')
WITH 
(
rid [varchar](50) '@rid',
uid [varchar](100) '@uid'
)

EXEC sp_xml_removedocument @hDoc
GO

我可以让代码工作,但只有当它不包含xmlns信息时,如下所示为什么会这样?

xmlns:xsd =“http://www.w3.org/2001/XMLSchema”

xmlns:xsi =“http://www.w3.org/2001/XMLSchema-instance”

的xmlns = “http://www.thalesgroup.com/rtti/XmlTimetable/v8”

XML标头

<PportTimetable xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" timetableID="20161018020822" xmlns="http://www.thalesgroup.com/rtti/XmlTimetable/v8">
  <Journey rid="201610188012733" uid="P12733" trainId="2J27" ssd="2016-10-18" toc="AW">
</Journey>
</PportTimetable>

2 个答案:

答案 0 :(得分:3)

您需要将namespace指定为sp_xml_preparedocument

的第三个参数
LEFT JOIN

答案 1 :(得分:3)

我建议完全跳过OPENXML内容,并在SQL Server中使用内置的本机XQuery支持:

declare @input XML = '<PportTimetable xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" timetableID="20161018020822" xmlns="http://www.thalesgroup.com/rtti/XmlTimetable/v8">
    <Journey rid="201610188012733" uid="P12733" trainId="2J27" ssd="2016-10-18" toc="AW">
    </Journey>
</PportTimetable>'

-- define your XML namespaces - here, there's only a single "default" namespace    
;WITH XMLNAMESPACES(DEFAULT 'http://www.thalesgroup.com/rtti/XmlTimetable/v8')
SELECT 
    RID = XC.value('@rid', 'varchar(50)'),
    UID = XC.value('@uid', 'varchar(20)'),
    TrainId = XC.value('@trainId', 'varchar(25)'),
    SSD = XC.value('@ssd', 'varchar(25)'),
    TOC = XC.value('@toc', 'varchar(20)')
FROM 
    @input.nodes('/PportTimetable/Journey') AS XT(XC)

使用XQuery .nodes()函数将XML“分解”为XML片段的“内联”表(在此示例中为每个<Journey>节点一个),然后使用{{1函数从这些XML片段中逐个获取单个元素和属性。