xqueryzorba

Scope of variables in XQuery?


I have note.xml:

<?xml version="1.0"?>
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

and note.xqy:

let $srcDoc:="note.xml"
for $x in doc($srcDoc)/note
return (),

for $x in doc($srcDoc)/note
return ()

For some reasons I need two fors to process note.xml. I don't want to write the processed file name two times, so I define a variable. Strange is, the variable is not defined in the second for:

$ zorba -i -f -q note.xqy
note.xqy>:5,15: static error [err:XPST0008]: "srcDoc": undeclared variable

Solution

  • A let-bound variable in XQuery is only in scope inside the FLWOR expression it is defined in. In your case that is everything before the comma.

    Since FLWOR expressions can be nested, one solution would be to split the let into it an enclosing expression and put both loops into the return:

    let $srcDoc:="note.xml"
    return (
        for $x in doc($srcDoc)/note
        return (),
    
        for $x in doc($srcDoc)/note
        return ()
    )
    

    Since you bind a constant at the start of your XQuery script, you can also use declare variable, which only works in that case:

    declare variable $srcDoc := "note.xml";
    
    for $x in doc($srcDoc)/note
    return (),
    
    for $x in doc($srcDoc)/note
    return ()