db2功能不起作用

时间:2013-09-08 03:13:13

标签: db2

我创建了下面的函数来处理逗号分隔的字符串并创建一个单独的字符串。例如,如果字符串为“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

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

查询:

从my_table中选择fn_get_betnum('1,2')仅获取前1行

结果集:

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

  1 record(s) selected.

我做错了什么?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

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

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

    declare s varchar(100) default '';