XQuery is a declarative language, you cannot use let
to increment a counter.
A rather hackish workaround to the missing at
feature would be to count the preceding sibling <person/>
tags:
for $person in /Root/Persons/Person
let $count := count($person/preceding-sibling::Person) + 1
return <Person ID="{$count}">{$person}</Person>
Be aware that this code will have O(n^2)
runtime if not optimized by the execution engine (which it will probably not do) because of the repeated preceding sibling scans.
Edit: As stated in the comments, MS SQL doesn't even support the preceding-sibling
axis. They do support the <<
node order comparison operator, though. This query should be fully supported:
for $person in /Root/Persons/Person
let $count := count($person/parent::Persons/Person[. << $person]) + 1
return <Person ID="{$count}">{$person}</Person>
By the way, you possibly only want to paste the person's name, so better use
(: snip :)
return <Person ID="{$count}">{data($person)}</Person>