【问题标题】:Escaping wildcards in LIKE在 LIKE 中转义通配符
【发布时间】:2018-06-27 17:13:02
【问题描述】:

在 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 中尝试了以下查询,它们返回了我想要的行:

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

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

不幸的是,它在 Oracle 12c 中不起作用。是否有转义通配符的“标准”方式?或者至少可以在 Oracle 中使用?

【问题讨论】:

  • 你应该使用 unicode 表示

标签: sql oracle sql-like


【解决方案1】:

您可以使用the escape syntax

您可以使用标识转义字符的ESCAPE 子句在模式中包含实际字符%_。如果转义字符在模式中的字符 %_ 之前,则 Oracle 在模式中按字面意思解释此字符,而不是作为特殊的模式匹配字符。

所以你可以这样做:

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

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

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

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

【讨论】:

  • 作为一个有点相关的说明,在 MySQL 中有一个细微的变化(需要转义反斜杠): ... escape '\\';
  • 另外值得一提的是,您不必使用反斜杠字符。
  • 嗯,是的,该子句指定要使用的转义字符...尽管大多数示例似乎默认为反斜杠。还可以提到您可以通过重复搜索转义字符本身(在文档中显示为@@@)。
猜你喜欢
  • 2021-12-22
  • 2017-06-28
  • 2011-03-01
  • 2023-04-06
  • 1970-01-01
  • 2014-03-28
  • 1970-01-01
相关资源
最近更新 更多