Re: Setting a default for nextval sequence

From: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
To: Robert Lakes <robertl(at)propaas(dot)com>
Cc: "pgsql-general(at)postgresql(dot)org" <pgsql-general(at)postgresql(dot)org>
Subject: Re: Setting a default for nextval sequence
Date: 2017-11-27 19:24:10
Message-ID: CAKFQuwa+i_PVMJC+spzyX_qN0Bgccc8LWzPFTMaTS8P=hyGRnQ@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Mon, Nov 27, 2017 at 12:13 PM, Robert Lakes <robertl(at)propaas(dot)com> wrote:

> I'm attempting to set the default value for a serial column. I created a
> generic function that I am passing a table name as the only parameter. I
> had it working correctly, however, it does not seem to like the sequence
> name being the same name for each audit table that is created through the
> function.
> So I changed the code to include the table name as part of the naming
> convention. Now, I need help on how to alter the serial column the new
> value
>
> EXECUTE 'CREATE SEQUENCE '|| t_name ||'tab_id_seq'|| ' OWNED BY '|| t_name
> || '_cdc'||'.table_id';
>
> EXECUTE 'ALTER TABLE ' || quote_ident(t_name || '_cdc') || ' ALTER
> COLUMN table_id SET DEFAULT nextval(''tab_id_seq'');';
>

​Not tested but:​

​EXECUTE format('CREATE SEQUENCE %I OWNED BY %I.table_id',
t_name || 'tab_id_seq',
t_name ||​ '_cdc');

EXECUTE format('ALTER TABLE %I ALTER COLUMN table_id SET DEFAULT
nextval(%L);',
t_name || '_cdc',
t_name || 'tab_id_seq');

​David J.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Melvin Davidson 2017-11-27 19:29:32 Re: Setting a default for nextval sequence
Previous Message Tom Lane 2017-11-27 19:16:25 Re: ERROR: too many dynamic shared memory segments