I'm using PostgreSQL. I have two tables, table_a
and table_b
. table_b
is a structural copy of table_a
but it was created without the constraints of table_a
. At a later date, I want to add the constraints to table_b
.
All the constraints are regular foreign keys to the primary key of table_a
and for the purposes of this question, we can assume that the data are the same in both tables, but I still don't want to drop and recreate table_b
; I want to add the constraints independent of table creation.
Is there a generic way of doing this without having to be provided details of the tables' structure or the specific constraints of table_a
?
Best Answer
You can use
information_schema
view to get information about FOREIGN KEYS in this way:You can dynamically build SQL statements to add FOREIGN KEYS.
Copy&Paste and EXECUTE or use a function like this SO answer to execute.
dbfiddle here