pl/PgSQL, variable names in NEW

From: Martin Edlman <edlman(at)fortech(dot)cz>
To: pgsql-sql(at)postgresql(dot)org
Subject: pl/PgSQL, variable names in NEW
Date: 2008-04-07 11:19:39
Message-ID: 47FA034B.7090201@fortech.cz
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-docs pgsql-hackers pgsql-sql

Hello,

is it possible to use variables as field names in the NEW record? Let's
suppose I have a varchar attname containg the name of the field and I want
to know a value that field of the NEW record.

Problem is that I get an error 'record "new" has no field "attname"'. Of
course I want to use a value of NEW.author when col.attname = attname =
'author'.

Is there a solution?

Example trigger function. It finds all columns in the table which are
referenced in other tables and checks if the value of the column has
changed. If yes, then invoke some other function. The problem is that the
column name is in the 'col' record and is different during the loop and at
each function call.

CREATE OR REPLACE FUNCTION replace_values() RETURNS trigger AS
$BODY$
DECLARE
col record;
attname varchar;
BEGIN
FOR col IN
SELECT DISTINCT pgaf.attname, pgaf.attnum
FROM pg_constraint, pg_attribute AS pgaf
WHERE pg_constraint.contype = 'f' -- fkey
AND pg_constraint.confrelid = TG_RELID -- table oid
AND pgaf.attrelid = TG_RELID
AND pgaf.attnum = ANY(pg_constraint.confkey) LOOP

attname := col.attname;
IF NEW.attname <> OLD.attname THEN
RAISE NOTICE ' value changed from "%" to "%"', OLD.attname, NEW.attname;
-- INVOKE OTHER FUNCTION
END IF;
END LOOP;

END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE;

--
Martin Edlman
Fortech Ltd.
57001 Litomysl, CZ

Responses

Browse pgsql-docs by date

  From Date Subject
Next Message Pavel Stehule 2008-04-07 12:11:23 Re: pl/PgSQL, variable names in NEW
Previous Message Bruce Momjian 2008-04-07 00:51:33 Details for ROW IS NULL test

Browse pgsql-hackers by date

  From Date Subject
Next Message Pavel Stehule 2008-04-07 12:11:23 Re: pl/PgSQL, variable names in NEW
Previous Message Tom Dunstan 2008-04-07 10:46:37 Re: [HACKERS] Database owner installable modules patch

Browse pgsql-sql by date

  From Date Subject
Next Message Pavel Stehule 2008-04-07 12:11:23 Re: pl/PgSQL, variable names in NEW
Previous Message Sabin Coanda 2008-04-07 08:56:35 undefined relations in pg_locks