1
votes

I want to use the ascending or descending option dynamically based on xpath value.

let $order := "ascending"
for $aRslt in ("1","2","3","4")
    order by ($aRslt)
    if($order eq "ascending") then ascending else descending
return $aRslt

Using this throwing Error.

We can have the if condition for the whole "for" statement. But when we have more conditions in where; order by; and lot of statements in return, then it looks code duplicating just for the ascending or descending.

Is there any option to use without using condition for the whole "for".

1
Good question! Unfortunately, the XQuery spec doesn't really cover variable order by specifications (same problem with empty greatest). We use the same workaround as Tyler suggested.dirkk
It would be better if the XQuery spec has the variable order by specification. Is it done by purpose or any chance for this to be done in the future release?Karthick
I think it just didn't come up often enough. I found this issue: w3.org/Bugs/Public/show_bug.cgi?id=17599 If you want to support this issue maybe raise your concern in the bugtracker or on the xquery-talk mailing list. I think there is a real use case here and it is possible to include this in a future version of the spec.dirkk

1 Answers

4
votes

Whenever I've had to order dynamically this is whats worked best for me. It takes advantage of multiple order spec. (http://www.w3.org/TR/xquery/#id-orderby-return) This is a bit different because of order Modifier being a token and not a variable or expression so it can be hard to work with. And that's why you have to have the two if statements and the empty else statements.

   let $order := "ascending"
    for $aRslt in ("1","2","3","4")
         order by 
         if($order eq "ascending") then $aRslt else() ascending,
         if($order eq "descending") then $aRslt else () descending
    return $aRslt