在 LIKE 中转义通配符
Escaping wildcards in LIKE
在 Oracle 中使用 SQL LIKE
运算符时如何转义通配符(_
和 %
)?
我今天遇到了一个愚蠢的问题。我需要使用 LIKE
在 varchar 列上搜索是否存在下划线 _
。它不起作用——如预期的那样——因为根据 SQL,下划线是通配符。这是我的(简化的)代码:
create table property (
name varchar(20),
value varchar(50)
);
insert into property (name, value) values ('port', '8120');
insert into property (name, value) values ('max_width', '90');
insert into property (name, value) values ('taxrate%', '5.20');
我在 PostgreSQL 中尝试了以下查询,它们 return 我想要的行:
select * from property where name like '%\_%'; -- should return: max_width
select * from property where name like '%\%%'; -- should return: taxrate%
不幸的是,它在 Oracle 12c 中不起作用。是否有 "standard" 转义通配符的方法?或者至少可以在 Oracle 中运行?
您可以使用the escape
syntax
You can include the actual characters %
or _
in the pattern by using the ESCAPE
clause, which identifies the escape character. If the escape character precedes the character %
or _
in the pattern, then Oracle interprets this character literally in the pattern rather than as a special pattern-matching character.
所以你可以这样做:
select * from property where name like '%\_%' escape '\';
NAME VALUE
-------------------- --------------------------------------------------
max_width 90
select * from property where name like '%\%%' escape '\';
NAME VALUE
-------------------- --------------------------------------------------
taxrate% 5.20
在 Oracle 中使用 SQL LIKE
运算符时如何转义通配符(_
和 %
)?
我今天遇到了一个愚蠢的问题。我需要使用 LIKE
在 varchar 列上搜索是否存在下划线 _
。它不起作用——如预期的那样——因为根据 SQL,下划线是通配符。这是我的(简化的)代码:
create table property (
name varchar(20),
value varchar(50)
);
insert into property (name, value) values ('port', '8120');
insert into property (name, value) values ('max_width', '90');
insert into property (name, value) values ('taxrate%', '5.20');
我在 PostgreSQL 中尝试了以下查询,它们 return 我想要的行:
select * from property where name like '%\_%'; -- should return: max_width
select * from property where name like '%\%%'; -- should return: taxrate%
不幸的是,它在 Oracle 12c 中不起作用。是否有 "standard" 转义通配符的方法?或者至少可以在 Oracle 中运行?
您可以使用the escape
syntax
You can include the actual characters
%
or_
in the pattern by using theESCAPE
clause, which identifies the escape character. If the escape character precedes the character%
or_
in the pattern, then Oracle interprets this character literally in the pattern rather than as a special pattern-matching character.
所以你可以这样做:
select * from property where name like '%\_%' escape '\';
NAME VALUE
-------------------- --------------------------------------------------
max_width 90
select * from property where name like '%\%%' escape '\';
NAME VALUE
-------------------- --------------------------------------------------
taxrate% 5.20