0
votes

See the following query:

select
  xmlquery
  (
    '
      if ($xml/foo/bar) then
        transform copy $xml := $xml modify do replace $xml/foo/bar with <bar>some stuff</bar> return $xml
      else
        $xml
    '
    passing xmlparse(document '<foo><bar>something here</bar></foo>') as "xml"
  )
from sysibm.sysdummy1

This query works just fine: It replaces the /foo/bar node and I am perfectly happy. In case that the /foo/bar node does not exist I just want nothing to happen. So the following query should just return the unmodified XML:

select
  xmlquery
  (
    '
      if ($xml/foo/bar) then
        transform copy $xml := $xml modify do replace $xml/foo/bar with <bar>some stuff</bar> return $xml
      else
        $xml
    '
    passing xmlparse(document '<foo>nothing here</foo>') as "xml"
  )
from sysibm.sysdummy1

Well... so I thought. In fact DB2 happily tells me:

SQL16085N The target node of an XQuery "replace" expression is not valid.

Maybe I am wrong about the syntax of the if I thought and the "then"-part is executed in both the queries above. So I tried to swap the then and the else, because clearly DB2 should not attempt to execute the then AND the else part. But that did not change anything at all.

Now I am clearly confused. Is it not possible to do what I like to do with XPath, because all path expressions must be satisfied whether they are executed or not? Or am I just doing something wrong?

2
might be interesting for you - all db2 xml possibilities amolnpujari.wordpress.com/2008/04/12/db2-native-xml - Amol Pujari

2 Answers

1
votes

I had similar problem and I solved it so:

select
    xmlquery('
        let $xml0 := <xml><foo><bar/></foo></xml> return
        if ($xml/foo/bar) then
            transform copy $xml := ($xml[foo/bar], $xml0)[1] modify 
            do replace $xml/foo/bar with <bar>some stuff</bar>
            return $xml
        else
            $xml
            ' passing xmlparse(document '<foo>nothing here</foo>') as "xml")
            from sysibm.sysdummy1

It seems like a bug

0
votes

And counln't you use any type of function "exists(....)" for example fn:exists(item1, item2...) where exists function returns true if the value of the arguments IS NOT an empty sequence, otherwise it returns false? Granted that I know nothing about db2 :)