Received: from maia.hub.org (unknown [200.46.208.211]) by mail.postgresql.org (Postfix) with ESMTP id 2D97C633C7C for ; Mon, 1 Mar 2010 12:30:19 -0400 (AST) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.208.211]) (amavisd-maia, port 10024) with ESMTP id 69260-02 for ; Mon, 1 Mar 2010 16:30:08 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from out04.wanadoo.es (out04.wanadoo.es [62.36.20.204]) by mail.postgresql.org (Postfix) with ESMTP id 634D9633BC3 for ; Mon, 1 Mar 2010 12:30:08 -0400 (AST) Received: from [83.44.109.142] (helo=hilex11.localnet) by out04.wanadoo.es with esmtpa (Exim 4.43) id 1Nm8VR-0000NM-P8 for pgsql-sql@postgresql.org; Mon, 01 Mar 2010 17:30:06 +0100 From: Aron To: pgsql-sql@postgresql.org Subject: Re: Using new.id in the WHERE condition of one UPDATE inside ON INSERT rule Date: Mon, 1 Mar 2010 17:30:05 +0100 User-Agent: KMail/1.12.2 (Linux/2.6.31-19-generic; KDE/4.3.2; x86_64; ; ) References: <201002251619.32048.auryn@wanadoo.es> <3702.1267111736@sss.pgh.pa.us> In-Reply-To: <3702.1267111736@sss.pgh.pa.us> MIME-Version: 1.0 Content-Type: Text/Plain; charset="iso-8859-15" Content-Transfer-Encoding: quoted-printable Message-Id: <201003011730.05471.auryn@wanadoo.es> X-login: X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-0.185 tagged_above=-10 required=5 tests=BAYES_40=-0.185 X-Spam-Level: X-Archive-Number: 201003/6 X-Sequence-Number: 33713 On Jueves 25 Febrero 2010 16:28:56 usted escribi=F3: > Aron writes: > > I would like to avoid using "SELECT MAX(id) FROM my_table" (it doesn't > > seem a good method), but if I use "new.id", I get new id values, not the > > "id" inserted with the rule, and the condition is always false. >=20 > "new.id" is a macro, which in this example will be expanded into a > nextval() function call, which is why it doesn't work --- the nextval() > in the WHERE condition will produce a different value from the one in > the original INSERT. You would be far better off using a trigger here > instead of a rule. >=20 > regards, tom lane >=20 Thank you very much. I've used this trigger succesfully: CREATE OR REPLACE FUNCTION copy_cost RETURNS "trigger" AS ' DECLARE change_other BOOL; BEGIN IF (tg_op =3D ''UPDATE'') THEN IF (new.id_other <> old.id_other) THEN change_other =3D true; ELSE change_other =3D false; END IF; END IF; IF (tg_op =3D ''INSERT'' AND new.my_cost IS NULL) OR change_other) THEN new.my_cost =3D ( SELECT my_other_cost FROM my_other_table WHERE id =3D new.id_other ); END IF; RETURN NEW; END; ' LANGUAGE 'plpgsql'; CREATE TRIGGER copy_cost__trigger BEFORE INSERT OR UPDATE ON my_table FOR EACH ROW EXECUTE PROCEDURE copy_cost();