Thursday, March 26, 2015

PostgreSQL: cursor example

create or replace function test_cursor() returns void as
$$
declare
    _my_cursor(p_co_id text) for
        select * from crm_db.ht_co_addon where co_id = p_co_id;
    _idx int := 0;
    _row record;
begin
    -- Example 1
    for _row in _my_cursor('000000000666') loop
        _row.co_addon_id := _idx;
        _idx := _idx + 1;
    end loop;

    -- Example 2
    open _my_cursor('000000000666')
    loop
        fetch _my_cursor into _row
        exit when not found
        raise notice 'co_addon_id=%', _row.co_addon_id
    end loop
    close _my_cursor
end;
$$ language plpgsql security definer;