2013-08-28 57 views
2

我有一個表像下面:的Oracle SQL函數SUBSTR

Last_name First_name 
aaaa  bbb - 
aaa  bbbb - 
aaa  gggg j 

如何使用SUBSTR函數刪除 - 在first_name並保持字母,如果它是不是 - ?

感謝

回答

3

可以使用rtrim()功能,指定爲您希望從一個字符串的右側刪除第二個參數的字符(S):

SQL> with t1(Last_name, First_name) as(
    2 select 'aaaa', 'bbb -' from dual union all 
    3 select 'aaa', 'bbbb -' from dual union all 
    4 select 'aaa', 'gggg j' from dual 
    5 ) 
    6 select last_name 
    7  , rtrim(first_name, ' -') as first_name 
    8 from t1 
    9 ; 

結果:

LAST_NAME FIRST_NAME 
--------- ---------- 
aaaa  bbb 
aaa  bbbb 
aaa  gggg j 

從Oracle 10g版本開始,您還可以使用regexp_replace()正則表達式函數:

select last_name 
    , regexp_replace(first_name, '\s*-\s*$') as first_name 
    from t1 

結果:

LAST_NAME FIRST_NAME 
--------- ---------- 
aaaa  bbb 
aaa  bbbb 
aaa  gggg j 
+0

作品Great.Thank非常感謝! – haoyun

1

如果你真的想用SUBSTR,試試這個:

with t1(Last_name, First_name) as(
    select 'aaaa', 'bbb -' from dual union all 
    select 'aaa', 'bbbb -' from dual union all 
    select 'aaa', 'gggg j' from dual 
) 
select last_name 
    , substr(first_name, 1, decode(instr(first_name,' -'), 0, length(first_name), instr(first_name,' -') -1)) as first_name 
    from t1 
; 

結果:

LAST_NAME FIRST_NAME 
--------- ---------- 
aaaa  bbb 
aaa  bbbb 
aaa  gggg j