Download PostgreSQL 7.1 Programmer`s Guide

Transcript
Chapter 24. PL/pgSQL - SQL Procedural Language
FOR i IN REVERSE 1..10 LOOP
-- some expressions here
END LOOP;
24.2.7. Working with RECORDs
Records are similar to rowtypes, but they have no predefined structure. They are used in selections and
FOR loops to hold one actual database row from a SELECT operation.
24.2.7.1. Declaration
One variables of type RECORD can be used for different selections. Accessing a record or an attempt
to assign a value to a record field when there is no actual row in it results in a runtime error. They can be
declared like this:
name RECORD;
24.2.7.2. Assignments
An assignment of a complete selection into a record or row can be done by:
SELECT
INTO target expressions FROM ...;
target can be a record, a row variable or a comma separated list of variables and record-/row-fields.
Note that this is quite different from Postgres’ normal interpretation of SELECT INTO, which is that the
INTO target is a newly created table. (If you want to create a table from a SELECT result inside a
PL/pgSQL function, use the equivalent syntax CREATE TABLE AS SELECT.)
If a row or a variable list is used as target, the selected values must exactly match the structure of the
target(s) or a runtime error occurs. The FROM keyword can be followed by any valid qualification,
grouping, sorting etc. that can be given for a SELECT statement.
Once a record or row has been assigned to a RECORD variable, you can use the "." (dot) notation to
access fields in that record:
DECLARE
users_rec RECORD;
full_name varchar;
BEGIN
SELECT INTO users_rec * FROM users WHERE user_id=3;
full_name := users_rec.first_name || ’’ ’’ || users_rec.last_name;
There is a special variable named FOUND of type boolean that can be used immediately after a
SELECT INTO to check if an assignment had success.
298