sql通配符用法参考

发布时间:2019-10-08编辑:脚本学堂
本文介绍了sql通配符的用法,有关sql server通配符的实例参考,有需要的朋友可以看看。

在搜索数据库中的数据时,sql 通配符可以替代一个或多个字符。
sql 通配符必须与 like 运算符一起使用。
like关键字共有四种通配符。“%”代表“包含0个或更多字符的任意字符串”;“_”代表“任何单个字符”;“[]”代表“指定范围(例如 [a-f])或集合(例如 [abcdef])内的任何单个字符”;“[^]”代表“不在指定范围(例如 [^a - f])或集合(例如 [^abcdef])内的任何单个字符”。
 

复制代码 代码示例:
select * from sysobjects where [name] like '%sys%'---包含字符串"sys"的所有记录
union all
select * from sysobjects where [name] like 's_s_t_'---包含单词"s""s""t"并穿插一个任意单词的所有记录
union all
select * from sysobjects where [name] like '_ysrowsets'---包含一个任意单词开头且以字符串"ysrowsets"结尾的所有记录
union all
select * from sysobjects where [name] like 'j%s'---包含单词"j"开头"s"结尾的所有记录
union all
select * from sysobjects where [name] like '[qe]%'---包含单词"q"或"e"开头的所有记录
union all
select * from sysobjects where [name] like '[^djsmupftqe]%'---不包含单词"d,j,s,m,u,p,f,t,q,e"开头的所有记录
union all
select * from sysobjects where [name] like '[^a-s]%'--不包含单词"a"到"s"开头的所有记录
union all
select * from sysobjects where [name] like '%[_]ins'---包含单词"_ins"并以此结尾的所有记录
/*或使用 charindex 或patindex
返回指定表达式中某模式第一次出现的起始位置;如果在全部有效的文本和字符数据类型中没有找到该模式,则返回零。
*/
union all
select * from sysobjects where charindex('%s1%',[name])> 0 ---包含单词"s1"的所有记录
union all
select * from sysobjects where patindex('%s1%',[name])> 0 ---包含单词"s1"的所有记录

使用通配符可以编辑复杂的搜索字符串。假如要确定一个字符串是否包含字母a和z,还有任何数字,这个parindex函数命令可能像这样:
patindex('%[a,z,0-9]%[a,z,0-9]%[a,z,0-9]%','xyzabc123')
 
注意,在使用函数时 charindex > like > padindex  效率依次递减。