我正在艰难地在Sql Server 2008中使用XML。我有一个xml文档,我需要解析成一个行集。我正在尝试提出一个示例查询,当针对blob执行时,返回结果,例如:
ID Status
-------- --------
3765aaf7-afaa-4a46-8499-5a61b607692c 0
1234aaf7-afaa-4a46-8499-5a61b607692c 1
以下是XML示例:
DECLARE @xml XML
SET @xml = '<Batch xmlns="urn:mynamespace">
<request xmlns:b="urn:mymessages">
<b:Batches xmlns:c="urn:myentities">
<c:BatchEntry>
<c:ID>3765aaf7-afaa-4a46-8499-5a61b607692c</c:ID>
<c:Status>0</c:Status>
</c:BatchEntry>
<c:BatchEntry>
<c:ID>1234aaf7-afaa-4a46-8499-5a61b607692c</c:ID>
<c:Status>1</c:Status>
</c:BatchEntry>
</b:Batches>
<b:BatchID>8492cbaa-eea5-479d-86c4-60cb62ac4b7c</b:BatchID>
</request>
</Batch>'
我最接近的是:
SELECT T.a.query('.') AS ID
FROM @xml.nodes('/*[local-name() = "Batch"]/*[local-name() = "request"]/*[local-name() = "Batches"]/*[local-name() = "BatchEntry"]/*[local-name() = "ID"]/text()') T(a)
但是我无法弄清楚如何基本上选择'Batches'节点然后为每个'BatchEntry'返回一个rowset。我觉得我只是不了解一些Sql Server xml操作符..:)
非常感谢您的帮助!
更新 2011-01-07
通过下面的@IanC答案,我能够获得一个完整的工作实例,包含xml命名空间,我需要做的事情。我在这里更新,以防其他人遇到它。
DECLARE @xml XML
SET @xml =
'<Batch xmlns="urn:mynamespace">
<request xmlns:b="urn:mymessages">
<b:Batches xmlns:c="urn:myentities">
<c:BatchEntry>
<c:ID>3765aaf7-afaa-4a46-8499-5a61b607692c</c:ID>
<c:Status>0</c:Status>
</c:BatchEntry>
<c:BatchEntry>
<c:ID>1234aaf7-afaa-4a46-8499-5a61b607692c</c:ID>
<c:Status>1</c:Status>
</c:BatchEntry>
</b:Batches>
<b:BatchID>8492cbaa-eea5-479d-86c4-60cb62ac4b7c</b:BatchID>
</request>
</Batch>'
DECLARE @sp int
DECLARE @hxml int
DECLARE @Result int
DECLARE @t table
(
ID UNIQUEIDENTIFIER,
BatchStatus INT
)
EXEC @sp = sp_xml_preparedocument @hxml OUTPUT, @xml
,
'<Batch
xmlns:a="urn:mynamespace"
xmlns:b="urn:mymessages"
xmlns:c="urn:myentities"
/>'
if @sp != 0 begin
SET @Result = '0'
RETURN
end
INSERT INTO @t
SELECT *
FROM OPENXML (@hxml, '/a:Batch/a:request/b:Batches/c:BatchEntry', 2)
WITH
(
ID UNIQUEIDENTIFIER 'c:ID',
BatchStatus INT 'c:Status'
)
SELECT * FROM @t
EXEC sp_xml_removedocument @hxml;
答案 0 :(得分:2)
尝试将其作为一般模式。如果您需要更多帮助,请告诉我,我将根据您的XML进行定制。
DECLARE @t table (
ProductTypeID int,
LowMin real,
HiMax real,
ParamTypeID int,
ParamWeight real,
Low real,
Hi real,
Mode tinyint
)
EXEC @sp = sp_xml_preparedocument @hxml OUTPUT, @XMLText
if @sp != 0 begin
SET @Result = '0'
RETURN
end
INSERT INTO @t
SELECT *
FROM OPENXML (@hxml, '/query/product/param/item', 2)
WITH (
ProductTypeID int '../../@type',
LowMin real '../@lowMin',
HiMax real '../@hiMax',
ParamTypeID int '../@type',
ParamWeight real '@weight',
Low real '@low',
Hi real '@hi',
Mode tinyint '@mode'
)
EXEC sp_xml_removedocument @hxml;