如何使用列的下一个值增加变量

时间:2017-12-12 10:27:30

标签: oracle

我有一个具有此代码的函数

for i in cursor
loop
variavel1=i.id
  while i.id=variavel1
   loop
    ---- do someting
    --- incriment variavel1 with next i.id
   end loop;

end loop;

我需要使用i中的下一个id(具有光标日期的对象)来增加variavel1。

2 个答案:

答案 0 :(得分:1)

如果连接是你需要的一切,你可以使用纯sql:

select id, listagg(text) within group (order by text) as list
    from (
        select 1 id, 'abc' text from dual union all
        select 1 id, 'def' text from dual union all
        select 1 id, 'ghi' text from dual union all
        select 3 id, 'jkl' text from dual union all
        select 7 id, 'mno' text from dual union all
        select 7 id, 'pqr' text from dual)
    group by id;

其他可能性,就像在这个PLSQL块中一样:

declare
    cursor crsr is 
        select 1 id, 'abc' text from dual union all
        select 1 id, 'def' text from dual union all
        select 1 id, 'ghi' text from dual union all
        select 3 id, 'jkl' text from dual union all
        select 7 id, 'mno' text from dual union all
        select 7 id, 'pqr' text from dual;

    variavel1 number;
    variavel2 varchar2(1000);

begin
    for i in crsr loop
        if variavel1 is null or variavel1 <> i.id then
            if variavel1 is not null then
                dbms_output.put_line(variavel1||' - '||variavel2);
            end if;
            variavel1 := i.id;
            variavel2 := i.text;
        else
            variavel2 := variavel2 || i.text;
        end if;
    end loop;
    dbms_output.put_line(variavel1||' - '||variavel2);

end;

您还可以将简单类型定义为对象表(id,text),并在循环中将项添加到此类型的变量中。

declare
    type tob is record (id number, text varchar2(1000));
    type ttb is table of tob;

    variavel2 ttb := ttb();

    cursor crsr is 
        select 1 id, 'abc' text from dual union all
        select 1 id, 'def' text from dual union all
        select 1 id, 'ghi' text from dual union all
        select 3 id, 'jkl' text from dual union all
        select 7 id, 'mno' text from dual union all
        select 7 id, 'pqr' text from dual;

begin
    for i in crsr loop
        if variavel2.count = 0 or variavel2(variavel2.count).id <> i.id then
            variavel2.extend();
            variavel2(variavel2.count).id := i.id;
        end if;
        variavel2(variavel2.count).text := variavel2(variavel2.count).text||i.text;
    end loop;

    -- now we have array of values
    for x in 1..variavel2.count loop
        dbms_output.put_line(variavel2(x).id||' - '||variavel2(x).text);
    end loop;

end;

我认为id不可为空,如果你需要进行细微的修改。所有解决方案的输出是:

    ID LIST
------ --------------
     1 abcdefghi
     3 jkl
     7 mnopqr

答案 1 :(得分:0)

打开光标;    FETCH游标INTO cursor_result;    WHILE找到光标%    环     variavel1 = cursor_result.id     WHILE(variavel1 = cursor_result.id和找到的游标%)       环         --- dO SOMITHING ----         FETCH游标INTO cursor_result; ----通过下一个价值       结束循环;    结束循环;