contains 函數 (XQuery)

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

語法

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

引數

  • $arg1
    要測試的字串值。

  • $arg2
    要尋找的子字串。

備註

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

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

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

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

若要取得不區分大小寫的比較,您可以使用 upper-case 或 lower-case 函數。

範例

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

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

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

--The product model description document uses
--namespaces. The WHERE clause uses the exit()
--method of the xml data type. Inside the exit method,
--the XQuery contains()function is used to
--determine whether the <Summary> text contains the word
--Aerodynamic. 

USE AdventureWorks
GO
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.exist('
   /pd:ProductDescription/pd:Summary//text()
    [contains(., "Aerodynamic")]') = 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>