基于字符串值的函数 - 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 () 函数返回空序列,而不是 TrueFalse 的布尔值。 SQL Server不会在 XQuery 表达式上引发动态错误。

为了获取不区分大小写的比较,可以使用 大写 或小写函数。

补充字符(代理项对)

XQuery 函数中代理对的行为依赖于数据库兼容级别,并且在某些情况下,还依赖于函数的默认命名空间 URI。 有关详细信息,请参阅主题 2016 SQL Server 中数据库引擎功能的中断性变更中的“XQuery 函数可识别代理项”部分。 另请参阅 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>

另请参阅

针对 xml 数据类型的 XQuery 函数