我有一张如下表:
Last_name First_name
aaaa bbb -
aaa bbbb -
aaa gggg j
如何使用substr函数删除first_name
中的 - 并保留字母,如果它不是 - ?
由于
答案 0 :(得分:3)
您可以使用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
答案 1 :(得分: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