Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 一般在POSTGRES中删除外键_Sql_Database_Postgresql_Foreign Keys - Fatal编程技术网

Sql 一般在POSTGRES中删除外键

Sql 一般在POSTGRES中删除外键,sql,database,postgresql,foreign-keys,Sql,Database,Postgresql,Foreign Keys,一般情况下,如何删除外键。我的意思是,如果表中有许多外键约束。像 每月评估的可编入预算的合同: budgetid_主键(主键) branchid_fk(外键) accountid_fk(外键) 部门fk(外键) 在postgres中是否有一种方法可以删除现有表中的所有外键? 我正在使用这行代码在现有表中删除外键 ALTER TABLE "public"."monthlyevaluatedbudgettable" DROP CONSTRAINT "accountid_fk";

一般情况下,如何删除
外键
。我的意思是,如果表中有许多外键约束。像

每月评估的可编入预算的合同:

  • budgetid_主键(主键)
  • branchid_fk(外键)
  • accountid_fk(外键)
  • 部门fk(外键)
在postgres中是否有一种方法可以删除现有表中的所有外键? 我正在使用这行代码在现有表中删除外键

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

但是我不想特别输入
accountid\u fk
branchid\u fk
dept\u fk
,我想删除它。有办法吗?提前感谢。

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
谢谢你的解决方案。它帮助了我

在我的例子(POSGRESQL9.6)中,我只需要添加一个小的“改进”

和约束\u名称,如“fk%”
防止错误的附加约束,如:

PG::SyntaxError:ERROR:位于或接近“2200”的语法错误 第1行:更改表格“关系”删除约束2200_856906_1_编号


执行什么?无论如何。很简单。首先需要找到所有外键(),然后需要删除它们。
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