我有一个如下表:
Last_name First_name
aaaa bbb -
aaa bbbb -
aaa gggg j
如何使用 substr 函数删除 - 中的 -first_name
如果不是 - 则保留字母?
谢谢
您可以使用rtrim()函数,指定要从字符串右侧删除的第二个参数字符:
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
如果你真的想使用 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