Function predefined variables

The PL/pgSQL functions have several special variables that are created automatically in the top-level block. For example, if the function returns a trigger, then several variables, such as NEW, OLD, and TG_OP, are created.

In addition to the trigger special values, there is a Boolean variable called FOUND. This is often used in combination with DML and PERFORM statements to conduct sanity checks. The value of the FOUND variable is affected by the SELECT, INSERT, UPDATE, DELETE, and PERFORM statements. These statements set FOUND to true if at least one row is selected, inserted, updated, or deleted.

The PERFORM statement is similar to the SELECT statement, but it discards the result of the query. Finally, the EXECUTE statement does not change the value of the FOUND variable. The following examples show how the FOUND variable is affected by the INSERT and PERFORM statements:

DO $$
BEGIN
CREATE TABLE t1(f1 int);

INSERT INTO t1 VALUES (1);
RAISE NOTICE '%', FOUND;

PERFORM* FROM t1 WHERE f1 = 0;
RAISE NOTICE '%', FOUND;
DROP TABLE t1;
END;
$$LANGUAGE plpgsql;
--- output
NOTICE: t
NOTICE: f

In addition to the preceding query, one could get the last OID--object identifier--for an inserted row, as well as the affected number of rows, by using the INSERT, UPDATE, and DELETE statements via the following commands:

GET DIAGNOSTICS variable = item;

Assuming that there is a variable called i of type integer, one can get the affected number of rows, as follows:

GET DIAGNOSTICS i = ROW_COUNT;
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset