我有一个存储在sql server 2005中的xml文档,我希望从xml元素中的id属性中找到所有重复的值。 xml看起来像这样:
<?xml version="1.0" encoding="utf-8"?>
<session sessionValue="" id="ID-1">
<data id="ID-3">
<id>d394E6FF844734CB9A5E8B17612DC050A</id>
<TotalResult>803</TotalResult>
<AgencyListRequestURL>http://ews.harleysvillegroup.com:5555/invoke/HmiPortalDCTRedirect.flows:getAgencyList</AgencyListRequestURL>
<system id="systemid">
<global id="ID-2">
<id>gEBE0E6C2D61340698B264E30D1B2DC59</id>
<Button />
<GlobalOutputSpacer />
<Spacer />
<LocationIDToCompare />
<MasterManuScriptID />
<CurrentVehicle />
</global>
<page id="ID-2">
<id>p7B81433D8EB4400CA775CB3F7F0AD4DE</id>
<DialogMode>0</DialogMode>
<DifferentAddress>0</DifferentAddress>
</page>
</system>
</data>
</session>
在本例中,我希望生成一个sql结果,该结果查看整个XML文档中的所有“ID”属性,并告诉我“ID-2”是重复值。
这在XPATH中可行吗?
感谢您的帮助!
答案 0 :(得分:3)
select id, count(*)
from (
select x.value('@id', 'varchar(100)') as id
from @x.nodes('//*[@id]') t(x)) as ids
group by id
having count(*) > 1;
关键是XPath //*[@id]
,它选择具有id
属性的所有文档元素。
<强>更新强>
如果XML在表字段中:
select id, count(*)
from (
select x.value('@id', 'varchar(100)') as id
from [<table>]
cross apply [<table>].[<field>].nodes('//*[@id]') t(x)) as ids
group by id
having count(*) > 1;
这将在所有行中选择重复值。如果要仅在每行中选择重复的属性值,请通过以下方式将表主键添加到组中:
select id, <primary key>, count(*)
from (
select x.value('@id', 'varchar(100)') as id
, <primary key>
from [<table>]
cross apply [<table>].[<field>].nodes('//*[@id]') t(x)) as ids
group by id, <primary key>
having count(*) > 1;