2011-11-08 56 views

回答

10

這裏的樣本如何分割字符串,並WRI將子字符串轉換爲表格:

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 
+0

很酷。非常感謝你。 –

+0

需要注意的是:它不會像'',1,2''那樣返回'AINPUT'的任何結果,但它會像'1,2'一樣返回'AINPUT'的三個子串。 – Wodzu

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 ;^
+0

偉大的工作@MartjinPieters :) – hims056

+0

謝謝@MartijnPieters。 – Wodzu

3

它看起來只是有一點好,我的火鳥服務器的Varchar大小申報32000事業「實施超限」的例外,所以要小心。我建議使用BLOB SUB_TYPE文本而不是:)

2

類似的解決方案,我用,在以前發表的由吉日Cincura http://blog.cincura.net/232347-tokenize-string-in-sql-firebird-syntax/

recreate procedure Tokenize(input varchar(1024), token char(1)) 
returns (result varchar(255)) 
as 
declare newpos int; 
declare oldpos int; 
begin 
    oldpos = 1; 
    newpos = 1; 
    while (1 = 1) do 
    begin 
    newpos = position(token, input, oldpos); 
    if (newpos > 0) then 
    begin 
     result = substring(input from oldpos for newpos - oldpos); 
     suspend; 
     oldpos = newpos + 1; 
    end 
    else if (oldpos - 1 < char_length(input)) then 
    begin 
     result = substring(input from oldpos); 
     suspend; 
     break; 
    end 
    else 
    begin 
     break; 
    end 
    end 
end