我的oracle数据库中有一个表,其中包含varchar2列' Detail_Number'记录如下所示 -
Detail_Number
--------------
P1464187
1-17J3P
VAR1460621
P15000566
VRH-P146310034
RH-73082_SS1
19502744
现在,我想使用一个case语句,它只返回特殊字符' _'之前的Detail_Number列的一部分。如果存在特殊字符。否则,只需返回Detail_Number。
我写的案例陈述是 -
CASE
WHEN INSTR(A.AGREEMENT_NUMBER, '_') IS NOT NULL THEN SUBSTR(A.AGREEMENT_NUMBER, 0, INSTR(A.AGREEMENT_NUMBER, '_')-1)
WHEN INSTR(A.AGREEMENT_NUMBER, '_') = 0 THEN A.AGREEMENT_NUMBER
--ELSE A.AGREEMENT_NUMBER
END AS Output
查询结果如下 -
Detail_Number Output
------------- --------
P1464187
1-17J3P
VAR1460621
P15000566
VRH-P146310034
RH-73082_SS1 RH-73082
19502744
在这里,我得到的是' _'被跳过了。但是,如果' _'不存在,它返回null。请你帮我一下。
感谢。
答案 0 :(得分:3)
你的意思是?
SQL> with
2 data as (select 'P1464187' t# from dual union all
3 select '1-17J3P' t# from dual union all
4 select 'VAR1460621' t# from dual union all
5 select 'P15000566' t# from dual union all
6 select 'VRH-P146310034' t# from dual union all
7 select 'RH-73082_SS1' t# from dual union all
8 select '19502744' t# from dual)
9 select
10 substr(t#, 1, instr(t# || '_', '_') - 1)
11 from
12 data;
SUBSTR(T#,1,INSTR(T#||'_','_')-1)
--------------------------------------------------------
P1464187
1-17J3P
VAR1460621
P15000566
VRH-P146310034
RH-73082
19502744
7 rows selected.
答案 1 :(得分:1)
使用REGEXP_REPLACE的选项(在大型建筑物中可能不像Sanders INSTR选项那样有效;)(但仍然有效)
with w_data as (
select rtrim('P1464187 ') c from dual union all
select rtrim('1-17J3P ') c from dual union all
select rtrim('VAR1460621 ') c from dual union all
select rtrim('P15000566 ') c from dual union all
select rtrim('VRH-P146310034') c from dual union all
select rtrim('RH-73082_SS1 ') c from dual union all
select rtrim('19502744 ') c from dual
)
Select c, regexp_replace(c, '^(.*)[_$]','\1') d
from w_data;
C D
-------------- ----------------------------------------
P1464187 P1464187
1-17J3P 1-17J3P
VAR1460621 VAR1460621
P15000566 P15000566
VRH-P146310034 VRH-P146310034
RH-73082_SS1 RH-73082SS1
19502744 19502744
7 rows selected.