Lab #11 Worksheet – Triggers, & Cursors

Triggers

A trigger is procedural SQL code associated with a given table, and is automatically executed before or after some update/insertion/deletion on that table (triggering event). A trigger can be used to enforce constraints, to automate critical actions (like updating some derived attribute). A trigger can update values, insert records, and call procedures. A table may have multiple triggers that are fired on different events and can do different things. Triggers add processing capabilities to a database application (event-based actions).

To create a new trigger in PostgreSQL, you follow these steps:

CREATE FUNCTION trigger_function()
RETURNS TRIGGER
LANGUAGE PLPGSQL 
AS $$ BEGIN					 Β 
-- trigger logic
END;
$$;

A trigger function receives data about its calling environment through a special structure called TriggerData which contains a set of local variables. For example, OLD and NEW represent the states of the row in the table before or after the triggering event.

CREATE TRIGGER trigger_name {BEFORE | AFTER} { event }
 ON table_name
 [FOR [EACH] { ROW | STATEMENT }]		
EXECUTE PROCEDURE trigger_function
ALTER TABLE Product ADD COLUMN reorder smallint;
CREATE FUNCTION update_prod() RETURNS TRIGGER
AS $$
BEGIN
UPDATE Product
SET reorder = 1
WHERE productCode = NEW.productCode;
RETURN NEW;
END;
$$
LANGUAGE plpgsql;

CREATE TRIGGER trProdUpd AFTER UPDATE ON
Product FOR EACH ROW
WHEN (OLD.quantityOnHand IS DISTINCT FROM NEW.quantityOnHand
AND NEW.quantityOnHand < NEW.minQuantityOnHand) EXECUTE FUNCTION update_prod();
UPDATE Product
    SET quantityOnHand = quantityOnHand - 9
    WHERE productCode = '1546-QQ2';

Check that product’s row values.

What happened? Please note that this trigger may need improvement.