postgresql游标的简单使用

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/ziptop/article/details/45746743

百度游标的定义,显示游标是系统为用户开设的一个数据缓冲区,存放SQL语句的执行结果。感觉游标就跟指针差不多,对于select查询出的结果,能够根据自己的需要一行一行的取来用,从一个大的查询里面检索少数的几行数据。

【游标使用在事务中】

游标的使用分类
这里写图片描述
使用游标的步骤:
这里写图片描述

1、SQL命令级别使用游标
(1)declare定义游标:declare cur_name cursor for query 【语句中有一些可选的项,可以通过查官方文档得知】 这里的游标被认为在定义的时候就已经打开了;查询可用游标的sql语句为select * from pg_cursors;
(2)fetch 使用游标检索行,刚创建完的游标是放在第一行之前的
(3)move 在不检索数据的情况下,重新定位一个游标,类似于fetch,使用时的参数也相同
(4)close 关闭游标,释放资源
(5)例子:

postgres=# begin;--事务开始
BEGIN
postgres=# declare mycur cursor for select * from xu;--定义一个游标
DECLARE CURSOR
postgres=# fetch first from mycur;--抓取查询的第一行
 i | c 
---+---
 1 | a
(1 row)
postgres=# fetch next from mycur;/*抓取下一行,因为上条语句抓取的第一行,这条会
                             抓取第二行*/
 i | c 
---+---
 2 | b
(1 row)
postgres=# move last in mycur;--将游标重新定位到最后一行
MOVE 1
postgres=# fetch next from mycur;--所以最后一行的下一行没有数据显示了
 i | c 
---+---
(0 rows)
postgres=# close mycur;--关闭游标
CLOSE CURSOR
postgres=# commit;--事务结束
COMMIT

2、PL/pgSQL函数中使用游标
(1)定义游标
这里写图片描述
第二种定义方式中的arguments是用逗号分隔的name,datatype对的列表,使用时传入的值用来替换query中条件里的同名值,例如
declare cur_name(a int,b char) for select * from table_name where col_name1=a and col_name2=b;
(2)打开游标
只定义了游标还是不能使用该游标进行检索行的,所以需要先打开游标才行
这里写图片描述
(3)使用游标
使用游标是用的fetch,从游标中抓取行的命令
使用游标的操作不需要发生在和打开该游标开始操作的同一个函数里,可以从函数中返回一个refcursor值,然后让调用者操作该游标
(4)关闭游标
关闭游标使用close

(5)例子:
·这个例子来源于官方文档,用法是从函数中返回一个refcursor值,然后让调用者操作该游标

调用该函数时,输入的参数即为游标名

postgres=# create function test_cur(refcursor) returns refcursor as $$
postgres$# begin
postgres$#   open $1 for select * from xu;
postgres$#   return $1;
postgres$# end;
postgres$# $$language plpgsql;
CREATE FUNCTION

postgres=# begin;
BEGIN
postgres=# select test_cur('mycur');--调用函数,定义游标名
 test_cur 
----------
 mycur
(1 row)

postgres=# fetch all from mycur;--抓取数据
 i | c 
---+---
 1 | a
 2 | b
 3 | c
 4 | d
 1 | e
(5 rows)

postgres=# commit;
COMMIT

·通过游标结果循环的例子
原表xu的数据如下:

postgres=# select * from xu;
 i | c 
---+---
 1 | a
 2 | b
 3 | c
 4 | d
 1 | e
(5 rows)

创建函数:

create function use1_cur() returns setof xu as $$  --返回的是与表xu行对应的复合数据类型
declare
 mycur cursor for select * from xu;
 some xu;
 index int; --下标变量
begin
 open mycur;
 index:=1;
fetch mycur into some;
while found loop
  if index>=2 and index<=4 then
   return next some;
  end if;
  fetch mycur into some;
  index:=index+1;
  if index>4 then
   return;
  end if;
 end loop;
end;
$$ language plpgsql;
CREATE FUNCTION

调用函数的结果:

postgres=# select use1_cur();
 use1_cur 
----------
 (2,b)
 (3,c)
 (4,d)
(3 rows)

猜你喜欢

转载自blog.csdn.net/ziptop/article/details/45746743