How to replace the value of the * all * attribute with appropriate elements using XQuery?

I'm trying without luck to create a modify () statement to change the attribute value in all elements that have this attribute value - for now, I can only make it change the value in the first matching element. I created an example below of what I still have that I am running in 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;

Doing this gives the results below - only the first copy of the Phoenix cardinals has been changed.

<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>

Could you help me with the correct modify () statement to replace all instances?

Thanks!
Kevin

+3
source share
1 answer

- ( , ) :

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")
');

.

+5

Source: https://habr.com/ru/post/1720082/


All Articles