据我所知,在postgresql中删除主键的唯一方法是
ALTER TABLE schema.tableName DROP CONSTRAINT constraint_name;
默认情况下,约束名称是tableName_pkey,但是有时如果表已经重命名,我就无法获得原始表名来构造右约束名.
例如,表创建为A然后重命名为B约束仍为A_pkey但我只有B.
您是否知道通过只知道模式名称和表名来删除pkey约束的正确方法?
我正在编写programm来执行此操作,因此我只需要使用SQL查询.像"打开pgAdmin并查看约束名称"这样的解决方案将无效.
zed*_*xus 12
您可以使用目录表中的信息,如下所示:
创建一个以id作为主键的表
create table test1 (id int primary key, name text);
Run Code Online (Sandbox Code Playgroud)
创建SQL以删除密钥
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';
Run Code Online (Sandbox Code Playgroud)
结果将是:
alter table public.test1 drop constraint test1_pkey
Run Code Online (Sandbox Code Playgroud)
您可以创建一个存储函数来提取此查询然后再提取execute它.
| 归档时间: |
|
| 查看次数: |
10332 次 |
| 最近记录: |