2016-11-23 6 views
1

一般的にはForeign keysをドロップできますか?テーブルに多くの外部キー制約があるとすれば、私は意味します。以下のような一般的にポストグルズの外部キーをドロップ

MonthlyEvaluatedBudgetTable Contraints:

  • budgetid_pk(主キー)
  • branchid_fk(外部キー)
  • accountid_fk(外部キー)
  • dept_fk(外部キー)

はですポストグルには、一般的にすべての外部キーを落とす方法があり、特に既存のテーブルにはありません。 このコード行を使用して、既存のテーブルに外部キーをドロップします。

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

しかし、私は、具体的accountid_fkbranchid_fkdept_fkを入力環境せずにそれをドロップします。それに道があるの?前もって感謝します。以下のようなDO文の

+3

:私の場合(Posgresql 9.6)で

は私だけのようなエラーを防ぐために、マイナーな "改善"

and constraint_name like 'fk_%'追加の制約を追加する必要がありましたか?いずれかの方法。それは簡単です。まず、すべての外部キー(http://stackoverflow.com/questions/1152260/postgres-sql-to-list-table-foreign-keys)を見つける必要があります。それから、それらを削除する必要があります。 – AlexM

答えて

3

ループそれ、:

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 
0

は解決のためにあなたVao Tsunをありがとうございます。それは私を助けた。何のために

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 
関連する問題