暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

openGauss每日一练第17天|学习游标

原创 小民 2021-12-17
586

1. 创建游标,且使用select子句指定游标返回的行,分别使用FETCH抓取数据,MOVE重定位游标

create table students ( id integer, name char(30), age integer, email char(50) ); insert into students values (0001, 'wy', 19, 'wy@qq.com'), (0002, 'lisi', 19, 'lisi@qq.com'),(0003, 'wangwu', 20, 'wangwu@qq.com'),(0004, 'liuxing', 19, 'liuxing@qq.com'); start transaction; CURSOR cursor1 FOR SELECT * FROM students ORDER BY 1; FETCH FORWARD 3 FROM cursor1; MOVE FORWARD 3 FROM cursor1; /

image.png
2. 在系统视图pg_cursors中查看游标

select * from pg_cursors; close cursor1; end; /

image.png
3. 创建一个使用游标的存储过程

create or replace procedure test_cursor_1 as students_id integer; students_name char(30); students_age integer; students_email char(50); cursor c1_all is --cursor without args select id, name, age, email from students; begin if not c1_all%isopen then open c1_all; end if; loop fetch c1_all into students_id, students_name, students_age, students_email; RAISE INFO 'students_name: %', students_name; exit when c1_all%notfound; end loop; if c1_all%isopen then close c1_all; end if; end; / call test_cursor_1(); drop procedure test_cursor_1; /

image.png
如果出现下图所示,是习惯把查询的字段id,name,age,email变为students_id,students_name,students_age,students_email导致无法查询到数据。
image.png
4. 清理数据

drop table students; /

「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论