加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-13 16:58:07 所属栏目:百科 来源:网络整理
导读:部分内容参考了http://blog.csdn.net/victor_ww/article/details/44240063 但是由于上面的文章,在我那里不能完全执行,所以我这边整理了一份可以运行成功的例子。 有的时候,我们会使用到函数,并且想使用函数中查询一些数据,并且当是多条结果集的时候,就

部分内容参考了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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读