如何放弃Foreign keys
。我的意思是,如果我在表中有很多外键约束。像
MonthlyEvaluatedBudgetTable Contraints:
postgres中是否有一种方法可以放弃所有外键,而不是特定地放在现有表中? 我使用这行代码将外键放在现有表中。
ALTER TABLE "public"."monthlyevaluatedbudgettable"
DROP CONSTRAINT "accountid_fk";
但我想删除它而不是专门输入accountid_fk
,branchid_fk
,dept_fk
。有没有办法呢?提前谢谢。
答案 0 :(得分:7)
将其循环到DO
语句中,如:
b=# create table a (a int primary key, b int unique);
CREATE TABLE
b=# create table b (a int references a(a), b int references a(b));
CREATE TABLE
b=# do
$$
declare r record;
begin
for r in (select constraint_name from information_schema.table_constraints where table_schema = 'public' and table_name='b') loop
raise info '%','dropping '||r.constraint_name;
execute CONCAT('ALTER TABLE "public"."b" DROP CONSTRAINT '||r.constraint_name);
end loop;
end;
$$
;
INFO: dropping b_a_fkey
INFO: dropping b_b_fkey
DO
答案 1 :(得分:2)
感谢Vao Tsun提供解决方案。它帮助了我。
在我的情况下(Posgresql 9.6)我只需要添加一个小的“改进”
and constraint_name like 'fk_%'
附加约束以防止错误,如:
PG ::语法错误:错误:语法错误处或附近 “2200” 行1:ALTER TABLE “关系” DROP约束2200_856906_1_no ...
execute <<-SQL.squish
DO $$
declare r record;
begin
for r in (
select constraint_name
from information_schema.table_constraints
where table_name='relationships'
and constraint_name like 'fk_%'
) loop
raise info '%','dropping '||r.constraint_name;
execute CONCAT('ALTER TABLE "relationships" DROP CONSTRAINT '||r.constraint_name);
end loop;
end;
$$
SQL