0

我创建了下面的函数来处理逗号分隔的字符串并创建一个字符串。例如,如果字符串为“1,2,34,5,67”,则此函数的输出应为“0102340567”。

Db2 版本是 9.1

create function fn_get_betnum (chartext varchar(100))
LANGUAGE SQL    
RETURNS VARCHAR(100)
DETERMINISTIC NO EXTERNAL ACTION
BEGIN atomic

    declare pos int;
    declare sep char(1);
    declare input varchar(100);
    declare s varchar(72);

    set sep=',';
    set input=trim(chartext);
    set pos = locate(sep,input);

    while pos > 0
    do
        set s=concat(s,right(concat('0',trim(substr(input,1,pos-1))),2));
        set input=substr(input,pos+1,length(input)-pos);
        set pos = locate(sep,input);
    end while;
    if length(input) > 0 then
        set s=concat(s,right(concat('0',trim(input)),2));
    end if;
    return s;
end

该函数已成功创建,但是当我尝试以下查询时,我得到一个空结果集:

询问:

select fn_get_betnum('1,2') from my_table 仅获取前 1 行

结果集:

1
----------------------------------------------------------------------------------------------------
-

  1 record(s) selected.

我究竟做错了什么?

4

2 回答 2

0

这是一个你可以尝试的。我试着把它简化一点。免责声明:这在 DB2 v6r1 (iSeries/AS400) 上运行良好。LUW 或 z 系列上的 DB2 可能需要对以下功能进行一些修改:

create function fn_get_betnum (chartext varchar(100))
returns varchar(100)
language sql
deterministic no external action
begin

    declare pos int;
    declare sep char(1) default ',';
    declare temp varchar(10);
    declare s varchar(100) default '';

    -- get position of comma
    set pos = locate(sep, chartext);

    -- loop till no comma is found
    while pos > 0 do

        -- get the left side before comma
        set temp = left(chartext, pos-1);
        if length(trim(temp)) = 1 then 
            set temp = '0' || temp;
        end if;     
        set s = s || temp;

        -- throw away the first command and everything before that
        set chartext = substr(chartext, pos+1, 100);

        -- find the next comma
        set pos = locate(sep, chartext);

    end while;

    -- take the remainder of the string after no comma
    -- is found and stick it behind the text to return
    if length(trim(chartext)) = 1 then
        set chartext = '0' || chartext;
    end if;
    set s = s || chartext;

    return s;
end;

结果:

select fn_get_betnum('1,2,34,5,67') from sysibm/sysdummy1;

结果是: 0102340567

于 2013-09-08T07:18:04.370 回答
0

由于您没有初始化变量s,因此这一行:

    set s=concat(s,right(concat('0',trim(substr(input,1,pos-1))),2));

将始终为空。正如@zfus 所示,初始化s为一个空字符串:

    declare s varchar(100) default '';
于 2013-09-08T14:20:08.033 回答