Re: Function PostgreSQL 9.2 - Mailing list pgsql-general

From drum.lucas@gmail.com
Subject Re: Function PostgreSQL 9.2
Date
Msg-id CAE_gQfU5syUhyQFZZob5z4bEMem06QUdYFrAh+ZWGYi3+bxVMA@mail.gmail.com
Whole thread Raw
In response to Re: Function PostgreSQL 9.2  ("drum.lucas@gmail.com" <drum.lucas@gmail.com>)
Responses Re: Function PostgreSQL 9.2
List pgsql-general


On 3 May 2016 at 12:44, drum.lucas@gmail.com <drum.lucas@gmail.com> wrote:
This is what I've done:


-- 1 - Creating the Sequence:

    CREATE SEQUENCE users_code_seq  
    INCREMENT 1  
    MINVALUE 1
    MAXVALUE 9223372036854775807  
    START 1000;
    CACHE 1;

-- 2 - Setting the DEFAULT

    ALTER TABLE public.users ALTER COLUMN code SET DEFAULT NEXTVAL('users_code_seq');

-- 3 - Setting the column as NOT NULL;

    ALTER TABLE public.users ALTER COLUMN code SET NOT NULL;

-- 4 - Setting the trigger

            CREATE TRIGGER public.update_code_column
              BEFORE UPDATE OR INSERT
              ON public.users
              FOR EACH ROW
              EXECUTE PROCEDURE public.users_code_seq;

-- 5 - Creating a CONSTRAINT UNIQUE
        ALTER TABLE public.users
          ADD CONSTRAINT uc_users_code UNIQUE("code");


Is that right?
Am I missing something?

Cheers
Lucas


Well.. I don't need to add a constraint if I already have a default value, that's right...

Anyway...


hmm.. actually.. it's a little bit different what I've done and what I need =(


1 - each user on the public.users table, is part of a company. Each company has a unique company_id

2 - Remember the default 1000 value? That value is per company.

Example:

Company Test1 - Company_id = 1
- user john01 = users.code: 1000
- user john02 = users.code: Nz
- user john03 = users.code: 1001
- user john04 = users.code: Nz

Company Test2 - Company_id = 2
- user matt01 = users.code: Text1
- user matt02 = users.code: 1000
- user matt03 = users.code: 1001
- user matt04 = users.code: 1002

Company Test3 - Company_id = 3
- user luke01 = users.code: 1000
- user luke02 = users.code: 1001
- user luke03 = users.code: Text2
- user luke04 = users.code: 1002


So, the default value is 1000 for EACH company. And the users must get the nextval value from there.


How can I do that?
Or at least if you guys can give me a direction...

Cheers

pgsql-general by date:

Previous
From: Sameer Kumar
Date:
Subject: Re: index question
Next
From: "David G. Johnston"
Date:
Subject: Re: Function PostgreSQL 9.2