postgresql数据库的游标使用例子说明

部分内容参考了http://blog.csdn.net/victor_ww/article/details/44240063

但是由于上面的文章,在我那里不能完全执行,所以我这边整理了一份可以运行成功的例子。

有的时候,我们会使用到函数,并且想使用函数中查询一些数据,并且当是多条结果集的时候,就需要使用游标了。

使用游标分为两种方式,这个也是自己参考上面的文章,然后自己瞎摸索出来的,多试几次。

1、没有where 条件的

CREATE OR REPLACE FUNCTION cursor_demo()  
  RETURNS refcursor AS  
$BODY$  
declare  
    unbound_refcursor refcursor;  
    v_id int;  
    v_step_desc varchar(1000);  
begin  
    open unbound_refcursor for execute 'select id,step_desc from t_runtime_step_log';  
    loop  
        fetch unbound_refcursor into v_id,v_step_desc;  
          
        if found then  
            raise notice '%-%',v_id,v_step_desc;  
        else  
            exit;  
        end if;  
    end loop;  
    close unbound_refcursor;  
    raise notice 'the end of msg...';  
    return unbound_refcursor;  
exception when others then  
    raise exception 'error--(%)',sqlerrm;  
end;  
$BODY$  
  LANGUAGE plpgsql;  

上面只是声明了一个函数,外部调用需要采用下面的方式。

begin;  
select cursor_demo();  
commit;

调用时,如果不使用begin和commit的话,会提示错误。

当然也可以再封装一个函数, 该函数中写上上面的代码。

unnamed portal

2、附带where条件的

CREATE OR REPLACE FUNCTION cursor_demo3(p_condition integer)  
  RETURNS refcursor AS  
$BODY$  
declare  
    bound_param_cursor cursor(id_condition integer) for select * from t_runtime_step_log where id > id_condition;  
begin  
    open bound_param_cursor(p_condition);  
    return bound_param_cursor;  
end;  
$BODY$  
  LANGUAGE plpgsql;  

上面只是声明了一个函数,外部调用需要采用下面的方式。

begin;  
select cursor_demo();  
commit;

调用时,如果不使用begin和commit的话,会提示错误。

当然也可以再封装一个函数, 该函数中写上上面的代码。

unnamed portal


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值