如何使用SQL Server查询XML列中的索引值



我需要查询下面XML列中的所有id值,并且需要一些帮助。如何在select语句中使用索引值?如有任何帮助/指导,我们将不胜感激。谢谢

这是XML文件:

<rotation>
<adjuster id="3381" index="0" />
<adjuster id="7629" index="1" />
<adjuster id="10087" index="2" />
<adjuster id="10741" index="3" />
<adjuster id="11544" index="4" />
<adjuster id="12367" index="5" />
</rotation>

这是我的select语句,但只得到返回的第一个值:

select 
t.AssignmentRotation.value('(/rotation/adjuster/@id)[1]','varchar(max)') as adjuster_id 
from 
dbo.CMS_AdjusterTeam t 
where 
t.AdjusterTeamSysID IN (5, 6);

下面的片段演示了如何提取所有Id和索引值:

declare @xml xml = N'<rotation>
<adjuster id="3381" index="0" />
<adjuster id="7629" index="1" />
<adjuster id="10087" index="2" />
<adjuster id="10741" index="3" />
<adjuster id="11544" index="4" />
<adjuster id="12367" index="5" />
</rotation>'
select Id = rt.aj.value('@id', 'varchar(5000)'),
[Index] = rt.aj.value('@index', 'varchar(5000)')
from (select XmlData = @xml) t
cross apply t.XmlData.nodes('//rotation/adjuster') rt(aj)

所以你的最终查询会是这样的:

select rt.aj.value('@id','varchar(max)') as adjuster_id 
from dbo.CMS_AdjusterTeam t 
cross apply t.AssignmentRotation.nodes('//rotation/adjuster') rt(aj)
WHERE t.AdjusterTeamSysID IN (5, 6);

最新更新