【问题标题】:Drop foreign keys generally in POSTGRES通常在 POSTGRES 中删除外键
【发布时间】:2017-04-06 22:02:07
【问题描述】:

我一般如何删除Foreign keys。我的意思是,如果我在一个表中有很多外键约束。喜欢

MonthlyEvaluatedBudgetTable 约束:

  • budgetid_pk(主键)
  • branchid_fk(外键)
  • accountid_fk(外键)
  • dept_fk(外键)

postgres 中是否有一种方法可以删除所有外键,而不是专门删除现有表中的所有外键? 我使用这行代码在现有表中删除外键。

    ALTER TABLE "public"."monthlyevaluatedbudgettable"
    DROP CONSTRAINT "accountid_fk";

但我想删除它而不专门输入accountid_fk,branchid_fk,dept_fk。有办法吗?提前致谢。

【问题讨论】:

标签: sql database postgresql foreign-keys


【解决方案1】:

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

【讨论】:

  • 请注意,您不会只删除外键。此代码将删除所有主键约束,唯一键约束。如果你想过滤外键,你可以在查询中添加 constraint_type ='FOREIGN KEY'。
【解决方案2】:

感谢Vao Tsun 的解决方案。它帮助了我。

在我的情况下(Posgresql 9.6)我只需要添加一个小的“改进”

and constraint_name like 'fk_%' 附加约束以防止出现以下错误:

PG::SyntaxError: 错误:“2200”处或附近的语法错误 第 1 行:ALTER TABLE “关系” DROP CONSTRAINT 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

【讨论】:

    猜你喜欢
    • 2014-02-09
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-10
    • 1970-01-01
    • 2010-11-05
    • 1970-01-01
    相关资源
    最近更新 更多