Oracle中的instr函数

     最近修改某个条件,由原来输入一个数据修改为可以输入多个,如图所示:

   在实现时用到了regexp_substr函数进行分割连接起来的数据,查询时还用到了instr函数进行判断,但出现了问题,当子库存输入‘23107G’时会将23107和23107G的两个子库存都查询出来,查找后发现是instr函数的问题,其中where子句中用到了(p_sub_code IS NULL OR instr(p_sub_code,moq.subinventory_code)>0)。

   对于Instr函数,一般的用法是返回源字符串中目标子串的位置,语法:

   instr(string, substring, startposition, occurrence),有四个参数

  1.String:源字符串

  2.Substring:目标字符串

  3.Startposition:查找的起始位置,默认为1,注:字符串是从1开始。

  4.occurrence:出现的次数

    例1、SQL> select instr('oracle','or') position from dual;--从第一个位置开始搜索or出现的位置

     POSITION

     ----------

        1

    例2、SQL> select instr('oracleor','or', 3) position from dual; --从第三个位置开始搜索or出现的位置

    POSITION

    ----------

        7

   例3、SQL> select instr('oracleor','or', 1, 2) position from dual;--从第一个位置开始搜索or第二次出现的位置

    POSITION

    ----------

        7

例4、SQL> select instr('oracleor','or', -1, 1) position from dual;--从倒数第一个位置开始搜索or第一次出现的位置

   POSITION

   ----------

        7

 例5、SQL> select instr('oracleor','or', -1, 2) position from dual;--从倒数第一个位置开始搜索or第2次出现的位置

   POSITION

   ----------

        1

oracle用instr代替like,可以节省效率,会出现那个错误的原因就是因为查询实际是模糊查询。

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

SQL> set timing on
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
SQL> select count(*) from t where instr(title,’oracle’)=0;

COUNT(*)
———-
994530

Elapsed: 00:00:11.31
SQL> select count(*) from t where title not like ‘%oracle%’;

COUNT(*)
———-
994530

注:

instr(title,'oracle’)>0 相当于like

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

注:里面的例子摘自于https://blog.csdn.net/hzhsan/article/details/9186637

   

猜你喜欢

转载自www.cnblogs.com/chenchengfei/p/9237340.html