Escaping wildcards in LIKE

喜夏-厌秋 提交于 2019-11-27 08:46:40

问题


How do I escape wildcards (_ and %) when using a SQL LIKE operator in Oracle?

I came to a silly issue today. I need to search for the presence of an underscore _ on a varchar column using LIKE. It doesn't work -- as expected -- since underscores are wildcards according to SQL. Here's my (simpified) code:

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');

I tried the following queries in PostgreSQL and they return the rows I want:

select * from property where name like '%\_%'; -- should return: max_width

select * from property where name like '%\%%'; -- should return: taxrate%

Unfortunately it doesn't work in Oracle 12c. Is there a "standard" way of escaping wildcards? Or at least something that works in Oracle?


回答1:


You can use 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.

So you can do:

select * from property where name like '%\_%' escape '\';

NAME                 VALUE                                             
-------------------- --------------------------------------------------
max_width            90                                                

select * from property where name like '%\%%' escape '\';

NAME                 VALUE                                             
-------------------- --------------------------------------------------
taxrate%             5.20                                              


来源:https://stackoverflow.com/questions/51068202/escaping-wildcards-in-like

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!