msa*_*a25 7 sql database postgresql foreign-keys
我怎么能放弃Foreign keys一般.我的意思是,如果我在表中有很多外键约束.喜欢
MonthlyEvaluatedBudgetTable Contraints:
在postgres中是否有一种方法可以放弃所有外键,而不是特定地放在现有表中?我使用这行代码删除现有表中的外键.
ALTER TABLE "public"."monthlyevaluatedbudgettable"
DROP CONSTRAINT "accountid_fk";
Run Code Online (Sandbox Code Playgroud)
但我想放弃它没有专门输入查询accountid_fk,branchid_fk,dept_fk.有没有办法呢?提前致谢.
Vao*_*sun 13
将其循环到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
Run Code Online (Sandbox Code Playgroud)
小智 5
感谢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
Run Code Online (Sandbox Code Playgroud)