Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Create stored procedure to return substrings from input string value. Substring delimiter shall be i

nedjoMar 4 2019 — edited Mar 5 2019

Task description

Stored procedure shall have input parameters:

  • STRING
  • DELIMITER //any symbol
  • STRING_NUMBER //number of substring to be returned

Input example: STRING => ‘one,two,three’,

                            DELIMITER => ‘e’,

                            STRING_NUMBER => null

Output shall be: ‘on’

                              ‘,two,thr’

                              ‘’

                              ‘’

If STRING_NUMBER => 2, output shall be: ‘,two,thr’

It is a job interview question.
I have done the following:
CREATE OR REPLACE PROCEDURE substring
(STRNG IN VARCHAR2,DELIMITER IN VARCHAR2, STRING_NUMBER IN NUMBER)
IS
replace_string VARCHAR2
(100);
instring NUMBER
;
comma_counter NUMBER
;
substring VARCHAR2
(100);
BEGIN
replace_string
:= REPLACE(STRNG,DELIMITER);
comma_counter
:=REGEXP_COUNT(STRNG,',');
instring
:=INSTR(STRNG,',',1,comma_counter-STRING_NUMBER+1);
substring
:=SUBSTR(replace_string,instring);

DBMS_OUTPUT
.PUT_LINE(replace_string);
DBMS_OUTPUT
.PUT_LINE(','||substring);

END;

set serveroutput on
BEGIN
substring
('one,two,three,four','e',2);
END;
Now, what is my concern:
1. substring('one,two,three','e',null); doesn't give the same output as in task description.
2. Doesn't work: substring('one,two,three,four',',',2); It is debatable because the comma character is kinda special in this case. You should not call the procedure on comma character. Rather, only use letters. As I say, it is debatable. If someone has a better solution, please provide it. What do you think?
Comments
Post Details
Added on Mar 4 2019
8 comments
1,258 views