postgreSQL PL/SQL编程学习笔记(三)——游标(Cursors)
Cursors
Rather than executing a whole query at once, it is possible to set up a cursor that encapsulates the query, and then read the query result a few rows at a time. A more interesting usage is to return a reference to a cursor that a function has created, allowing the caller to read the rows.
1. Declaring Cursor Variables
All access to cursors in PL/pgSQL goes through cursor variables, which are always of the special data type refcursor. One way to create a cursor variable is just to declare it as a variable of type refcursor. Another way is to use the cursor declaration syntax, which in general is:
name [ [ NO ] SCROLL ] CURSOR [ ( arguments ) ] FOR query;
If SCROLL is specified, the cursor will be capable of scrolling backward;
If NO SCROLL is specified, backward fetches will be rejected;
If neither specification appears, it is query-dependent whether backward fetches will be allowed.
Arguments, if specified, is a comma-separated list of pairs name datatype that define names to be replaced by parameter values in the given query.
Some examples:
DECLARE
curs1 refcursor;
curs2 CURSOR FOR SELECT * FROM tenk1;
curs3 CURSOR (key integer) FOR SELECT * FROM tenk1 WHERE unique1 = key;
The variable curs1 is said to be unbound since it is not bound to any particular query. while the second has a fully specified query already bound to it, and the last has a parameterized query bound to it.
2. Opening Cursors
Before a cursor can be used to retrieve rows, it must be opened. (equal to the SQL command DECLARE CURSOR.) PL/pgSQL has three forms of the OPEN statement, two of which use unbound cursor variables while the third uses a bound cursor variable.
2.1. OPEN FOR query
OPEN unbound_cursorvar [ [ NO ] SCROLL ] FOR query;
The cursor variable here should be a simple refcursor variable that has not been opened.
The query must be a SELECT, or something else that returns rows (such as EXPLAIN). The query is treated in the same way as other SQL commands in PL/pgSQL: PL/pgSQL variable names are substituted, and the query plan is cached for possible reuse.
When a PL/pgSQL variable is substituted into the cursor query, the value that is substituted is the one it has at the time of the OPEN; subsequent changes to the variable will not affect the cursor’s behavior.
The SCROLL and NO SCROLL options have the same meanings as for a bound cursor.
An example:
OPEN curs1 FOR SELECT * FROM foo WHERE key = mykey;
2.2. OPEN FOR EXECUTE
OPEN unbound_cursorvar [ [ NO ] SCROLL ] FOR EXECUTE query_string
[ USING expression [, ... ] ];
The cursor variable is opened and given the specified query to execute. The cursor variable here should be a simple refcursor variable that has not been opened.
The query is specified as a string expression, in the same way as in the EXECUTE command.
As usual, this gives flexibility so the query plan can vary from one run to the next, and it also means that variable substitution is not done on the command string.
As with EXECUTE, parameter values can be inserted into the dynamic command via format() and USING.
The SCROLL and NO SCROLL options have the same meanings as for a bound cursor.
An example:
OPEN curs1 FOR EXECUTE format(’SELECT * FROM %I WHERE col1 = $1’,tabname) USING keyvalue;
In this example, the table name is inserted into the query via format(). The comparison value for col1 is inserted via a USING parameter, so it needs no quoting.
2.3. Opening a Bound Cursor
OPEN bound_cursorvar [ ( [ argument_name := ] argument_value [, ...] ) ];
This form of OPEN is used to open a cursor variable whose query was bound to it when it was declared. The cursor cannot be open already. A list of actual argument value expressions must appear if and only if the cursor was declared to take arguments. These values will be substituted in the query.
The query plan for a bound cursor is always considered cacheable; there is no equivalent of EXECUTE in this case.
Notice that SCROLL and NO SCROLL cannot be specified in OPEN, as the cursor’s scrolling behavior was already determined.
Argument values can be passed using either positional or named notation.
In positional notation, all arguments are specified in order.
In named notation, each argument’s name is specified using := to separate it from the argument expression.
Similar to calling functions, it is also allowed to mix positional and named notation. Examples (these use the cursor declaration examples above):
OPEN curs2;
OPEN curs3(42);
OPEN curs3(key := 42);
Because variable substitution is done on a bound cursor’s query, there are really two ways to pass values into the cursor: either with an explicit argument to OPEN, or implicitly by referencing a PL/pgSQL variable in the query. For example, another way to get the same effect as the curs3 example above is
DECLARE
key integer;
curs4 CURSOR FOR SELECT * FROM tenk1 WHERE unique1 = key;
BEGIN
key := 42;
OPEN curs4;
3. Using Cursors
Once a cursor has been opened, it can be manipulated with the statements described here. These manipulations need not occur in the same function that opened the cursor to begin with. You can return a refcursor value out of a function and let the caller operate on the cursor.
3.1. FETCH
FETCH [ direction { FROM | IN } ] cursor INTO target;
FETCH retrieves the next row from the cursor into a target, which might be a row variable, a record variable, or a comma-separated list of simple variables, just like SELECT INTO.
If there is no next row, the target is set to NULL(s). As with SELECT INTO, the special variable FOUND can be checked to see whether a row was obtained or not.
The direction clause can be any of the variants allowed in the SQL FETCH command except the ones that can fetch more than one row; namely, it can be NEXT, PRIOR, FIRST, LAST, ABSOLUTE count, RELATIVE count, FORWARD, or BACKWARD. Omitting direction is the same as specifying NEXT.
direction values that require moving backward are likely to fail unless the cursor was declared or opened with the SCROLL option.
cursor must be the name of a refcursor variable that references an open cursor portal.
Examples:
FETCH curs1 INTO rowvar;
FETCH curs2 INTO foo, bar, baz;
FETCH LAST FROM curs3 INTO x, y;
FETCH RELATIVE -2 FROM curs4 INTO x;
3.2. MOVE
MOVE [ direction { FROM | IN } ] cursor;
MOVE repositions a cursor without retrieving any data. MOVE works exactly like the FETCH command, except it only repositions the cursor and does not return the row moved to.
As with SELECT INTO, the special variable FOUND can be checked to see whether there was a next row to move to.
The direction clause can be any of the variants allowed in the SQL FETCH command. Omitting direction is the same as specifying NEXT.
direction values that require moving backward are likely to fail unless the cursor was declared or opened with the SCROLL option.
Examples:
MOVE curs1;
MOVE LAST FROM curs3;
MOVE RELATIVE -2 FROM curs4;
MOVE FORWARD 2 FROM curs4;
3.3. UPDATE/DELETE WHERE CURRENT OF
UPDATE table SET ... WHERE CURRENT OF cursor;
DELETE FROM table WHERE CURRENT OF cursor;
When a cursor is positioned on a table row, that row can be updated or deleted using the cursor to identify the row.
There are restrictions on what the cursor’s query can be (in particular, no grouping) and it’s best to use FOR UPDATE in the cursor. For more information see the DECLARE reference page.
An example:
UPDATE foo SET dataval = myval WHERE CURRENT OF curs1;
3.4. CLOSE
CLOSE cursor;
CLOSE closes the portal underlying an open cursor. This can be used to release resources earlier than end of transaction, or to free up the cursor variable to be opened again.
An example:
CLOSE curs1;
3.5. Returning Cursors
PL/pgSQL functions can return cursors to the caller. This is useful to return multiple rows or columns, especially with very large result sets.
To do this, the function opens the cursor and returns the cursor name to the caller (or simply opens the cursor using a portal name specified by or otherwise known to the caller).
The caller can then fetch rows from the cursor. The cursor can be closed by the caller, or it will be closed automatically when the transaction closes.
The portal name used for a cursor can be specified by the programmer or automatically generated. To specify a portal name, simply assign a string to the refcursor variable before opening it. The string value of the refcursor variable will be used by OPEN as the name of the underlying portal. However, if the refcursor variable is null, OPEN automatically generates a name that does not conflict with any existing portal, and assigns it to the refcursor variable.
Note: A bound cursor variable is initialized to the string value representing its name, so that the portal name is the same as the cursor variable name, unless the programmer overrides it by assignment before opening the cursor. But an unbound cursor variable defaults to the null value initially, so it will receive an automatically-generated unique name, unless overridden.
The following example shows one way a cursor name can be supplied by the caller:
CREATE TABLE test (col text);
INSERT INTO test VALUES (’123’);
CREATE FUNCTION reffunc(refcursor) RETURNS refcursor AS ’
BEGIN
OPEN $1 FOR SELECT col FROM test;
RETURN $1;
END;
’ LANGUAGE plpgsql;
BEGIN;
SELECT reffunc(’funccursor’);
FETCH ALL IN funccursor;
COMMIT;
The following example uses automatic cursor name generation:
CREATE FUNCTION reffunc2() RETURNS refcursor AS ’
DECLARE
ref refcursor;
BEGIN
OPEN ref FOR SELECT col FROM test;
RETURN ref;
END;
’ LANGUAGE plpgsql;
-- need to be in a transaction to use cursors.
BEGIN;
SELECT reffunc2();
reffunc2
--------------------
<unnamed cursor 1>
(1 row)
FETCH ALL IN "<unnamed cursor 1>";
COMMIT;
The following example shows one way to return multiple cursors from a single function:
CREATE FUNCTION myfunc(refcursor, refcursor) RETURNS SETOF refcursor AS $$
BEGIN
OPEN $1 FOR SELECT * FROM table_1;
RETURN NEXT $1;
OPEN $2 FOR SELECT * FROM table_2;
RETURN NEXT $2;
END;
$$ LANGUAGE plpgsql;
-- need to be in a transaction to use cursors.
BEGIN;
SELECT * FROM myfunc(’a’, ’b’);
FETCH ALL FROM a;
4. Looping Through a Cursor’s Result
There is a variant of the FOR statement that allows iterating through the rows returned by a cursor.
The syntax is:
[ <<label>> ]
FOR recordvar IN bound_cursorvar [ ( [ argument_name := ] argument_value [, ...] ) ] LOOP
statements
END LOOP [ label ];
The cursor variable must have been bound to some query when it was declared, and it cannot be open already. The FOR statement automatically opens the cursor, and it closes the cursor again when the loop exits.
A list of actual argument value expressions must appear if and only if the cursor was declared to take arguments. These values will be substituted in the query, in just the same way as during an OPEN.
The variable recordvar is automatically defined as type record and exists only inside the loop (any existing definition of the variable name is ignored within the loop). Each row returned by the cursor is successively assigned to this record variable and the loop body is executed.
postgreSQL PL/SQL编程学习笔记(三)——游标(Cursors)的更多相关文章
- postgreSQL PL/SQL编程学习笔记(二)
Control Structures of PL/SQL Control structures are probably the most useful (and important) part of ...
- postgreSQL PL/SQL编程学习笔记(六)——杂七杂八
1 PL/pgSQL Under the Hood This part discusses some implementation details that are frequently import ...
- postgreSQL PL/SQL编程学习笔记(五)——触发器(Triggers)
Trigger Procedures PL/pgSQL can be used to define trigger procedures on data changes or database eve ...
- postgreSQL PL/SQL编程学习笔记(一)
1.Structure of PL/pgSQL The structure of PL/pgSQL is like below: [ <<label>> ] [ DECLARE ...
- postgreSQL PL/SQL编程学习笔记(四)
Errors and Messages 1. Reporting Errors and Messages Use the RAISE statement to report messages and ...
- [推荐]ORACLE PL/SQL编程之四:把游标说透(不怕做不到,只怕想不到)
原文:[推荐]ORACLE PL/SQL编程之四:把游标说透(不怕做不到,只怕想不到) [推荐]ORACLE PL/SQL编程之四: 把游标说透(不怕做不到,只怕想不到) 继上两篇:ORACLE PL ...
- PL/SQL 编程(二)游标、存储过程、函数
游标--数据的缓存区 游标:类似集合,可以让用户像操作数组一样操作查询出来的数据集,实质上,它提供了一种从集合性质的结果中提取单条记录的手段. 可以将游标形象的看成一个变动的光标,他实质上是一个指针, ...
- PL/SQL编程基础(三):数据类型划分
数据类型划分 在Oracle之中所提供的数据类型,一共分为四类: 标量类型(SCALAR,或称基本数据类型) 用于保存单个值,例如:字符串.数字.日期.布尔: 标量类型只是作为单一类型的数据存在,有的 ...
- python网络编程学习笔记(三):socket网络服务器(转载)
1.TCP连接的建立方法 客户端在建立一个TCP连接时一般需要两步,而服务器的这个过程需要四步,具体见下面的比较. 步骤 TCP客户端 TCP服务器 第一步 建立socket对象 建立socket对 ...
随机推荐
- Java之匿名内部类和包装类
匿名内部类 作用: 假如某个类只使用一次,则可以使用匿名内部类,无需再新建该类 我们上下代码: package com.learn.chap03.sec16; /** * 定义接口 */ public ...
- krpano之字幕添加
字幕是指介绍语音的字幕,字幕随着语音的播放而滚动,随语音暂停而暂停.字幕添加的前提是用之前的方法添加过介绍语音. 原理: 字幕层在溢出隐藏的父元素中向右滑动,当点击声音控制按钮时,字幕位置被固定,再次 ...
- freemodbus modbus TCP 学习笔记
1.前言 使用modbus有些时间了,期间使用过modbus RTU也使用过modbus TCP,通过博文和大家分享一些MODBUS TCP的东西.在嵌入式中实现TCP就需要借助一个以太网协议 ...
- 「小程序JAVA实战」微信小程序简介(一)
转自:https://idig8.com/2018/08/09/xiaochengxu-chuji-01/ 一直想学习小程序,苦于比较忙,加班比较多没时间,其实这都是理由,很多时候习惯了搬砖,习惯了固 ...
- vue中使用markdown富文本,并在html页面中展示
想给自己的后台增加一个markdown编辑器,下面记录下引用的步骤 引入组件mavon-editor 官网地址:https://github.com/hinesboy/mavonEditor // 插 ...
- Eclipse中建立Maven项目后,Java Resources资源文件下没有src/main/java文件夹
当建立好一个Maven项目后,在Java Resources资源文件夹下没有看到src/main/java文件夹,然后手动去创建Source Folder时,提示该文件已存在,如图: 有一个解决办法: ...
- Java多线程-新特征-信号量Semaphore
简介信号量(Semaphore),有时被称为信号灯,是在多线程环境下使用的一种设施, 它负责协调各个线程, 以保证它们能够正确.合理的使用公共资源. 概念Semaphore分为单值和多值两种,前者只能 ...
- webmagic使用
webmagic是Java语言用于爬虫的工具.官网地址:http://webmagic.io/,中文文档地址:http://webmagic.io/docs/zh/ 使用webmagic有3种配置需要 ...
- ajax请求参数中含有特殊字符"#"的问题 (另附上js编码解码的几种方法)
使用ajax向后台提交的时候 由于参数中含有# 默认会被截断 只保留#之前的字符 json格式的字符串则不会被请求到后台的action 可以使用encodeURIComponent在前台进行编码, ...
- Android 建立AIDL的步骤
建立AIDL服务要比建立普通的服务复杂一些,具体步骤如下: (1)在Eclipse Android工程的Java包目录中建立一个扩展名为aidl的文件.该文件的语法类似于Java代码,但会稍有不同.详 ...