Examples
PL/pgSQL can be used to define trigger procedures. A trigger procedure is created with the CREATE FUNCTION command as a function with no arguments and a return type of OPAQUE. Note that the function must be declared with no arguments even if it expects to receive arguments specified in CREATE TRIGGER --- trigger arguments are passed via TG_ARGV, as described below.- NEW
- OLD
- TG_NAME
Data type name; variable that contains the name of the trigger actually
fired.
- TG_WHEN
Data type text; a string of either
BEFORE or AFTER
depending on the trigger's definition.
- TG_LEVEL
Data type text; a string of either
ROW or STATEMENT depending on the
trigger's definition.
- TG_OP
- TG_RELID
Data type oid; the object ID of the table that caused the
trigger invocation.
- TG_RELNAME
Data type name; the name of the table that caused the trigger
invocation.
- TG_NARGS
- TG_ARGV[]
Example 23-1. A PL/pgSQL Trigger Procedure Example
CREATE TABLE emp (
empname text,
salary integer,
last_date timestamp,
last_user text
);
CREATE FUNCTION emp_stamp () RETURNS OPAQUE AS '
BEGIN
-- Check that empname and salary are given
IF NEW.empname ISNULL THEN
RAISE EXCEPTION ''empname cannot be NULL value'';
END IF;
IF NEW.salary ISNULL THEN
RAISE EXCEPTION ''% cannot have NULL salary'', NEW.empname;
END IF;
-- Who works for us when she must pay for?
IF NEW.salary < 0 THEN
RAISE EXCEPTION ''% cannot have a negative salary'', NEW.empname;
END IF;
-- Remember who changed the payroll when
NEW.last_date := ''now'';
NEW.last_user := current_user;
RETURN NEW;
END;
' LANGUAGE 'plpgsql';
CREATE TRIGGER emp_stamp BEFORE INSERT OR UPDATE ON emp
FOR EACH ROW EXECUTE PROCEDURE emp_stamp();Example 2. A Simple PL/pgSQL Function to Increment an Integer
CREATE FUNCTION add_one (integer) RETURNS INTEGER AS '
BEGIN
RETURN $1 + 1;
END;
' LANGUAGE 'plpgsql';Example 3. A Simple PL/pgSQL Function to Concatenate Text
This function receives two text parameters and returns the result of concatenating them.
CREATE FUNCTION concat_text (TEXT, TEXT) RETURNS TEXT AS '
BEGIN
RETURN $1 || $2;
END;
' LANGUAGE 'plpgsql';
No comments:
Post a Comment