PL / SQL-存储的子字符串过程

时间:2019-03-04 07:46:25

标签: stored-procedures plsql substring

我正在做一次面试PL / SQL问题,我真的很困。有人可以帮忙吗?

创建存储过程以从输入字符串值返回子字符串。子字符串定界符应为输入参数。

任务描述

存储过程应具有输入参数:

•   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’

编辑:

首先,我正在尝试使用TRIM函数修剪字符串,但这不起作用。为什么?

CREATE OR REPLACE PROCEDURE substring
(STRNG IN VARCHAR2,DELIMITER IN VARCHAR2)
IS
instring VARCHAR2(100);
BEGIN
instring:= TRIM(DELIMITER FROM STRNG);
DBMS_OUTPUT.PUT_LINE(instring);
END;

set serveroutput on
BEGIN
substring('marc','a');
END;

编辑2:

这是工作的一部分:

CREATE OR REPLACE PROCEDURE substring
(STRNG IN VARCHAR2,DELIMITER IN VARCHAR2)
IS
instring VARCHAR2(100);
BEGIN
instring:= REPLACE(STRNG,DELIMITER);
DBMS_OUTPUT.PUT_LINE(instring);
END;

set serveroutput on
BEGIN
substring('marc','a');
END;

1 个答案:

答案 0 :(得分:0)

这是我自己的解决方案:

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;