0

I'm trying to execute on an alter table to assign a column to a sequence nextval for an auto-increment, but can't seem to figure out how to do this last part. The sequence is created fine, owners are all asigned, and table_a.id is the owner of table_a_id_seq. I've already created table_a_id_seq.

In a postgres sql function, how do I format this correctly.

I've tried:

EXECUTE format('ALTER TABLE ONLY %s ALTER COLUMN id SET DEFAULT nextval($1::regclass)', new_table_name) USING new_seq_name;

But it says that $1 is not pointing to new_table_seq_name. I've also tried:

EXECUTE format('ALTER TABLE ONLY %s ALTER COLUMN id SET DEFAULT nextval("%s"::regclass)', new_table_name, new_seq_name);

But it tells me the sequence doesn't exist which makes me wonder if it needs to be behind a transaction separated by this statement.

How can I successfully execute this alter on new_table_name? Thanks for the help!

3
  • select sequence_schema,sequence_name from information_schema.sequences where sequence_schema ='yourschema' and sequence_name = 'new_seq_name'; would you please just make sure you define schema and seq name well?..
    – Vao Tsun
    Jun 25, 2016 at 18:56
  • Do you want to achieve sth like in DEMO? Jun 25, 2016 at 19:01
  • just to be sure you use nextval('"myschema".foo') syntax (unless you have schema in search path)
    – Vao Tsun
    Jun 25, 2016 at 19:03

1 Answer 1

0

Use the format specifier %L for a literal:

EXECUTE format(
    'ALTER TABLE ONLY %s ALTER COLUMN id SET DEFAULT nextval(%L::regclass)', 
    new_table_name, 
    new_seq_name);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.