Question

I'm using MySQL 5.5.37. Given a group of tables, (table_a, table_b, ..., table_n), how do I write an SQL statement (or procedure) that will generate the SQL that produces all the foreign keys that these tables link to? Note that although I can run a mysqldump that will produce "CREATE TABLE" statements with "CONSTRAINT" clauses, I want ONLY the statmeents that will add the foreign keys, e.g.

ALTER TABLE table_a ADD FOREIGN KEY (P_Id) REFERENCES table_x(P_Id)

Thanks, - Dave

Was it helpful?

Solution

SELECT CONCAT('ALTER TABLE ', table_name,
              ' ADD FOREIGN KEY (', constraint_name, ')',
              ' REFERENCES ', referenced_table_name,
              '(', referenced_column_name, ');') AS alter_cmd
FROM information_schema.key_column_usage
WHERE referenced_table_name IS NOT NULL;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top