1. 程式人生 > >Oracle instr與substr的區別及用法

Oracle instr與substr的區別及用法

一、instr函式是一個字串處理函式,它在Oracle/PLSQL中是返回子字串在源字串中的位置。
/*
 * 返回子字串在源字串中的位置(字串位置從1開始,而不是從0開始)
 * @param string 源字串
 * @param substring 子字串
 * @param position 檢索位置,可省略(預設為1),引數為正時,從左向右檢索,引數為負時,從右向左檢索
 * @param occurrence 檢索子字串出現的次數,可省略(預設為1),值只能為正整數,否則會報錯
 * @return 返回子字串在源字串中出現的位置(沒找到返回0)
 */
instr(string, substring, position, occurrence);
SELECT INSTR('hello world', 'l') FROM DUAL;           --結果:3
SELECT INSTR('hello world', 'l', 5) FROM DUAL;        --結果:10
SELECT INSTR('hello world', 'l', -1) FROM DUAL;       --結果:10
SELECT INSTR('hello world', 'l', 2, 2) FROM DUAL;     --結果:4
SELECT INSTR('hello world', 'l', -3, 3) FROM DUAL;    --結果:0

注:這一塊的第2、3不太透徹
二、substr函式是一個字串擷取函式,它返回的是擷取的字串。
--函式定義如下:
/*
 * 擷取字串(字串位置從1開始,而不是從0開始)
 * @param string 源字串
 * @param position 檢索位置,引數為正時,從左向右檢索,引數為負時,從右向左檢索
 * @param substring_length 要擷取的長度,可省略(預設從position位開始擷取全部),值小於1時返回空字串
 * @return 返回擷取的字串
 */
substr(string, position, substring_length);
SELECT SUBSTR('hello world', 2) FROM DUAL;        --結果:ello world
SELECT SUBSTR('hello world', -2) FROM DUAL;       --結果:ld
SELECT SUBSTR('hello world', 4, 4) FROM DUAL;     --結果:lo w
SELECT SUBSTR('hello world', -4, 3) FROM DUAL;    --結果:orl
SELECT SUBSTR('hello world', 4, -1) FROM DUAL;    --結果:空字串

--可以將SUBSTR和INSTR結合使用來實現擷取字串中特定字元前後的字串
--<1> 擷取“hello,world”字串中“,”分隔符之前的字串
select INSTR('hello,world', ',')-1 from dual;
SELECT SUBSTR('hello,world', 1, INSTR('hello,world', ',')-1) FROM DUAL;
--結果:hello
--<2> 擷取“hello,world”字串中“,”分隔符之後的字串  
select INSTR('hello,world', ',')+1 from dual;                           
SELECT SUBSTR('hello,world', INSTR('hello,world', ',')+1) FROM DUAL;
--結果:world
--<3> 擷取“hello,world,HH”字串中第1次出現的“,”字元和第2次出現的“,”字元之間的字串
select INSTR('hello,world,HH', ',',1)+1,INSTR('hello,world,HH', ',', 2)-1 from dual;
SELECT SUBSTR('hello,world,HH', INSTR('hello,world,HH', ',',1)+1, INSTR('hello,world,HH', ',', 2)-1) FROM DUAL;
--結果:world
三、再給大家幾個比較實用的例子
--1、根據檔案路徑擷取檔名;如 E:/1234/5678/1357.txt
--思路:獲取檔名,根據/進行劃分,從後往前,語法帶入:instr(路徑,'/',-1)
select INSTR('E:/1234/5678/1357.txt','/',-1)+1 from dual;
select SUBSTR('E:/1234/5678/1357.txt',INSTR('E:/1234/5678/1357.txt','/',-1)+1) from dual;
--2、根據檔名獲取檔案字尾;如 測試檔案.pdf
select SUBSTR('測試檔案.pdf',instr('測試檔案.pdf','.',1)+1) from dual;
--3、根據去掉檔名字尾;如 測試檔案.xls
select SUBSTR('測試檔案.pdf',1,instr('測試檔案.pdf','.',1)-1) from dual;
--4、根據檔案路徑獲取檔名稱,不帶字尾
select SUBSTR(SUBSTR('E:/1234/5678/1357.txt',INSTR('E:/1234/5678/1357.txt','/',-1)+1),1,
INSTR(SUBSTR('E:/1234/5678/1357.txt',INSTR('E:/1234/5678/1357.txt','/',-1)+1),'.',-1)-1)from dual;