[英]SQL querying XML attributes
我有一个要使用SQL查询的XML。
<QueryB>
<investment name="InvestmentA">
<Account Type="DIVIDEND">
<glsum YTD="0.0000" />
<glsum Inception="111111.0000" />
<glsum QTD="0.0000" />
</Account>
</investment>
<investment name="InvestmentB">
<Account Type="DIVIDEND">
<glsum YTD="0.0000" />
<glsum Inception="222222.0000" />
<glsum QTD="0.0000" />
</Account>
</investment>
<investment name="InvestmentC">
<Account Type="CAP">
<glsum YTD="90.0000" />
<glsum Inception="333333.0800" />
<glsum QTD="90.0000" />
</Account>
</investment>
<investment name="InvestmentD">
<Account Type="CAP">
<glsum YTD="0.0000" />
<glsum Inception="555555.0000" />
<glsum QTD="0.0000" />
</Account>
<Account Type="DIVIDEND">
<glsum YTD="0.0000" />
<glsum Inception="444444.0000" />
<glsum QTD="0.0000" />
</Account>
</investment>
请注意,InvestmentD具有股息和上限帐户类型。 因此,我尝试使用以下查询此数据:
select rtrim(ltrim(t.c.value('@name', 'nvarchar(500)'))) as name,
rtrim(ltrim(t.c.value('(Account/@Type)[1]', 'nvarchar(500)'))) as Type,
rtrim(ltrim(t.c.value('(Account/glsum/@YTD)[1]', 'nvarchar(500)'))) as YTD,
rtrim(ltrim(t.c.value('(Account/glsum/@Inception)[1]', 'nvarchar(500)'))) as inception,
rtrim(ltrim(t.c.value('(Account/glsum/@QTD)[1]', 'nvarchar(500)'))) as QTD
from @x.nodes('/QueryB/investment')t(c)
其中@x是XML。 这种毫不奇怪的是,不会从InvestmentD获得两个节点。 我不知道如何解析所有节点。 朝着正确方向的指针将不胜感激。 谢谢。
添加cross apply tcnodes('Account') as a(c)
并从ac
获取属性值,而无需在xPath表达式中指定Acount
。
名称仍应使用tc
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.