取代表示式
取代表示式會將現有節點取代為零個以上節點的新序列,或在保留節點身分的同時取代節點的值。
語法
- do replace
- 以取代表示式開頭的關鍵字。
- TargetExpression
- 不是更新表示式的 XQuery 表示式。 如果表示式包括最上層逗點運算子,則表示式必須以括弧括住。 TargetExpression 的結果必須是非文件節點的單一節點。 如果 TargetExpression 的結果是文件節點,則 Db2 XQuery 會傳回錯誤。
如果未指定 value of 關鍵字,則 TargetExpression 的結果必須是母項內容不是空的單一節點。
- value of
- 指定在保留節點身分時取代 TargetExpression 節點值的關鍵字。
- with
- 以來源表示式開頭的關鍵字。
- SourceExpression
- 不是更新表示式的 XQuery 表示式。 如果表示式包括最上層逗點運算子,則表示式必須以括弧括住。
如果指定 value of 關鍵字,則會將 SourceExpression 評估為文字節點建構子的內容表示式。 SourceExpression 的結果是單一文字節點或空序列。
如果未指定 value of 關鍵字,則 SourceExpression 的結果必須是一連串節點。 SourceExpression 會評估為以元素建構子括住的表示式。 如果 SourceExpression 序列包含文件節點,則該文件節點會取代為其子項。 SourceExpression 序列必須由下列節點類型組成:
- 如果 TargetExpression 節點是屬性節點,則取代序列必須由零個以上屬性節點組成。
- 如果 TargetExpression 節點是元素、文字、註解或處理指示節點,則取代序列必須包含零或多個元素、文字、註解或處理指示節點的組合。
當指定 value
of 關鍵字時,會產生下列更新項目:
- 如果 TargetExpression 節點是元素節點,則 SourceExpression所傳回的文字節點會取代 TargetExpression 節點的現有子項。 如果 SourceExpression 傳回空序列,則 TargetExpression 節點的子項內容會變成空的。 如果 TargetExpression 節點包含屬性節點,則它們不受影響。
- 如果 TargetExpression 節點不是元素節點,則 TargetExpression 節點的字串值會取代為 SourceExpression所傳回之文字節點的字串值。 如果 SourceExpression 未傳回文字節點,則 TargetExpression 節點的字串值會取代為長度為零的字串。
未指定 value
of 關鍵字時,會產生下列更新項目:
- SourceExpression 節點會取代 TargetExpression 節點。 TargetExpression 節點的母節點會變成每一個 SourceExpression 節點的母節點。 SourceExpression 節點佔用 TargetExpression 節點所佔用節點階層中的位置。
- TargetExpression 節點、其所有屬性及後代都會與節點序列分離。
範例
下列範例使用來自 Db2 SAMPLE 資料庫的 CUSTOMER 表格。 在 CUSTOMER 表格中, XML 直欄 INFO 包含客戶地址和電話資訊。
在下列範例中,轉換表示式的 copy 子句會從直欄 INFO 建立 XML 文件的副本。 取代表示式會取代 addr 元素及其子項:
xquery
transform
copy $mycust := db2-fn:sqlquery('select info from customer where cid = 1000')
modify
do replace $mycust/customerinfo/addr
with
<addr country="Canada">
<street>1596 14th Avenue NW</street>
<city>Calgary</city>
<prov-state>Alberta</prov-state>
<pcode-zip>T2N 1M7</pcode-zip>
</addr>
return $mycust
針對 SAMPLE 資料庫執行時,表示式會傳回下列結果及被取代的位址資訊:
<customerinfo Cid="1000">
<name>Kathy Smith</name>
<addr country="Canada">
<street>1596 14th Avenue NW</street>
<city>Calgary</city>
<prov-state>Alberta</prov-state>
<pcode-zip>T2N 1M7</pcode-zip>
</addr>
<phone type="work">416-555-1358</phone>
</customerinfo>
下列表示式會將客戶電話元素的 type 屬性值從 home 取代為 personal:
xquery
transform
copy $mycust := db2-fn:sqlquery('select info from customer where cid = 1004')
modify
do replace value of $mycust/customerinfo/phone[@type="home"]/@type with "personal"
return $mycust針對 SAMPLE 資料庫執行時,表示式會傳回具有被取代屬性值的下列結果:
<customerinfo Cid="1004">
<name>Matt Foreman</name>
<addr country="Canada">
<street>1596 Baseline</street>
<city>Toronto</city>
<prov-state>Ontario</prov-state>
<pcode-zip>M3Z 5H9</pcode-zip>
</addr>
<phone type="work">905-555-4789</phone>
<phone type="personal">416-555-3376</phone>
<assistant>
<name>Gopher Runner</name>
<phone type="home">416-555-3426</phone>
</assistant>
</customerinfo>
助理電話屬性的值未變更。
