I have this XML in SQL Server 2008:
DECLARE @xml xml = '<Root>
<Contacts>
<Contact name="John Doe" type="REG" other="value" />
<Contact name="Jane Doe" type="REG" other="value" />
<Contact name="Jennifer Doe" type="REG" other="value" />
<Contact name="Jane Doe" type="REG" other="value" />
</Contacts>
</Root>'
I want to change the value of the types to something else. I can hard code which one(s) I want to change with no problem.
SET @xml.modify('replace value of (/Root/Contacts/Contact)[1]/@type with "NEW"')
SELECT @xml
That "does the right thing," regardless of what value I put in the brackets. IOW, the above changes the first one, changing it to [3] changes the third one, etc.
I want to change all of them, regardless of how many or how few there are. So, I need to get the count, then iterate over them using a variable. Getting the count is easy, but I can't get the variable to work.
IOW, this XML, which just replaces the [1] above with the variable, doesn't work.
DECLARE @i int = 1
SET @xml.modify('replace value of (/Root/Contacts/Contact)[sql:variable("@i")]/@type with "NEW"')
SELECT @xml
It gives me this error, which is telling me I did something wrong, but I can't grok the error to figure out what I did wrong:
Msg 2337, Level 16, State 1, Line 14
XQuery [modify()]: The target of 'replace' must be at most one node, found 'attribute(type,xdt:untypedAtomic) *'
As I was about to hit "Post" on this, I found reference to something that said you had to use position() in order to use a variable on the node index, but the example was a query, not a modify. And that doesn't work, either.
DECLARE @i int = 1
SET @xml.modify('replace value of (/Root/Contacts/Contact)[position()=sql:variable("@i")]/@type with "NEW"')
SELECT @xml
I have no doubt this is something easy, but I've searched here and elsewhere for how to use sql:variable, and almost all of the examples I've found are using it as the value in a replace, not the index (none of the "Questions which may already have your answer" helped, either.) I've also experimented with extra parentheses in various places, etc., and just haven't been able to hit on the magic combination.
What am I missing to make the above SET work with @i?