Why doesn't a TRUNCATE on mygroup
work? Even though I have ON DELETE CASCADE SET
I get:
ERROR 1701 (42000): Cannot truncate a table referenced in a foreign key constraint (
mytest
.instance
, CONSTRAINTinstance_ibfk_1
FOREIGN KEY (GroupID
) REFERENCESmytest
.mygroup
(ID
))
drop database mytest; create database mytest; use mytest; CREATE TABLE mygroup ( ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY ) ENGINE=InnoDB; CREATE TABLE instance ( ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, GroupID INT NOT NULL, DateTime DATETIME DEFAULT NULL, FOREIGN KEY (GroupID) REFERENCES mygroup(ID) ON DELETE CASCADE, UNIQUE(GroupID) ) ENGINE=InnoDB;
You can't truncate a table that has a foreign key constraint, that is the whole reason for having a constraint. You will need to delete and re-create the constraints so make sure you script them out before deleting them.
You cannot truncate a table that has foreign key constraints.
Truncate also has the ability to reset the seed to its initial value. On delete triggers are also not fired and all foreign keys constraint must be removed or disabled. Instead of removing all constraints, it is possible to tell SQL Server to not check foreign key.
Yes you can:
SET FOREIGN_KEY_CHECKS = 0; TRUNCATE table1; TRUNCATE table2; SET FOREIGN_KEY_CHECKS = 1;
With these statements, you risk letting in rows into your tables that do not adhere to the FOREIGN KEY
constraints.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With