当前位置: 移动技术网 > IT编程>数据库>Oracle > Oracle中instr函数使用方法

Oracle中instr函数使用方法

2017年12月12日  | 移动技术网IT编程  | 我要评论

七彩读写,罗马法原论,一肩之隔歌词

instr (源字符串, 目标字符串, 起始位置, 匹配序号)

  在oracle/plsql中,instr函数返回要截取的字符串在源字符串中的位置。只检索一次,就是说从字符的开始到字符的结尾就结束。

  语法如下:
  instr( string1, string2 [, start_position [, nth_appearance ] ] )
  参数分析:
  string1
  源字符串,要在此字符串中查找。
  string2
  要在string1中查找的字符串.
  start_position

  代表string1 的哪个位置开始查找。此参数可选,如果省略默认为1. 字符串索引从1开始。如果此参数为正,从左到右开始检索,如果此参数为负,从右到左检索,返回要查找的字符串在源字符串中的开始索引。

  nth_appearance

  代表要查找第几次出现的string2. 此参数可选,如果省略,默认为 1.如果为负数系统会报错。

  注意:

  如果string2在string1中没有找到,instr函数返回0.

  示例:

  select instr('syranmo','s') from dual; -- 返回 1
  select instr('syranmo','ra') from dual; -- 返回 3
  select instr('syran mo','a',1,2) from dual; -- 返回 0

  (根据条件,由于a只出现一次,第四个参数2,就是说第2次出现a的位置,显然第2次是没有再出现了,所以结果返回0。注意空格也算一个字符!)

  select instr('syranmo','an',-1,1) from dual; -- 返回 4

  (就算是由右到左数,索引的位置还是要看‘an'的左边第一个字母的位置,所以这里返回4)

  select instr('abc','d') from dual; -- 返回 0

  注:也可利用此函数来检查string1中是否包含string2,如果返回0表示不包含,否则表示包含。
  对于上面说到的,我们可以这样运用instr函数。请看下面示例:

  如果我有一份资料,上面都是一些员工的工号(字段:code),可是我现在要查询出他们的所有员工情况,例如名字,部门,职业等等,这里举例是两个员工,工号分别是'a10001′,'a10002′,其中假设staff是员工表,那正常的做法就如下:

  select code , name , dept, occupation from staff where code in ('a10001','a10002');

  或者:

  select code , name , dept, occupation from staff where code = 'a10001' or code = 'a10002';

  有时候员工比较多,我们对于那个'觉得比较麻烦,于是就想,可以一次性导出来么?这时候你就可以用instr函数,如下:

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

  查询出来结果一样,这样前后只用到两次单引号,相对方便点。

  还有一个用法,如下:

  select code, name, dept, occupation from staff where instr(code, '001') > 0;
  等同于
  select code, name, dept, occupation from staff where code like '%001%' ;

oracle的instr函数使用实例

instr方法的格式为
instr(src, substr,startindex, count)
src: 源字符串
substr : 要查找的子串
startindex : 从第几个字符开始。负数表示从右往左查找。
count: 要找到第几个匹配的序号
返回值: 子串在字符串中的位置,第1个为1;不存在为0. (特别注意:如果src为空字符串,返回值为null)。

用法举例:

最简单的一种,查找l字符,首个l位于第3个位置。
sql> select instr('hello,java world', 'l') from dual;

instr('hello,javaworld','l')
----------------------------
3

查找l字符,从第4个位置开始。
sql> select instr('hello,java world', 'l', 4) from dual;
instr('hello,javaworld','l',4)
------------------------------
4

查找l字符,从第1个位置开始的第3个
sql> select instr('hello,java world', 'l', 1, 3) from dual;
instr('hello,javaworld','l',1,
------------------------------
15

查找l字符,从右边第1个位置开始,从右往左查找第3个(也即是从左到右的第1个)
sql> select instr('hello,java world', 'l', -1, 3) from dual;
instr('hello,javaworld','l',-1
------------------------------
3
找不到返回0
sql> select instr('hello,java world', 'mm') from dual;
instr('hello,javaworld','mm')
-----------------------------
0

源字符为空字符串''的情况
复制代码 代码如下:

-- created on 2010-12-22 by chen
declare
-- local variables here
i varchar2(2);
begin
-- test statements here
i := instr('',',');
if i is null then
dbms_output.put_line(' i is empty');
end if;
end;

结果输出:

i is empty

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网