- 我的电脑系统:Windows 10 64位
- SQL Server 软件版本: SQL Server 2014 Express
本篇博客里面使用了 scott
库,如何你现在还没有添加这个库到你的服务器里面,请在查看本篇博客前,访问这篇博文来在你的服务器里面附加scott
库。
怎样编写模糊查询语句
1
2
3
4
5
6
| select * from emp where ename like '%A%'
--ename只要含有字母A就输出
select * from emp where ename like 'A%'
--ename只要首字母是A的就输出
select * from emp where ename like '%A'
--ename只要尾字母是A的就输出
|



1
2
| select * from emp where ename like '_A%'
--ename只要第二个字母是A的就输出
|

1
2
| select * from emp where ename like '_[A-F]%'
--把ename中第二个字符是A或者B或者C或者D或者E或者F的记录输出
|

1
2
| select * from emp where ename like '_[^A-F]%'
--把ename中第二个字符不是A也不是B也不是C也不是D也不是E也不是F的记录输出
|

创建一个 student
表。(预备操作)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| create table student
(
name nvarchar(20) null,
age int
);
insert into student values ('张三', 68);
insert into student values ('Tom', 66);
insert into student values ('a_b', 22);
insert into student values ('c%d', 44);
insert into student values ('abc_fe', 56);
insert into student values ('haobin', 25);
insert into student values ('HapBin', 88);
insert into student values ('c%', 66);
insert into student values ('long''s', 100)
select * from student;
|

1
2
3
4
| select * from student where name like '%\%%' escape '\'
--把name中包含有%的输出
select * from student where name like '%\_%' escape '\'
--把name中包含有_的输出
|


总结: 通配符:
格式: select 字段的集合 from 表名 where 某个字段的名字 like 匹配的条件
匹配的条件通常含有通配符
%
_
(这个是下划线,不是减号)
[a-f]
a
到 f
中的任意单个字符。只能是a
、b
、c
、d
、e
、f
中的任意一个字符
[a, f]
[^a-c]
注意:
- 匹配的内容必须使用单引号括起来。不能省略,也不能改用双引号。
escape '\'
里面 escape
后面 ''
里面的\
字符就自定义的:通配符。它可以替换成其他的字符(比如:a
、b
、m
等等)。