postgreSQL PL/SQL编程学习笔记(二)
Control Structures of PL/SQL
Control structures are probably the most useful (and important) part of PL/pgSQL.With PL/pgSQL's control structures, you can manipulate PostgreSQL data in a very flexible and powerful way.
1.Returning From a Function
RETURN
RETURN expression;
RETURN with an expression terminates the function and returns the value of expression to the caller.
This form is used for PL/pgSQL functions that do not return a set.
In a function that returns a scalar type, the expression’s result will automatically be cast into the
function’s return type as described for assignments.
To return a composite (row) value, you must
write an expression delivering exactly the requested column set. This may require use of explicit
casting.
If you declared the function to return void, a RETURN statement can be used to exit the function early;
but do not write an expression following RETURN.
Some examples:
-- functions returning a scalar type
RETURN 1 + 2;
RETURN scalar_var;
-- functions returning a composite type
RETURN composite_type_var;
RETURN (1, 2, ’three’::text); -- must cast columns to correct types
RETURN NEXT and RETURN QUERY
RETURN NEXT expression;
RETURN QUERY query;
RETURN QUERY EXECUTE command-string [ USING expression [, ... ] ];
When a PL/pgSQL function is declared to return SETOF sometype, the individual items to return are specified by a sequence of RETURN NEXT or
RETURN QUERY commands, and then a final RETURN command with no argument is used to indicate
that the function has finished executing.
RETURN NEXT and RETURN QUERY do not actually return from the function — they simply append
zero or more rows to the function’s result set.
If you declared the function with output parameters, write just RETURN NEXT with no expression.
Here is an example of a function using RETURN NEXT:
CREATE TABLE foo (fooid INT, foosubid INT, fooname TEXT);
INSERT INTO foo VALUES (1, 2, 'three');
INSERT INTO foo VALUES (4, 5, 'six');
CREATE OR REPLACE FUNCTION get_all_foo() RETURNS SETOF foo AS
$BODY$
DECLARE
r foo%rowtype;
BEGIN
FOR r IN
SELECT * FROM foo WHERE fooid > 0
LOOP
-- some processing below
r.foosubid = r.foosubid +2333;
r.fooname = r.fooname || 'hello'::text;
RETURN NEXT r; -- return current row of SELECT
END LOOP;
RETURN;
END
$BODY$
LANGUAGE plpgsql;
SELECT * FROM get_all_foo();
if you specified "RETURNS setof record " when create function,like:
CREATE OR REPLACE FUNCTION get_all_foo() RETURNS setof record ....
maybe you should use the way below(cause the system do not know what will return ,you should specified one):
SELECT * FROM get_all_foo() f(fooid int, foosubid int, fooname text);
if you want to return a composite type ,maybe you can first create a new type:
create type myty as (a int ,b int);
then:
CREATE OR REPLACE FUNCTION get_all_fooxx() RETURNS myty AS
$BODY$
BEGIN
RETURN (1,1);
END
$BODY$
LANGUAGE plpgsql;
2.Conditionals
IF and CASE statements let you execute alternative commands based on certain conditions.
IF
for IF-THEN,there are three types:
1.IF-THEN
IF boolean-expression THEN
statements
END IF;
2.IF-THEN-ELSE
IF boolean-expression THEN
statements
ELSE
statements
END IF;
3.IF-THEN-ELSIF
IF boolean-expression THEN
statements
[ ELSIF boolean-expression THEN
statements
[ ELSIF boolean-expression THEN
statements
...]]
[ ELSE
statements ]
END IF;
CASE
for CASE ,there are three types:
1.Simple CASE
CASE search-expression
WHEN expression [, expression [ ... ]] THEN
statements
[ WHEN expression [, expression [ ... ]] THEN
statements
... ]
[ ELSE
statements ]
END CASE;
2.Searched CASE
CASE
WHEN boolean-expression THEN
statements
[ WHEN boolean-expression THEN
statements
... ]
[ ELSE
statements ]
END CASE;
3.LOOPS of PL/SQL
3.1 LOOP
for LOOP, it is often used with EXIT ,CONTINUE ,which is just like "break" and "continue" in C for a loop.
the grammar is like below:
[ <<label>> ]
LOOP
statements
END LOOP [ label ];
example is:
LOOP
-- some computations
EXIT WHEN count > 100;
CONTINUE WHEN count < 50;
-- some computations for count IN [50 .. 100]
END LOOP;
3.2 WHILE
WHILE is just like LOOP,but with some condition:
[ <<label>> ]
WHILE boolean-expression LOOP
statements
END LOOP [ label ];
for boolean-expression you can use NOT, AND, OR.
3.3 FOR(Integer Variant)
The syntax is:
[ <<label>> ]
FOR name IN [ REVERSE ] expression .. expression [ BY expression ] LOOP
-- BY expression is the walk step length
statements
END LOOP [ label ];
example is:
FOR i IN REVERSE 10..1 LOOP
-- i will take on the values 10,9,8,7,6,5,4,3,2,1 within the loop
END LOOP;
FOR i IN REVERSE 10..1 BY 2 LOOP
-- i will take on the values 10,8,6,4,2 within the loop
END LOOP;
3.4 Looping Through Query Results
Using a different type of FOR loop, you can iterate through the results of a query and manipulate that
data accordingly. The syntax is:
[ <<label>> ]
FOR target IN query LOOP
statements
END LOOP [ label ];
3.5 Looping Through Arrays
The FOREACH loop iterates through the elements of an array value.
The FOREACH statement to loop over an array is:
[ <<label>> ]
FOREACH target [ SLICE number ] IN ARRAY expression LOOP
statements
END LOOP [ label ];
4.Trapping Errors
By default, any error occurring in a PL/pgSQL function aborts execution of the function and surrounding transaction as well.
Here, You can trap errors and recover from them by using a BEGIN block with an EXCEPTION clause.
The syntax is an extension of the normal syntax for a BEGIN block:
[ <<label>> ]
[ DECLARE
declarations ]
BEGIN
statements
EXCEPTION
WHEN condition [ OR condition ... ] THEN
handler_statements
[ WHEN condition [ OR condition ... ] THEN
handler_statements
... ]
END;
1)If no error occurs, this form of block simply executes all the statements, and then control passes to the next statement after END.
2)But if an error occurs within the statements, further processing of the statements is abandoned, and control passes to the EXCEPTION list. The list is searched for the first condition matching the error that occurred. If a match is found, the corresponding handler_statements are executed, and then control passes to the next statement after END.
3)If no match is found, the error propagates out as though the EXCEPTION clause were not there at all: the error can be caught by an enclosing block with EXCEPTION, or if there is none it aborts processing of the function.
The condition names can be any of those shown in Appendix A. A category name matches any error within its category. The special condition name OTHERS matches every error type except QUERY_CANCELED and ASSERT_FAILURE. Condition names are not case-sensitive. Also, an error condition can be specified by SQLSTATE code;
for example these are equivalent:
WHEN division_by_zero THEN ...
WHEN SQLSTATE ’22012’ THEN ...
When an error is caught by an EXCEPTION clause:
the local variables of the PL/pgSQL function remain as they were when the error occurred,
but all changes to persistent database state within the block are rolled back.
As an example, consider this fragment:
INSERT INTO mytab(firstname, lastname) VALUES(’Tom’, ’Jones’);
BEGIN
UPDATE mytab SET firstname = ’Joe’ WHERE lastname = ’Jones’;
x := x + 1;
y := x / 0;
EXCEPTION
WHEN division_by_zero THEN
RAISE NOTICE ’caught division_by_zero’;
RETURN x;
END;
Here, results RETURN the incremented value of x, UPDATE command in EXCEPTION block has been rollbacked. so that the database contains Tom Jones not Joe Jones.
Obtaining Information About an Error
There are two ways to get information about the current exception in PL/pgSQL: special variables and the GET STACKED DIAGNOSTICS command.
Within an exception handler, the special variable SQLSTATE contains the error code that corresponds to the exception that was raised. The special variable SQLERRM contains the error message associated with the exception. These variables are undefined outside exception handlers.
the GET STACKED DIAGNOSTICS command, which has the form:
GET STACKED DIAGNOSTICS variable { = | := } item [ , ... ];
Each item is a key word identifying a status value to be assigned to the specified variable (which should be of the right data type to receive it). The currently available status items are shown below:
Here is an example:
DECLARE
text_var1 text;
text_var2 text;
text_var3 text;
BEGIN
-- some processing which might cause an exception
...
EXCEPTION WHEN OTHERS THEN
GET STACKED DIAGNOSTICS text_var1 = MESSAGE_TEXT,
text_var2 = PG_EXCEPTION_DETAIL,
text_var3 = PG_EXCEPTION_HINT;
END;
5.Obtaining Execution Location Information
The GET DIAGNOSTICS command, previously described in Section 41.5.5, retrieves information about current execution state (whereas the GET STACKED DIAGNOSTICS command discussed above reports information about the execution state as of a previous error). Its PG_CONTEXT status item is useful for identifying the current execution location. PG_CONTEXT returns a text string with line(s) of text describing the call stack. The first line refers to the current function and currently executing GET DIAGNOSTICS command. The second and any subsequent lines refer to calling functions further up the call stack.
For example:
CREATE OR REPLACE FUNCTION outer_func() RETURNS integer AS $$
BEGIN
RETURN inner_func();
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION inner_func() RETURNS integer AS $$
DECLARE
stack text;
BEGIN
GET DIAGNOSTICS stack = PG_CONTEXT;
RAISE NOTICE E’--- Call Stack ---\n%’, stack;
RETURN 1;
END;
$$ LANGUAGE plpgsql;
SELECT outer_func();
NOTICE: --- Call Stack ---
PL/pgSQL function inner_func() line 5 at GET DIAGNOSTICS
PL/pgSQL function outer_func() line 3 at RETURN
CONTEXT: PL/pgSQL function outer_func() line 3 at RETURN
outer_func
------------
1
(1 row)
GET STACKED DIAGNOSTICS ... PG_EXCEPTION_CONTEXT returns the same sort of stack trace, but describing the location at which an error was detected, rather than the current location.
postgreSQL PL/SQL编程学习笔记(二)的更多相关文章
- 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编程学习笔记(三)——游标(Cursors)
Cursors Rather than executing a whole query at once, it is possible to set up a cursor that encapsul ...
- 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 ...
- PL/SQL编程基础(二):变量的声明、赋值、(赋值、连接、关系、逻辑)运算符
变量的声明.赋值.运算符 1.声明并使用变量 变量可以在声明时赋值,也可以先定义后赋值: 使用%TYPE与%ROWTYPE可以根据已有类型定义变量. PL/SQL是一种强类型的编程语言,所有的变量都必 ...
- PL/SQL个人学习笔记(二)
IF条件 declare cursor s is select version from city_server t; s_ city_server.version%type ...
- MySql-Mysql技术内幕~SQL编程学习笔记(N)
1._rowid 类似Oracle的rowid mysql> ; +-------+----+----------------+-------------+---------------+--- ...
- MySql-Mysql技术内幕~SQL编程学习笔记(1)
1.MySQL的历史,一些相关概念. 2.MySQL数据类型 *通常一个页内可以存放尽可能多的行,那么数据库的性能就越好,选择一个正确的数据类型至关重要. 1>UNSIGNED类型: 将数字类型 ...
随机推荐
- Springboot项目打成jar包运行 和 打成war包 外部tomcat运行
Jar打包方式运行 类型为jar时 <packaging>jar</packaging> 1.使用命令mvn clean package 打包 2.使用java –jar 包 ...
- JavaScript之BON
1.windows对象 全局作用域: 2.窗口关系及框架 如果页面包含框架,则每个框架都有自己的window对象,并且保存在iframes集合中,在iframe集合中,可以通过数值索引(从0开始,从左 ...
- Nginx配置之基于域名的虚拟主机
1.配置好DNS解析 大家好,今天我给大家讲解下在Linux系统下DNS服务器的基本架设,正向解析,反向解析,负载均衡,还有从域以及一个服务器两个域或者多个域的情况. 实验环境介绍:1.RHEL5.1 ...
- docker问题:docker端口映射错误
1 docker端口映射错误 1.1 问题描述 利用docker启动nginx容器的时候报错: 1.2 解决办法 一次执行下面的命令就可以解决 pkill docker iptables -t nat ...
- Redis02 Redis客户端之Java、连接远程Redis服务器失败
1 查看支持Java的redis客户端 本博文采用 Jedis 作为redis客户端,采用 commons-pool2 作为连接redis服务器的连接池 2 下载相关依赖与实战 2.1 到 Repos ...
- Angular23 loading组件、路由配置、子路由配置、路由懒加载配置
1 需求 由于Angular是单页面的应用,所以在进行数据刷新是进行的局部刷新:在进行数据刷新时从浏览器发出请求到后台响应数据是有时间延迟的,所以在这段时间就需要进行遮罩处理来提示用户系统正在请求数据 ...
- Nginx+Tomcat集群+session共享
Nginx+Tomcat集群+session共享 1)安装Nginx 2)配置多个Tomcat,在server.xml中修改端口(端口不出现冲突即可) 3)在nginx.conf文件中配置负载均衡池, ...
- 25.AVG 函数
定义和用法 AVG 函数返回数值列的平均值.NULL 值不包括在计算中. SQL AVG() 语法 SELECT AVG(column_name) FROM table_name SQL AVG() ...
- Part8-不用内存怎么行_6410内存初始化lesson3
1.6410地址空间 外设区:从0x70000000-0x7FFFFFFF有256MB 主存储区:从0x00000000-0x6FFFFFFF有1972MB 对于主存储区: 静态存储区可以接我们的NO ...
- Tarjan算法求出强连通分量(包含若干个节点)
[功能] Tarjan算法的用途之一是,求一个有向图G=(V,E)里极大强连通分量.强连通分量是指有向图G里顶点间能互相到达的子图.而如果一个强连通分量已经没有被其它强通分量完全包含的话,那么这个强连 ...