Re: Writing my first trigger

From: Andreas Kretschmer <andreas(at)a-kretschmer(dot)de>
To: pgsql-novice(at)lists(dot)postgresql(dot)org
Subject: Re: Writing my first trigger
Date: 2022-05-20 15:06:11
Message-ID: 81b6ada5-7274-b260-2a59-19c6e450fb30@a-kretschmer.de
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

Am 19.05.22 um 20:18 schrieb Chris Tsongas:
> Working on my first trigger to create a fullName value from firstName,
> optional preferredFirstName, and lastName fields, where the full name
> uses the optional preferred first name if it exists, otherwise it uses
> the first name and of course the required last name.
>
> Would be great to get feedback on the following code before I try
> running it (note I already have an employee table, just including the
> CREATE TABLE statement for clarity):
>
> CREATE TABLE employee (
> firstName text NOT NULL,
> preferredFirstName text,
> lastName text NOT NULL,
> fullName text,
> );
>
> CREATE OR REPLACE FUNCTION update_employee() RETURNS TRIGGER AS $$
> BEGIN
> IF (OLD."preferredFirstName" IS NOT NULL) THEN
> NEW."fullName" = OLD."preferredFirstName" || ' ' || OLD."lastName";
> ELSE
> NEW."fullName" = OLD."firstName" || ' ' || OLD."lastName";
> END IF;
> NEW."updatedAt" = now();
> RETURN NEW;
> END;
> $$ LANGUAGE plpgsql;
>
> CREATE TRIGGER fullName
> INSTEAD OF INSERT OR UPDATE ON employee
> FOR EACH ROW EXECUTE FUNCTION update_employee();
>

your table doesn't contain the field "updatedA". I would suggest to
calculate the fullName at select-time and not via TRIGGER.

Andreas

--
2ndQuadrant, an EDB company
www.2ndQuadrant.com / www.enterprisedb.com

In response to

Responses

Browse pgsql-novice by date

  From Date Subject
Next Message Andreas Kretschmer 2022-05-21 13:36:15 Re: Writing my first trigger
Previous Message hubert depesz lubaczewski 2022-05-20 11:24:59 Re: Writing my first trigger