string 函數 (XQuery)

傳回以字串表示的 $arg 值。

語法

fn:string() as xs:string
fn:string($arg as item()?) as xs:string

引數

  • $arg
    是一個節點或不可部份完成的值。

備註

  • 如果 $arg 是空白時序,就會傳回長度為零的字串。

  • 如果 $arg 是一個節點,該函數會傳回使用字串值存取子而取得之節點的字串值。這定義在 W3C XQuery 1.0 及 XPath 2.0 Data Model 規格中。

  • 如果 $arg 是不可部份完成的值,函數就會傳回相同的字串,此字串是由運算式轉換為 xs:string、$arg 後傳回,另有註明時除外。

  • 如果 $arg 的類型為 xs:anyURI,則會將 URI 轉換成沒有逸出特別字元的字串。

  • 在此實行中,沒有引數的 fn:string() 只能在內容相依述詞的內容中使用。尤其是只能在方括號 ([ ]) 內使用。

範例

此主題提供 XML 執行個體的 XQuery 範例,它儲存在 AdventureWorks 資料庫中的不同 xml 類型資料行中。如需這些資料行中每個資料行的概觀,請參閱<在 AdventureWorks 資料庫中的 xml 資料類型表示法>。

A. 使用 string 函數

以下查詢會擷取 <ProductDescription> 元素的 <Features> 子元素。

SELECT CatalogDescription.query('
declare namespace PD="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription";
 /PD:ProductDescription/PD:Features
')
FROM Production.ProductModel
WHERE ProductModelID=19

以下是部份結果:

<PD:Features xmlns:PD="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription">
   These are the product highlights. 
   <p1:Warranty xmlns:p1="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelWarrAndMain">
    <p1:WarrantyPeriod>3 years</p1:WarrantyPeriod>
    <p1:Description>parts and labor</p1:Description>
   </p1:Warranty>
       ...
</PD:Features>

如果指定 string() 函數,就會接收到指定節點的字串值。

SELECT CatalogDescription.query('
declare namespace PD="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription";
 string(/PD:ProductDescription[1]/PD:Features[1])
')
FROM Production.ProductModel
WHERE ProductModelID=19

以下是部份結果。

These are the product highlights. 
3 yearsparts and labor...  

B. 在不同節點上使用 string 函數

在以下範例中,XML 執行個體會指定給一個 xml 類型變數。指定查詢以說明對不同節點套用 string() 的結果。

declare @x xml
set @x = '<?xml version="1.0" encoding="UTF-8" ?>
<!--  This is a comment -->
<root>
  <a>10</a>
just text
  <b attr="x">20</b>
</root>
'

以下查詢會擷取文件節點的字串值。此值是串連所有下階文字節點的字串值而成。

select @x.query('string(/)')

以下是結果:

This is a comment 10
just text
 20

以下查詢會嘗試擷取處理指示節點的字串值。因為並不包含文字節點,所以結果會是空白時序。

select @x.query('string(/processing-instruction()[1])')

以下查詢會擷取註解節點的字串值,並傳回文字節點。

select @x.query('string(/comment()[1])')

以下是結果:

This is a comment