xquery version '1.0'; let $newuniqueid := let $olduniqueid := let $part as xs:integer := let $resource := let $allparts := ( for $exercise in doc($resource)/*/exercise[ variables/uniqueid = $olduniqueid ] order by xs:dateTime($exercise/dateTime) return $exercise ) let $numparts := count($allparts) let $newpart := min((max(($part,1)),$numparts)) let $relevantexercises := $allparts[ position() < $newpart + 1 ] let $updatedexercises := ( for $exercise in $relevantexercises let $variables-copy := $exercise/variables/*[not(self::uniqueid)] let $resource-and-date := $exercise/*[not(self::variables)] return { $variables-copy } {$newuniqueid} { $resource-and-date } ) return (update insert $updatedexercises into doc($resource)/exercises )