如何仅在外键不存在时添加外键

时间:2014-11-07 15:20:28

标签: sql postgresql foreign-keys

PostgreSQL数据库升级脚本使用命令添加外键约束:

update omrid set tellkanne=null where tellkanne =0 or tellkanne not in (select dokumnr from dok);

alter table omrid ADD constraint omrid_tellkanne_fkey  FOREIGN KEY (tellkanne)
 REFERENCES dok(dokumnr) ON UPDATE CASCADE on delete set null DEFERRABLE

dokumnr是具有serial类型的点表主键。 这两个字段都是int类型

如果在报告错误之前已经添加了外键,则需要很长时间。 仅当外键omrid_tellkanne_fkey不存在时如何运行这些命令?

1 个答案:

答案 0 :(得分:0)

您可以查询其中一个information_schema视图,以查看该名称的约束是否存在。

select constraint_name 
from information_schema.referential_constraints
where constraint_name = 'omrid_tellkanne_fkey';

这是否可靠地依赖于应用程序。虽然这个可靠地告诉你是否有一个名为&#; omrid_tellkanne_fkey'的外键约束。存在,它不会告诉您该约束是否是您对感兴趣的表之间的外键约束。您需要从information_schema视图中加入一个或两个表来获取它。

更通用的查询可能如下所示。

select k.table_catalog || '.' ||
       k.table_schema || '.' ||
       k.table_name referencing_table,
       r.constraint_name,
       c.table_catalog || '.' ||
       c.table_schema || '.' ||
       c.table_name referenced_table
from information_schema.referential_constraints r
inner join information_schema.key_column_usage k
  on r.constraint_catalog = k.constraint_catalog
  and r.constraint_schema = k.constraint_schema
  and r.constraint_name = k.constraint_name
inner join information_schema.constraint_column_usage c
  on r.constraint_catalog = c.constraint_catalog
  and r.constraint_schema = c.constraint_schema
  and r.constraint_name = c.constraint_name
-- Change this WHERE clause to match your object names. 
where r.constraint_catalog = 'your_database'
  and r.constraint_schema = 'your_schema'
  and r.constraint_name = 'omrid_tellkanne_fkey'
  and k.table_name = 'omrid'
  and c.table_name = 'dok';