简体   繁体   中英

Get values after and before specific character in SQL/PL SQL?

I have a string value as a parameter and I need to parse it. My value is :

param := ('1234@5432@4567@8763');

I have to get 1234 , 5432 , 4567 and 8763 values partially. I will set these values different parameters.

How can I solve it with SQL?

Thanks,

Assuming that you are in PL/SQL and you need to split a value of a parameter or a variable into four variables, this could be a way:

declare
    param    varchar2(100);
    param1   varchar2(100);
    param2   varchar2(100);
    param3   varchar2(100);
    param4   varchar2(100);
begin    
    param := '1234@5432@4567@8763';
    --
    param1 := substr(param, 1, instr(param, '@', 1, 1)-1);
    param2 := substr(param, instr(param, '@', 1, 1) +1 , instr(param, '@', 1, 2) - instr(param, '@', 1, 1)-1);
    param3 := substr(param, instr(param, '@', 1, 2) +1 , instr(param, '@', 1, 3) - instr(param, '@', 1, 2)-1);
    param4 := substr(param, instr(param, '@', 1, 3) +1  );
    --
    dbms_output.put_line('Param1: ' || param1);
    dbms_output.put_line('Param2: ' || param2);
    dbms_output.put_line('Param3: ' || param3);
    dbms_output.put_line('Param4: ' || param4);
end;    

With regular expressions, you can get the same result by searching the 1st, 2nd, ... occurrence of a string that is followed by a @ or by the end of the line ( '$' ); a better explanation of this approach is described in the link gave by Gary_W in his comment

...
param1 := regexp_substr(param, '(.*?)(@|$)', 1, 1, '', 1 );
param2 := regexp_substr(param, '(.*?)(@|$)', 1, 2, '', 1 );
param3 := regexp_substr(param, '(.*?)(@|$)', 1, 3, '', 1 );
param4 := regexp_substr(param, '(.*?)(@|$)', 1, 4, '', 1 );
...
select level, regexp_substr(a,'\d+',1,level)
from(select '1234@5432@4567@8763' a from dual)
connect by level <= regexp_count(a,'@') + 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM