简体   繁体   English

在postgres中使用变量和表名正确格式化执行更改

[英]Properly formatting an execute alter with variable and table name in postgres

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. 我正在尝试在alter table上执行,以将一列分配给nextval序列以进行自动增量,但似乎无法弄清楚如何完成最后一部分。 The sequence is created fine, owners are all asigned, and table_a.id is the owner of table_a_id_seq . 序列创建精细,业主都asigned,并table_a.id是所有者table_a_id_seq I've already created table_a_id_seq . 我已经创建了table_a_id_seq

In a postgres sql function, how do I format this correctly. 在postgres sql函数中,如何正确设置此格式。

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 . 但是它说$ 1没有指向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 ? 我如何在new_table_name上成功执行此更改? Thanks for the help! 谢谢您的帮助!

Use the format specifier %L for a literal: 将格式说明符%L用作文字:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM