Getting data from a record variable dynamically - Mailing list pgsql-general

From Rhys A.D. Stewart
Subject Getting data from a record variable dynamically
Date
Msg-id CACg0vTnDD1G3GgduCAxuU-41VezxPPKowTOGhkFbrJsXXuGdgw@mail.gmail.com
Whole thread Raw
Responses Re: Getting data from a record variable dynamically  ("David G. Johnston" <david.g.johnston@gmail.com>)
Re: Getting data from a record variable dynamically  (Alban Hertroys <haramrae@gmail.com>)
List pgsql-general
Greetings All,

I have a trigger that is attached to several different tables. In the
trigger function I retrieve a single row and I want the info from a
specific column. This column is dependent on the table in question.
and I have the column name stored in a variable as well. Without
writing a conditional for each table, what is the best way to
dynamically get the data from the record variable?

The only workaround I can think of is to wrap the query that populates
the record variable in a to_jsonb function and then subscript that.
Like so:

DO $$
 DECLARE
  rec record;
  colname text;
 BEGIN
  SELECT to_jsonb(n.*) FROM kgn21.__nodes n limit 1 INTO rec;
  colname = 'lw_id';  -- colname is different for each table
  RAISE NOTICE '%', rec.to_jsonb['lw_table'];
 END;
 $$ language plpgsql;

Is there a better way?

Regards,


Rhys
Peace & Love | Live Long & Prosper



pgsql-general by date:

Previous
From: Christoph Berg
Date:
Subject: Re: AIX and EAGAIN on open()
Next
From: "David G. Johnston"
Date:
Subject: Re: Getting data from a record variable dynamically