SQL Server 2005提供sp_xml_preparedocument处理XML片段,使之可以在当次连接会话中使用。并提供sp_xml_removedocument移除。
除上述使用属性外还可解析内嵌的XML
最后使用:
具体操作:
DECLARE @hdoc int
DECLARE @doc varchar(2000)
SET @doc = '
<root>
<Customers CustomerID="ALFKI" ContactName="Maria Anders"/>
<Customers CustomerID="ASDFD" ContactName="Earia Anders"/>
<Customers CustomerID="AS23D" ContactName="Earia 212nders"/>
</root>'
EXEC sp_xml_preparedocument @hdoc OUTPUT, @doc
select *--ContactName
from OpenXml(@hdoc,'/root/Customers')
--with( CustomerID varchar(10), ContactName varchar(20))
--Where CustomerID = 'AS23D'
除上述使用属性外还可解析内嵌的XML
<roo>
<Customer>
<Name>eric</Name>
</Customer>
</root>
此时代码需要作调整:
(
注意OpenXML的参数)
set @doc2 ='
<root>
<Customers>
<name>eric</name>
<sex>男</sex>
</Customers>
<Customers>
<name>John</name>
<sex>女</sex>
</Customers>
</root>'
EXEC sp_xml_preparedocument @hdoc OUTPUT, @doc2
select *--ContactName
from OpenXml(@hdoc,'/root/Customers',2)
--with( CustomerID varchar(10), ContactName varchar(20))
with( name nvarchar(10), sex nvarchar(20))
--Where CustomerID = 'AS23D'
Exec sp_xml_removedocument @hdoc
最后使用:
Exec sp_xml_removedocument @hdoc
移除。