您的位置:首页 > 数据库

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

2017-02-20 15:00 253 查看
部分内容参考了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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: