共用方式為


contains 函數 (XQuery)

傳回 xs:boolean 類型的值,指出 $arg1 的值是否包含 $arg2 指定的字串值。

語法

fn:contains ($arg1 as xs:string?, $arg2 as xs:string?) as xs:boolean?

引數

  • $arg1
    要測試的字串值。
  • $arg2
    要尋找的子字串。

備註

如果 $arg2 的值是長度 0 的字串,則此函數傳回 True。如果 $arg1 的值是長度 0 的字串,且 $arg2 的值不是長度 0 的字串,則此函數傳回 False。

如果 $arg1$arg2 的值是空的序列,此引數會當成長度 0 的字串來處理。

contains() 函數使用 XQuery 的預設 Unicode 字碼指標定序來進行字串比較。

$arg2 指定的子字串值必須小於或等於 4000 個字元。如果指定的值大於 4000 個字元,會發生動態錯誤狀況,且 contains() 函數會傳回空的序列,而非布林值 True 或 False。SQL Server 2005 不會對 XQuery 運算式引發動態錯誤。

範例

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

A. 使用 contains() XQuery 函數來搜尋特定的字元字串

下列查詢會尋找產品摘要描述中有包含 Aerodynamic 一字的產品。此查詢會傳回這類產品的 ProductID 及 <Summary> 元素。

WITH XMLNAMESPACES ('https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription' AS pd)
SELECT ProductModelID, CatalogDescription.query('
      <Prod>
         { /pd:ProductDescription/@ProductModelID }
         { /pd:ProductDescription/pd:Summary }
      </Prod>
 ') as Result
FROM Production.ProductModel
where CatalogDescription.value('
  contains( (/pd:ProductDescription/pd:Summary//*/text())[1], 
            "Aerodynamic")','bit')  = 1

注意下列項目是從上一個查詢而來:

  • 產品型號描述文件使用命名空間。因此,namespace 關鍵字定義 XQuery 初構中的命名空間前置詞。
  • WHERE 子句使用 xml 資料類型的 value() 方法。在 Value 方法內,XQuery contains() 函數是用來判斷 <Summary> 文字是否包含 Aerodynamic 一字。contain() 函數傳回的布林值會轉換成 bit。然後會與 1 做比較。

以下是結果:

ProductModelID Result
-------------- ---------
28     <Prod ProductModelID="28">
        <pd:Summary xmlns:pd= 
          "https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription">
         <p1:p xmlns:p1="http://www.w3.org/1999/xhtml">
           A TRUE multi-sport bike that offers streamlined riding and 
           a revolutionary design. Aerodynamic design lets you ride with 
          the pros, and the gearing will conquer hilly roads.</p1:p>
        </pd:Summary>
       </Prod>

請參閱

參考

對 XML 資料類型進行 XQuery 函數

說明及資訊

取得 SQL Server 2005 協助