I have the exact same code running on two different servers:
Truncate table2;
Truncate table1;
Both table structures are exactly the same in both servers, table2 has a foreign key referencing table1.
Since table2 was truncated before table1, it is empty and there are no keys pointing to table1, so truncating table2 shouldn't be a problem. But!!!:
In one server it works perfectly well and on the other I get a foreign key constraint error:
Cannot truncate a table referenced in a foreign key constraint (user`.`table2`,
CONSTRAINT `table2_ibfk_1` FOREIGN KEY (`ID`) REFERENCES `user`.`table1` (`ID`))
I can understand from this that there must be a setting that can be changed in order to always allow to truncate empty tables. If not server one should give me the same error.
I know I can use delete instead but it is a longer process and auto_increment needs to be reset in that case.
I just want to understand why server 1 has no error and server 2 does.
Any ideas?
Thanks.
SET FOREIGN_KEY_CHECKS=0; TRUNCATE table1; SET FOREIGN_KEY_CHECKS=1;
Related
I tried every thing to truncate a table, but I always have the same message :
Cannot delete or update a parent row: a foreign key constraint fails (`mybdd`.`c_member`, CONSTRAINT `fk_cm_c_id` FOREIGN KEY (`c_id`) REFERENCES `comment` (`c_id`))
Looking some posts on this site I tried this :
ALTER TABLE comment
ADD CONSTRAINT c_member FOREIGN KEY (c_id)
REFERENCES comment (c_id);
But it doens't work :
Can't create table 'mybdd.#sql-2ee0_3769864' (errno: 150){"success":false,"error":"
1005 - Can't create table 'sameditrbdd.#sql-2ee0_3769864' (errno: 150)</div>"}
How can I do that ?
You need to delete all references to the table, including all foreign key constraints and indexes, before you can drop a table.
Foreign key constraints can also prevent you from deleting specific rows.
Alternatively, you can turn off foreign key checks, but then setting them back on again will likely result in errors or unpredictable behavior (because your constraints are violated by the data in the data base).
You can use:
SET foreign_key_checks = 0;
DROP <your_table>
SET foreign_key_checks = 1;
Very likely some people or their process holding your table hostage!!!
You should try to kill them addressing them by their spid #!
To see who is holding your table hostage, you open up your query analyser to run
execute sp_who2 'active' -- under the database of interest
Then, make your own judgment whether it is OK to kill them or not, or call those who logged in.
To kill, just do
kill 999 -- your spid # found in that table returned by above command
After that, try to truncate or drop again!
Best luck!!!
Hi i am using sql server 2008 r2,
i have a genuine problem.
i have a Table A and Table B,
where i have a column IID in table A as a primary key constraint.
and the same column i.e. IID in table B as a foreign key constraint.
i have a situation where i wanted to truncate the table A. while running query Truncate table A it give me following error.
Msg 4712, Level 16, State 1, Line 1
Cannot truncate table 'A' because it is being referenced by
a FOREIGN KEY constraint.
my problem i cant do any DML & DDL operation on table B.
how can i truncate table A ?
Thanks! in advanced.
The only way to allow a truncate is to drop the foreign key constraint(s) against table A. It doesn't matter if the constraint is disabled or if both tables are empty, SQL Server still will not allow it. So if you have the definition of the foreign key handy, you could do:
ALTER TABLE dbo.TableB DROP CONSTRAINT FK_whatever;
TRUNCATE TABLE dbo.TableA;
ALTER TABLE dbo.TableB ADD CONSTRAINT FK_Whatever
FOREIGN KEY ...;
Otherwise as #Damien says the solution to your "genuine problem" is to use DELETE instead of TRUNCATE. If you also were using TRUNCATE to reset the IDENTITY column, you can perform a DELETE and then a DBCC CHECKIDENT('dbo.TableA', RESEED, 1);...
If you can't do anything against Table B, then you're going to have to let SQL Server validate that its not removing rows which are referenced by Table B.
So, it's nice, slow, logged DELETE FROM A.
In MySQL I want to drop a table.
I tried a lot things but I keep getting the error that the table named bericht can't be dropped. This is the error I'm getting:
#1217 - Cannot delete or update a parent row: a foreign key constraint fails
How do I drop this table?
This should do the trick:
SET FOREIGN_KEY_CHECKS=0; DROP TABLE bericht; SET FOREIGN_KEY_CHECKS=1;
As others point out, this is almost never what you want, even though it's whats asked in the question. A more safe solution is to delete the tables depending on bericht before deleting bericht. See CloudyMarble answer on how to do that. I use bash and the method in my post to drop all tables in a database when I don't want to or can't delete and recreate the database itself.
The #1217 error happens when other tables has foreign key constraints to the table you are trying to delete and you are using the InnoDB database engine. This solution temporarily disables checking the restraints and then re-enables them. Read the documentation for more. Be sure to delete foreign key restraints and fields in tables depending on bericht, otherwise you might leave your database in a broken state.
Try this:
SELECT *
FROM information_schema.KEY_COLUMN_USAGE
WHERE REFERENCED_TABLE_NAME = 'YourTable';
This should deliver you which Tables have references to the table you want to drop, once you drop these references, or the datasets which reference datasets in this table you will be able to drop the table
But fortunately, with the MySQL FOREIGN_KEY_CHECKS variable, you don't have to worry about the order of your DROP TABLE statements at all, and you can write them in any order you like -- even the exact opposite -- like this:
SET FOREIGN_KEY_CHECKS = 0;
drop table if exists customers;
drop table if exists orders;
drop table if exists order_details;
SET FOREIGN_KEY_CHECKS = 1;
For more clarification, check out the link below:
http://alvinalexander.com/blog/post/mysql/drop-mysql-tables-in-any-order-foreign-keys/
Use show create table tbl_name to view the foreign keys
You can use this syntax to drop a foreign key:
ALTER TABLE tbl_name DROP FOREIGN KEY fk_symbol
There's also more information here (see Frank Vanderhallen post):
http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
This probably has the same table to other schema the reason why you're getting that error.
You need to drop first the child row then the parent row.
I realize this is stale for a while and an answer had been selected, but how about the alternative to allow the foreign key to be NULL and then choose ON DELETE SET NULL.
Basically, your table should be changed like so:
ALTER TABLE 'bericht'
DROP FOREIGN KEY 'your_foreign_key';
ALTER TABLE 'bericht'
ADD CONSTRAINT 'your_foreign_key' FOREIGN KEY ('column_foreign_key') REFERENCES 'other_table' ('column_parent_key') ON UPDATE CASCADE ON DELETE SET NULL;
Personally I would recommend using both "ON UPDATE CASCADE" as well as "ON DELETE SET NULL" to avoid unnecessary complications, however your set up may dictate a different approach.
Hope this helps.
I get this error message:
ERROR 1217 (23000) at line 40: Cannot
delete or update a parent row: a
foreign key constraint fails
... when I try to drop a table:
DROP TABLE IF EXISTS `area`;
... defined like this:
CREATE TABLE `area` (
`area_id` char(3) COLLATE utf8_spanish_ci NOT NULL,
`nombre_area` varchar(30) COLLATE utf8_spanish_ci NOT NULL,
`descripcion_area` varchar(100) COLLATE utf8_spanish_ci NOT NULL,
PRIMARY KEY (`area_id`),
UNIQUE KEY `nombre_area_UNIQUE` (`nombre_area`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
The funny thing is that I already dropped all other tables in the schema that have foreign keys against area. Actually, the database is empty except for the area table.
How can it possibly have child rows if there isn't any other object in the database? As far as I know, InnoDB doesn't allow foreign keys on other schemas, does it?
(I can even run a RENAME TABLE area TO something_else command :-?)
On demand, now as an answer...
When using MySQL Query Browser or phpMyAdmin, it appears that a new connection is opened for each query (bugs.mysql.com/bug.php?id=8280), making it neccessary to write all the drop statements in one query, eg.
SET FOREIGN_KEY_CHECKS=0;
DROP TABLE my_first_table_to_drop;
DROP TABLE my_second_table_to_drop;
SET FOREIGN_KEY_CHECKS=1;
Where the SET FOREIGN_KEY_CHECKS=1 serves as an extra security measure...
Two possibilities:
There is a table within another schema ("database" in mysql terminology) which has a FK reference
The innodb internal data dictionary is out of sync with the mysql one.
You can see which table it was (one of them, anyway) by doing a "SHOW ENGINE INNODB STATUS" after the drop fails.
If it turns out to be the latter case, I'd dump and restore the whole server if you can.
MySQL 5.1 and above will give you the name of the table with the FK in the error message.
Disable foreign key checking
SET FOREIGN_KEY_CHECKS=0
from this blog:
You can temporarily disable foreign key checks:
SET FOREIGN_KEY_CHECKS=0;
Just be sure to restore them once you’re done messing around:
SET FOREIGN_KEY_CHECKS=1;
hopefully its work
SET foreign_key_checks = 0;
DROP TABLE table name;
SET foreign_key_checks = 1;
On Rails, one can do the following using the rails console:
connection = ActiveRecord::Base.connection
connection.execute("SET FOREIGN_KEY_CHECKS=0;")
Maybe you received an error when working with this table before. You can rename the table and try to remove it again.
ALTER TABLE `area` RENAME TO `area2`;
DROP TABLE IF EXISTS `area2`;
i found an easy solution, export the database, edit it what you want to edit in a text editor, then import it. Done
Cannot delete or update a parent row: a foreign key constraint fails (table1.user_role, CONSTRAINT FK143BF46A8dsfsfds##5A6BD60 FOREIGN KEY (user_id) REFERENCES user (id))
What i did in two simple steps . first i delete the child row in child table like
mysql> delete from table2 where role_id = 2 && user_id =20;
Query OK, 1 row affected (0.10 sec)
and second step as deleting the parent
delete from table1 where id = 20;
Query OK, 1 row affected (0.12 sec)
By this i solve the Problem which means Delete Child then Delete parent
i Hope You got it. :)
If I have table B with foreign key references to table A (set to ON UPDATE CASCADE) and I run a
LOAD DATA INFILE file.txt REPLACE INTO TABLE A;
command, will the references update properly?
Please note that I'm not talking about ON DELETE CASCADE; I know a REPLACE command will delete records in table B if I have that set.
MySQL doesn't fire the update event as a result of a replace query, only the delete. Here's why:
REPLACE works exactly like INSERT,
except that if an old row in the table
has the same value as a new row for a
PRIMARY KEY or a UNIQUE index, the
old row is deleted before the new row
is inserted.
(From the MySQL 5.0 Reference Manual)
I have a foreign key set with ON UPDATE CASCADE ON DELETE SET NULL, and whenever I do a REPLACE to the foreign table's primary key, the foreign key in my related table gets set to NULL.
I actually got here after searching for a similar answer. It looks like REPLACE INTO still deletes items as long as you have ON DELETE CASCADE set for your constraint.
See http://www.mysqlperformanceblog.com/2007/01/18/insert-on-duplicate-key-update-and-replace-into/