字串值的相關函式 - contains

適用於:SQL Server

傳回 xs:boolean 類型的值,指出 $arg 1 的值是否包含 $arg 2 所指定的字串值。

語法

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

引數

$arg 1
要測試的字串值。

$arg 2
要尋找的子字串。

備註

如果 $arg 2 的值是長度為零的字串,則函式會傳回 True。 如果 $arg 1 的值是長度為零的字串,且 $arg 2 的值不是零長度字串,則函式會傳回 False。

如果 $arg 1 或 $arg 2 的值是空序列,自變數就會被視為長度為零的字串。

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

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

為了取得不區分大小寫的比較, 可以使用大寫 或小寫函式。

補充字元 (Surrogate 字組)

XQuery 函式中 Surrogate 配對的行為取決於資料庫相容性層級,在某些情況下,則取決於函式的預設命名空間 URI。 更多資訊請參閱 ALTER DATABASE 相容性等級(Transact-SQL) 及 校對與Unicode支援。

範例

本主題針對 AdventureWorks 資料庫中各種 xml 類型數據行中儲存的 XML 實例,提供 XQuery 範例。

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 AdventureWorks2022;
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>