Modifying a column to not null causes a foreign key error

[expired user #10302]'s profile image [expired user #10302] posted 7 years ago in General Permalink

Using mysql 5.5 and 5.6 with heidisql 9.4.0.5125 : I have 2 tables (operation and service_site) with a foreign key constraint between operation.service_site_id and service_site.id, currently, operation.service_site_id has null value allowed. When I uncheck the NULL allowed column and save, it generates this script :

ALTER TABLE `operation`
    ALTER `service_site_id` DROP DEFAULT;
ALTER TABLE `operation`
    CHANGE COLUMN `service_site_id` `service_site_id` INT(10) UNSIGNED NOT NULL COMMENT 'the comment' AFTER `service_id`;

Which causes this error : SQL error (1832) : Cannot change column 'service_site_id': used in a foreign key constraint 'operation_service_site_id'

Seems like we have to drop then recreate the foreign key, this is what we wrote to get the job done :

ALTER TABLE `operation`
    DROP FOREIGN KEY `operation_service_site_id`,
    ALTER `service_site_id` DROP DEFAULT;
ALTER TABLE `operation`
    CHANGE COLUMN `service_site_id` `service_site_id` INT(10) UNSIGNED NOT NULL COMMENT 'the comment' AFTER `service_id`,
    ADD CONSTRAINT `operation_service_site_id` FOREIGN KEY (`service_site_id`) REFERENCES `service_site` (`id`) ON UPDATE NO ACTION ON DELETE NO ACTION;

So, we added the drop of the foreign key in the first generated query and recreated it in the second one, that's all. It would be great if heidisql did it when we set columns not null.

Please login to leave a reply, or register at first.