Updating counter in XQuery

后端 未结 7 1936
孤街浪徒
孤街浪徒 2020-12-10 13:39

I want to create a counter in xquery. My initial attempt looked like the following:

let $count := 0
for $prod in $         


        
7条回答
  •  萌比男神i
    2020-12-10 13:53

    As @Ranon said, all XQuery values are immutable, so you can't update a variable. But if you you really need an updateable number (shouldn't be too often), you can use recursion:

    declare function local:loop($seq, $count) {
      if(empty($seq)) then ()
      else
        let $prod  := $seq[1],
            $count := $count + 1
        return (
          { $count },
          local:loop($seq[position() > 1], $count)
        )
    };
    
    local:loop($collection, 0)
    

    This behaves exactly as you intended with your example.

    In XQuery 3.0 a more general version of this function is even defined in the standard library: fn:fold-right($f, $zero, $seq)

    That said, in your example you should definitely use at $count as shown by @tohuwawohu.

提交回复
热议问题