Re: Function PostgreSQL 9.2

From: "drum(dot)lucas(at)gmail(dot)com" <drum(dot)lucas(at)gmail(dot)com>
To: Berend Tober <btober(at)computer(dot)org>
Cc: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>, Alban Hertroys <haramrae(at)gmail(dot)com>, Melvin Davidson <melvin6925(at)gmail(dot)com>, Adrian Klaver <adrian(dot)klaver(at)aklaver(dot)com>, Postgres General <pgsql-general(at)postgresql(dot)org>
Subject: Re: Function PostgreSQL 9.2
Date: 2016-05-05 23:56:23
Message-ID: CAE_gQfWBDRBD0be9q5kU_R2hgeGwX4CYVLcy==4dd5K5Wc-xXQ@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

It's working now...

Final code:

ALTER TABLE public.companies ADD COLUMN client_code_increment integer;
> ALTER TABLE public.companies ALTER COLUMN client_code_increment SET NOT
> NULL;
> ALTER TABLE public.companies ALTER COLUMN client_code_increment SET
> DEFAULT 1000;
> COMMIT TRANSACTION;
>
> BEGIN;
> -- Creating the function
> CREATE OR REPLACE FUNCTION users_code_seq()
> RETURNS "trigger" AS $$
> DECLARE code character varying;
> BEGIN
> -- if it's an insert, then we update the client_code_increment column
> value to +1
> IF (TG_OP = 'INSERT') THEN
> UPDATE public.companies SET client_code_increment =
> (client_code_increment + 1) WHERE id = NEW.company_id;
> END IF;
> -- IF the customer didn't provide a code value, we insert the next
> available from companies.client_code_increment
> IF NEW.code IS NULL THEN
> SELECT client_code_increment INTO NEW.code FROM public.companies
> as c WHERE c.id = NEW.company_id ORDER BY client_code_increment DESC;
> END IF;
> RETURN NEW;
> END;
> $$ LANGUAGE plpgsql;
> -- Creating the trigger
> CREATE TRIGGER tf_users_code_seq
> BEFORE INSERT
> ON public.users
> FOR EACH ROW
> EXECUTE PROCEDURE users_code_seq();
>
> COMMIT TRANSACTION;

Thanks.
Lucas

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message dandl 2016-05-06 00:55:39 Re: CREATE OR REPLACE AGGREGATE -- NOT!
Previous Message Berend Tober 2016-05-05 23:32:28 Re: Function PostgreSQL 9.2