gpt4 book ai didi

sql - 通过仅了解模式和表名来删除 postgresql 中的主键约束

转载 作者:行者123 更新时间:2023-11-29 11:37:44 25 4
gpt4 key购买 nike

据我所知,在 postgresql 中删除主键的唯一方法是:

ALTER TABLE schema.tableName DROP CONSTRAINT constraint_name;

约束名称默认为tableName_pkey。但是有时如果表已经重命名,我无法获取原始表名来构造正确的约束名称。

例如,对于创建为 A 然后重命名为 B 的表,约束仍然是 A_pkey 但我只有表名 B.

您是否知道通过只知道模式名称和表名称来删除 pkey 约束的正确方法?

我正在为此编写程序,因此我只需要使用 SQL 查询。 “打开 pgAdmin 并查看约束名称”之类的解决方案将不起作用。

最佳答案

您可以像这样使用目录表中的信息:

创建一个id为主键的表

create table test1 (id int primary key, name text);

创建 SQL 以删除 key

select concat('alter table public.test1 drop constraint ', constraint_name) as my_query
from information_schema.table_constraints
where table_schema = 'public'
and table_name = 'test1'
and constraint_type = 'PRIMARY KEY';

结果将是:

alter table public.test1 drop constraint test1_pkey

您可以创建一个存储函数来提取此查询,然后执行

关于sql - 通过仅了解模式和表名来删除 postgresql 中的主键约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47962406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com