25. instr用法

很多时候,我们要进行字符串匹配,在SQL语句中,我们通常使用like来达到我们搜索的目标。但经过实际测试发现,like的效率与instr函数差别相当大。下面是一些测试结果: 

select instr('abcd','a') from dual;  --返回1
select instr('abcd','c') from dual;  --返回3
select instr('abcd','e') from dual;    --返回0

该函数可以用于模糊查询以及判断包含关系:

例如:

① select code, name, dept, occupation  from staff  where instr(code, '001') > 0;

  等同于

  select code, name, dept, occupation  from staff  where code like '%001%' ;

② select ccn,mas_loc from mas_loc where instr('FH,FHH,FHM',ccn)>0;

  等同于

  select ccn,mas_loc from mas_loc where ccn in ('FH','FHH','FHM');

SQL> select count(*) from t where instr(title,‟oracle‟)>0; COUNT(*) ———- 5478 
Elapsed: 00:00:11.04 


SQL> select count(*) from t where title like ”%oracle%‟; COUNT(*) ———- 5478 
Elapsed: 00:00:31.47

注: 
instr(title,'oracle‟)>0 相当于like 

instr(title,'oracle‟)=0 相当于not like 

--1.从第3个字符开始搜索 
SQL> select instr('oracleor','or', 3) position from dual; 

POSITION 

----------         

     7 


--2.从第1个字符开始,搜索第2次出现子串的位置 

SQL> select instr('oracleor','or', 1, 2) position from dual; 

POSITION 

----------        

     7 


--3.从倒数第1个字符开始,搜索第1次出现子串的位置 

SQL> select instr('oracleor','or', -1, 1) position from dual; 

POSITION 

----------     

    7

--4.从倒数第1个字符开始,搜索第2次出现子串的位置

SQL> select instr('oracleor','or', -1, 2) position from dual;

POSITION

----------    

     1

经典例子:

select * from tuser a where instr(','||(select substr(owner,8,length(owner)) from os_currentstep where entry_id=4252300)||',',','||a.id||',')>0;

(select substr(owner,8,length(owner)) from os_currentstep where entry_id=4252300) 结果为字符串:3993,451,1889,1482

如果直接这么写:select * from tuser a where a.id in (select substr(owner,8,length(owner)) from os_currentstep where entry_id=4252300)会报无效数字

原文地址:https://www.cnblogs.com/zkx4213/p/4203799.html