[英]How to replace attribute value of *all* matching elements with XQuery?
I'm trying without luck to create a modify() statement to change the value of an attribute in all elements that have that attribute value -- so far I can only get it to change the value in the first matched element. 我正在努力创建一个modify()语句来改变具有该属性值的所有元素中属性的值 - 到目前为止,我只能让它来改变第一个匹配元素中的值。 I created an example below of what I have so far, which I'm running in SQL Server 2005:
我在下面创建了一个示例,我在SQL Server 2005中运行:
DECLARE @x XML
SELECT @x = '
<FootballApparel>
<Item Team="Phoenix Cardinals" Type="Hat" Cost="$14.99" />
<Item Team="Indianapolis Colts" Type="Hat" Cost="$14.99" />
<Item Team="Cincinnati Bengals" Type="Hat" Cost="$14.99" />
<Item Team="Phoenix Cardinals" Type="Shirt" Cost="$21.99" />
<Item Team="Indianapolis Colts" Type="Shirt" Cost="$21.99" />
<Item Team="Cincinnati Bengals" Type="Shirt" Cost="$21.99" />
</FootballApparel>
';
SET @x.modify('
replace value of
(/FootballApparel/Item[@Team="Phoenix Cardinals"]/@Team)[1]
with "Arizona Cardinals"
');
SELECT @x;
Running this gives the results below -- only the first instance of Phoenix Cardinals has been changed. 运行此命令会得到以下结果 - 只有Phoenix Cardinals的第一个实例已被更改。
<FootballApparel>
<Item Team="Arizona Cardinals" Type="Hat" Cost="$14.99" />
<Item Team="Indianapolis Colts" Type="Hat" Cost="$14.99" />
<Item Team="Cincinnati Bengals" Type="Hat" Cost="$14.99" />
<Item Team="Phoenix Cardinals" Type="Shirt" Cost="$21.99" />
<Item Team="Indianapolis Colts" Type="Shirt" Cost="$21.99" />
<Item Team="Cincinnati Bengals" Type="Shirt" Cost="$21.99" />
</FootballApparel>
Can you please help me with the correct modify() statement to replace all instances? 你能帮我用正确的modify()语句替换所有实例吗?
Thanks! 谢谢!
Kevin 凯文
You're very close - what you need to do is loop (and there's no other way I know of to do it in this case) and repeatedly replace the values: 你非常接近 - 你需要做的是循环(在这种情况下我没有别的办法知道)并重复替换值:
WHILE @x.exist('(/FootballApparel/Item[@Team=sql:variable("@oldTeamName")])[1]') = 1
SET @x.modify('
replace value of (
/FootballApparel/Item[@Team=sql:variable("@oldTeamName")]/@Team
)[1]
with sql:variable("@newTeamName")
');
That should do the trick. 这应该够了吧。
Marc 渣
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.