当前位置:文章写作网 >日记 >日记 >charindex函数介绍

charindex函数介绍

2008-04-24 11:36 作者:tshfang 阅读量:9992 推荐15次 | 我要投稿

一、语法

CHARINDEX ( char1 ,string1 [ , start_location ] )

如果 char1 或 string1 之一是 Unicode 数据类型(nvarchar 或 nchar)而另一个不是,则将另一个转换为 Unicode 数据类型。CHARINDEX 不能与 text、ntext 和 image 数据类型一起使用。

如果 char1 或 string1 之一为 NULL,并且数据库兼容级别为 70 或更高,则 CHARINDEX 将返回 NULL。如果数据库兼容级别为 65 或更低,则 CHARINDEX 将仅在 char1 和 string1 都为 NULL 时才返回 NULL 值。

如果在 char1 内找不到 string1,则 CHARINDEX 返回 0。

char1 一个表达式,其中包含要查找的字符的序列。

string1 一个表达式,通常是一个为指定序列搜索的列。string1 属于字符串数据类别。

start_location 开始在 string1 中搜索 char1 时的字符位置。

如果 start_location 未被指定、是一个负数或零,则将从 string1 的开头开始搜索。start_location 可以是 bigint 类型。

string1 中包含 char1 时返回字符位置

string1 中不包含 char1 时返回0

二、举例

USE AdventureWorks

SELECT CHARINDEX('bicycle', DocumentSummary)

FROM Production.Document

WHERE DocumentID = 3;

返回结果为48。

SELECT CHARINDEX('bicycle1', DocumentSummary, 5)

FROM Production.Document

WHERE DocumentID = 3;

返回结果为0。

查询DocumentSummary字段中包含"bicycle"的所有行。

一般大家都会写成这样:

select * from Production.Document

where DocumentSummary like'%bicycle%'

了解这个函数以后,大家可以这样写:

select * from Production.Document

where charindex('bicycle',DocumentSummary)>0

这种方法比like'%%'的形式速度上要快很多.

数据库优化的时候可以考虑使用sql 2005的函数.

其他人在看啥

    《charindex函数介绍》的评论 (共 0 条)

    • Guest::piaoliang