Re: Stored procedure - change columns in a table that is being updated / inserted on?

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: bryan(at)flyingiranch(dot)com
Cc: pgsql-novice(at)postgresql(dot)org
Subject: Re: Stored procedure - change columns in a table that is being updated / inserted on?
Date: 2003-03-08 23:17:50
Message-ID: 12908.1047165470@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

bryan(at)flyingiranch(dot)com writes:
> As you can see, I created a new table, tbluserhealthcalculated, that is
> actually written to on any insert or update to tbluserhealthbasic.

This sure seems like the hard way to do it. If you really want
tbluserhealthcalculated to be separate from the underlying table,
why don't you make it a view?

CREATE VIEW tbluserhealthcalculated AS
SELECT *, (userWeight / (userHeight * userHeight)) AS bmi
FROM tbluserhealthbasic;

On the other hand, if you'd rather there were only one table, you
should be fixing the bmi value in a BEFORE trigger not an AFTER trigger.

CREATE FUNCTION calcbmi() RETURNS trigger AS '
BEGIN
NEW.bmi := (NEW.userWeight / (NEW.userHeight * NEW.userHeight));
RETURN NEW;
END' language plgsql;

CREATE TRIGGER docalcbmi BEFORE INSERT OR UPDATE
ON tblUserHealthBasic FOR EACH ROW EXECUTE
PROCEDURE calcbmi();

regards, tom lane

In response to

Browse pgsql-novice by date

  From Date Subject
Next Message bryan 2003-03-08 23:20:55 Re: Stored procedure - change columns in a table that is being updated / inserted on?
Previous Message bryan 2003-03-08 23:11:17 Re: Stored procedure - change columns in a table that is being updated / inserted on?