Drop foreign keys generally in POSTGRES

前端 未结 2 603
长发绾君心
长发绾君心 2021-01-11 15:45

How can I drop Foreign keys in general. I mean, if I have many foreign key constraints in a table. like

MonthlyEvaluatedBudgetTable Contraints:

2条回答
  •  甜味超标
    2021-01-11 16:42

    Thank you Vao Tsun for the solution. It helped me.

    In my case (Posgresql 9.6) I just had to add a minor "improvement"

    and constraint_name like 'fk_%' additional constraint to prevent errors like:

    PG::SyntaxError: ERROR:  syntax error at or near "2200" LINE 1: ALTER TABLE "relationships" 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
    

提交回复
热议问题