Re: Column value derived from generated column in INSERT? - Mailing list pgsql-general

From Adrian Klaver
Subject Re: Column value derived from generated column in INSERT?
Date
Msg-id 82c73b61-3028-639d-5406-e50dbc998498@aklaver.com
Whole thread Raw
In response to Re: Column value derived from generated column in INSERT?  (Adrian Klaver <adrian.klaver@aklaver.com>)
Responses Re: Column value derived from generated column in INSERT?
List pgsql-general
On 10/19/22 12:58 PM, Adrian Klaver wrote:
> On 10/19/22 12:48, Mark Raynsford wrote:
>> On 2022-10-19T12:43:31 -0700
>> Adrian Klaver <adrian.klaver@aklaver.com> wrote:
>>>
>>> HINT:  There is an entry for table "t", but it cannot be referenced from
>>> this part of the query.
>>>
>>> HINT:  There is a column named "x" in table "t", but it cannot be
>>> referenced from this part of the query.
>>
>> Yes, I saw those, hence asking on the list if there was a way to do it.
> 
> Using a trigger.

To expand:

create table t (
     x integer not null generated always as identity,
     y integer not null
   );
insert into t(y) values (1);

select * from t;

x | y
---+---
  1 | 1
(1 row)



CREATE FUNCTION identity_test( )
  RETURNS trigger
  LANGUAGE plpgsql
AS $function$
BEGIN
     NEW.y = NEW.x * 2;
     RETURN NEW;
END;

$function$
;

create trigger identity_trg before insert on t for each row execute 
function identity_test();

insert into t(y) values (0);

select * from t;

  x | y
---+---
  1 | 1
  2 | 4
(2 rows)

> 
>>
>> I'll handle it with multiple statements.
>>
> 


-- 
Adrian Klaver
adrian.klaver@aklaver.com



pgsql-general by date:

Previous
From: Thomas Kellerer
Date:
Subject: Re: COMMIT IN STORED PROCEDURE WHILE IN A LOOP
Next
From: Erik Wienhold
Date:
Subject: Re: Column value derived from generated column in INSERT?