最近發現一段對字元串進行trim 的SQL,發現LTRIM、RTRIM和TRIM 在ORACLE中的用法還是很強大的。
作用
三個函數功能都是對字元串進行前後去除一部分操作。但是又有點差別。先看下對比。
SELECT TRIM(BOTH '-' FROM '----FFF----ggggg----' ) AS trim_both,
TRIM( '-' FROM '----FFF----ggggg----' ) AS trim_default,
TRIM(LEADING '-' FROM '----FFF----ggggg----' ) AS trim_left,
TRIM( TRAILING '-' FROM '-----FFF------ggggg------' ) AS trim_right,
TRIM(' ----FFF----ggggg---- ' ) AS trim_default_Empty,
LTRIM('----FFF----ggggg----', '-F') AS ltrim_mult_char,
RTRIM('----FFF----ggggg----', '-g') AS rtrim_mult_char
FROM dual WHERE ROWNUM = 1;
上面利用三個函數對字元串進行處理,對比下不難發現一些差別。下面一個個進行了解。
TRIM
先看下文檔介紹
trim( [ leading | trailing | both [ trim_character ] FROM ] string1 )
leading - remove trim_string from the front of string1.
trailing - remove trim_string from the end of string1.
both - remove trim_string from the front and end of string1.
If none of these are chosen (ie: leading, trailing, both), the trim function will remove trim_string from both the front and end of string1.
trim_character is the character that will be removed from string1. If this parameter is omitted, the trim function will remove all leading and trailing spaces from string1.
string1 is the string to trim.
這是 Oracle 的官方文檔裡面的函數介紹。
說白了,各個參數有以下作用:
leading : 去頭
trailing : 去尾
both : 去頭尾
trim_character : 不空去該字元,預設去除空格
string1 : 待處理字元串
根據文法,不難發現會有以下的輸出
BOTH
另外,如果該參數不指定時,預設也是 BOTH
SELECT TRIM(BOTH '-' FROM '----FFF----ggggg----' ) AS trim_both ,
TRIM( '-' FROM '----FFF----ggggg----' ) AS trim_default
FROM dual WHERE ROWNUM = 1;
LEADING
SELECT TRIM(LEADING '-' FROM '----FFF----ggggg----' ) AS trim_left
FROM dual WHERE ROWNUM = 1;
TRAILING
SELECT TRIM( TRAILING '-' FROM '-----FFF------ggggg------' ) AS trim_right
FROM dual WHERE ROWNUM = 1;
而當我們不輸入要删除的字元(注意,這裡我說的是字元)時,預設删除頭尾的空格。
SELECT TRIM(' ----FFF----ggggg---- ' ) AS trim_default_Empty
FROM dual WHERE ROWNUM = 1;
上面沒輸入要trim 的單個字元參數時,函數隻是把前後空格 trim 掉。為啥要單個字元?看個例子,
SELECT TRIM( TRAILING '--' FROM '-----FFF------ggggg------' ) AS trim_right
FROM dual WHERE ROWNUM = 1;
這裡報錯,顯然其參數必須是單個字元。錯誤資訊如下:
ORA-30001: trim set should have only one character
30001. 00000 - "trim set should have only one character"
*Cause: Trim set contains more or less than 1 character. This is not
allowed in TRIM function.
LTRIM
從名字就知道,對字元串左側進行 trim。
SELECT LTRIM('----FFF----ggggg----', '-F') AS ltrim_mult_char
FROM dual WHERE ROWNUM = 1;
這裡 LTRIM 将 '----FFF----ggggg----' 的頭部的 '-' 和 'F' 都去掉了,最後變成了 'ggggg----'。顯然 LTRIM 對發現的任意字元 '-' 或字元 'F' 均做删除操作。即或的關系。
RTRIM
同樣的,RTRIM 功能類似,隻是從尾部開始删除而已。
SELECT RTRIM('----FFF----ggggg----', '-g') AS rtrim_mult_char
FROM dual WHERE ROWNUM = 1;
從結果看,同樣的對 '-' 和 'F' 進行删除。也是或的關系。