如何在存储过程中拆分逗号分隔的字符串?

Yor*_*iev 8 sql string firebird firebird2.5

如何将逗号分隔的字符串拆分为存储过程中的字符串并将它们插入表字段?

使用Firebird 2.5

Mic*_*ael 10

这里有一个示例如何拆分字符串并将子字符串写入表中:

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
Run Code Online (Sandbox Code Playgroud)


Wod*_*dzu 10

我发布修改后的迈克尔版本,也许对某人有用.

变化是:

  1. SPLIT_STRING是一个可选择的过程.
  2. 自定义分隔符是可能的.
  3. 它还解析了分隔符是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 ; ^
Run Code Online (Sandbox Code Playgroud)