我希望以某种方式显示列中的以下xml。我进行了搜索和搜索,但没有一个解决方案对我来说足够具体,所以就这样了。
XML:
<Top>
<Branch>
<BranchResult Version="1.0" Branch="Croydon" MilesToTravel="11" />
<BranchResult Version="1.0" Branch="Hendon" MilesToTravel="11" />
<BranchResult Version="1.0" Branch="Waltham" MilesToTravel="18" />
</Branch>
<Valuation>
<ValuationResult Version="1.0" °IDENTIFIER="thisOne" GuideLow="3159" GuideHigh="4196" />
</Valuation>
</Top>
我希望结果像这样
Branch1,Branch2,Branch3,IDENTIFIER
克罗伊登,亨顿,沃尔瑟姆,这一个
这就是我查看SQL查询的方式,但我可能在某处无法使用/或[]。我希望你明白这一点。
;WITH results AS (
SELECT branchNode.value('*:Branch/BranchResult/@Branch[1]', 'varchar(20)') AS Branch1
,branchNode.value('*:Branch/BranchResult/@Branch[2]', 'varchar(20)') AS Branch2
,branchNode.value('*:Branch/BranchResult/@Branch[3]', 'varchar(20)') AS Branch3
,ValuationNode.value('*:IDENTIFIER[1]', 'varchar(64)') AS IDENTIFIER,
FROM WWACGuidePriceLookup
CROSS APPLY res.nodes('//Top') AS branchNodes(branchNode)
CROSS APPLY res.nodes('//*:Top') AS ValuationNodes(ValuationNode)
where id = 2
) select * from results
对不起,这是我的第一次尝试,我的格式化垃圾。 我只需要一些东西来帮助我获取值和属性。
答案 0 :(得分:1)
以下内容应该是你要做的事情。
if object_id('tempdb.dbo.#tmp') is not null
drop table #tmp;
create table #tmp (x xml);
insert into #tmp (x) values
( '<Top>
<Branch>
<BranchResult Version="1.0" Branch="Croydon" MilesToTravel="11" />
<BranchResult Version="1.0" Branch="Hendon" MilesToTravel="11" />
<BranchResult Version="1.0" Branch="Waltham" MilesToTravel="18" />
</Branch>
<Valuation>
<ValuationResult Version="1.0" IDENTIFIER="thisOne" GuideLow="3159" GuideHigh="4196" />
</Valuation>
</Top>');
select
BranchNode.value('(BranchResult/@Branch)[1]', 'varchar(20)') as Branch1,
BranchNode.value('(BranchResult/@Branch)[2]', 'varchar(20)') as Branch2,
BranchNode.value('(BranchResult/@Branch)[3]', 'varchar(20)') as Branch3,
ValuationNode.value('(ValuationResult/@IDENTIFIER)[1]', 'varchar(64)') as IDENTIFIER
from #tmp
cross apply #tmp.x.nodes('/Top/Branch') as b(BranchNode)
cross apply #tmp.x.nodes('/Top/Valuation') as v(ValuationNode);
我在调用value()
函数时更改了xpath表达式。具体来说,我对路径进行了限定而不是使用通配符,并在将索引放入路径以生成标量值之前用括号包围路径本身。