Well - as you might have seen in a long discussion i had on here previously, postgres supports three types of function (store procedure in one case)
SQL stored function
Procedural language function (stored and compiled - Perl/PostgreSQL)
Programming language function (external, compiled - C normally)
For you the best of these is probably plpgsql - the Procedural compiled function.
To create the language plpgsql go to the postgres console ( CMD: psql database postgres )
and enter:
CREATE FUNCTION plpgsql_call_handler() RETURNS OPAQUE AS '/usr/lib/pgsql/plpgsql.so' LANGUAGE 'C';
where '/usr/lib/pgsql/plpgsql.so' is a variable location ( use CMD: locate plpgsql.so on linux )
then enter:
CREATE LANGUAGE 'plpgsql' HANDLER plpgsql_call_handler LANCOMPILER 'PL/pgSQL';
This will give you the ability to use perl/pg functions with logic. This might be something you're already doing, but just in case you're not.
The function takes a DECLARE BEGIN END format:
(example from a triggered procedure)
Code:
CREATE FUNCTION Func_bids_items() RETURNS opaque AS '
DECLARE
item_id int;
bid numeric(10,2);
current_bid numeric(10,2);
bid_count int;
BEGIN
SELECT INTO item_id, bid item_id, bid FROM bids WHERE id=NEW.id;
SELECT INTO current_bid current FROM items where id = item_id;
SELECT INTO bid_count bids FROM items where id = item_id;
if (current_bid < bid){
UPDATE items SET current = bid WHERE id = item_id;
UPDATE items SET bids = (bid_count+1) WHERE id = item_id;
}
else {
DELETE FROM bids WHERE id = NEW.id;
}
END;'
LANGUAGE 'plpgsql';
There's plenty of info on how to use functions and a huge chapter in postgres manuals (and the O'Reilly Practical Postgres) on how to use PL/pgSQL.
Hope you can pull this off without me having to write it for you 
Let me know if you need more mate.
Flawless
Bookmarks