返回 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 的值是空序列,则该参数将被作为长度为零的字符串来处理。
contains() 函数使用 XQuery 默认的 Unicode 码位排序规则来进行字符串比较。
为 $arg2 指定的子字符串值必须小于或等于 4000 个字符。 如果指定的值大于 4000 个字符,将出现动态错误情形,并且 contains() 函数将返回空序列(而非布尔值 True 或 False)。 SQL Server 不会对 XQuery 表达式生成动态错误。
若要进行不区分大小写的比较,可以使用 upper-case 或 lower-case 函数。
补充字符(代理项对)
XQuery 函数中代理对的行为依赖于数据库兼容级别,并且在某些情况下,还依赖于函数的默认命名空间 URI。 有关详细信息,请参阅主题SQL Server 2014 中数据库引擎功能的重大更改中的“XQuery 函数可识别代理”部分。 另请参阅 ALTER DATABASE 兼容性级别 (Transact-SQL) 和排序规则和 Unicode 支持。
示例
本主题提供了一些针对 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>