title: XQuery (DB2) replace node if it exists. Possible at all?
body: <p>See the following query:</p>
  
  
  
  <pre class="lang-sql prettyprint-override"><code>select
    xmlquery
    (
      '
        if ($xml/foo/bar) then
          transform copy $xml := $xml modify do replace $xml/foo/bar with &lt;bar&gt;some stuff&lt;/bar&gt; return $xml
        else
          $xml
      '
      passing xmlparse(document '&lt;foo&gt;&lt;bar&gt;something here&lt;/bar&gt;&lt;/foo&gt;') as "xml"
    )
  from sysibm.sysdummy1
  </code></pre>
  
  <p>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:</p>
  
  
  
  <pre class="lang-sql prettyprint-override"><code>select
    xmlquery
    (
      '
        if ($xml/foo/bar) then
          transform copy $xml := $xml modify do replace $xml/foo/bar with &lt;bar&gt;some stuff&lt;/bar&gt; return $xml
        else
          $xml
      '
      passing xmlparse(document '&lt;foo&gt;nothing here&lt;/foo&gt;') as "xml"
    )
  from sysibm.sysdummy1
  </code></pre>
  
  <p>Well... so I thought. In fact DB2 happily tells me:</p>
  
  <blockquote>
    <p>SQL16085N  The target node of an XQuery "replace" expression is not valid.</p>
  </blockquote>
  
  <p>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.</p>
  
  <p>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?</p>