How to split comma separated string inside stored procedure?
Use POSITION http://www.firebirdsql.org/refdocs/langrefupd21-intfunc-position.html
and
SUSTRING http://www.firebirdsql.org/refdocs/langrefupd21-intfunc-substring.html
functions in WHILE DO statement
I am posting modified Michael's version, maybe it will be useful for someone.
The changes are:
- SPLIT_STRING is a selectable procedure.
- Custom delimiter is possible.
- It parses also cases when delimiter is a first character in the P_STRING.
set term ^ ;
create procedure split_string (
p_string varchar(32000),
p_splitter char(1) )
returns (
part varchar(32000)
)
as
declare variable lastpos integer;
declare variable nextpos integer;
begin
p_string = :p_string || :p_splitter;
lastpos = 1;
nextpos = position(:p_splitter, :p_string, lastpos);
if (lastpos = nextpos) then
begin
part = substring(:p_string from :lastpos for :nextpos - :lastpos);
suspend;
lastpos = :nextpos + 1;
nextpos = position(:p_splitter, :p_string, lastpos);
end
while (:nextpos > 1) do
begin
part = substring(:p_string from :lastpos for :nextpos - :lastpos);
lastpos = :nextpos + 1;
nextpos = position(:p_splitter, :p_string, lastpos);
suspend;
end
end^
set term ; ^
Here a sample how to split the string and write the sub-strings into a table:
create procedure SPLIT_STRING (
AINPUT varchar(8192))
as
declare variable LASTPOS integer;
declare variable NEXTPOS integer;
declare variable TEMPSTR varchar(8192);
begin
AINPUT = :AINPUT || ',';
LASTPOS = 1;
NEXTPOS = position(',', :AINPUT, LASTPOS);
while (:NEXTPOS > 1) do
begin
TEMPSTR = substring(:AINPUT from :LASTPOS for :NEXTPOS - :LASTPOS);
insert into new_table("VALUE") values(:TEMPSTR);
LASTPOS = :NEXTPOS + 1;
NEXTPOS = position(',', :AINPUT, LASTPOS);
end
suspend;
end