If you want to add/drop foreign key then you need to check is foreign key is exist or not.
IF NOT EXISTS (SELECT NULL FROM information_schema.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = DATABASE() AND CONSTRAINT_NAME = 'fk_rabbits_main_page' AND CONSTRAINT_TYPE = 'FOREIGN KEY') THEN ALTER TABLE `rabbits` ADD CONSTRAINT `fk_rabbits_main_page` FOREIGN KEY (`main_page_id`) REFERENCES `rabbit_pages` (`id`); END IF
Using following query you will get more information about foreign key with column details.
SELECT TABLE_NAME,COLUMN_NAME, CONSTRAINT_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME='TABLENAME' AND REFERENCED_TABLE_NAME = 'REFERENCED_TABLE_NAME' AND CONSTRAINT_NAME='FK_Key_Name' AND REFERENCED_COLUMN_NAME='Code';
No comments:
Post a Comment