Oracle中的instr()函數 詳解及應用

轉自:https://www.cnblogs.com/dshore123/p/7813230.html

1)instr()函數的格式  (俗稱:字符查找函數)

INSTR( string, substring [, start_position [, th_appearance ] ] )

參數:
string - 要搜索的字符串。字符串可以是CHAR,VARCHAR2,NCHAR,NVARCHAR2,CLOB或NCLOB等類型。
substring - 要在字符串(string)中搜索的子字符串。 子字符串可以是CHAR,VARCHAR2,NCHAR,NVARCHAR2,CLOB或NCLOB等類型。
start_position - 可選的。 在搜索將開始的字符串中的位置。 如果省略,則默認爲1。字符串中的第一個位置爲1.如果start_position爲負數,INSTR函數會從字符串末尾開始計算start_position字符數,然後搜索字符串的開頭。
nth_appearance - 可選的。 子串的第n個出現。 如果省略,則默認爲1。
返回值

返回一個數字值。 字符串中的第一個位置是1。如果在字符串中找不到substring,那麼INSTR函數將返回0。

 

格式一:instr( string1, string2 )    /   instr(源字符串, 目標字符串)

格式二:instr( string1, string2 [, start_position [, nth_appearance ] ] )   /   instr(源字符串, 目標字符串, 起始位置, 匹配序號)

解析:string2 的值要在string1中查找,是從start_position給出的數值(即:位置)開始在string1檢索,檢索第nth_appearance(幾)次出現string2。

  注:在Oracle/PLSQL中,instr函數返回要截取的字符串在源字符串中的位置。只檢索一次,也就是說從字符的開始到字符的結尾就結束。

 

2)實例

格式一

1 select instr('helloworld','l') from dual; --返回結果:3    默認第一次出現“l”的位置
2 select instr('helloworld','lo') from dual; --返回結果:4    即:在“lo”中,“l”開始出現的位置
3 select instr('helloworld','wo') from dual; --返回結果:6    即“w”開始出現的位置

格式二

1 select instr('helloworld','l',2,2) from dual;  --返回結果:4    也就是說:在"helloworld"的第2(e)號位置開始,查找第二次出現的“l”的位置
2 select instr('helloworld','l',3,2) from dual;  --返回結果:4    也就是說:在"helloworld"的第3(l)號位置開始,查找第二次出現的“l”的位置
3 select instr('helloworld','l',4,2) from dual;  --返回結果:9    也就是說:在"helloworld"的第4(l)號位置開始,查找第二次出現的“l”的位置
4 select instr('helloworld','l',-1,1) from dual;  --返回結果:9    也就是說:在"helloworld"的倒數第1(d)號位置開始,往回查找第一次出現的“l”的位置
5 select instr('helloworld','l',-2,2) from dual;  --返回結果:4    也就是說:在"helloworld"的倒數第1(d)號位置開始,往回查找第二次出現的“l”的位置
6 select instr('helloworld','l',2,3) from dual;  --返回結果:9    也就是說:在"helloworld"的第2(e)號位置開始,查找第三次出現的“l”的位置
7 select instr('helloworld','l',-2,3) from dual; --返回結果:3    也就是說:在"helloworld"的倒數第2(l)號位置開始,往回查找第三次出現的“l”的位置

 

注:MySQL中的模糊查詢 like 和 Oracle中的 instr() 函數有同樣的查詢效果; 如下所示:

MySQL: select * from tableName where name like '%helloworld%';
Oracle:select * from tableName where instr(name,'helloworld')>0;  --這兩條語句的效果是一樣的

 

3)實例截圖

1、

2、

3、

4、

5、

6、

7、

8、

9、

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章