Trying to Run a stored procedure in mySQL and it fails on a foreign key constraint

1.6k Views Asked by At

I wrote a simple Stored Procedure with a while loop that's not working. Here's some data for you: the parent table is data_client_id. The tables are all innoDB. The primary key is ID. All other tables in the schema with the data_ prefix have this (data_client_id.id) column as a foreign key. I generated some dummy data and inserted it into the data_client_id table which auto-increments the primary key. The rows generated were 33 through 132. My intention was to write one stored procedure that would create rows with matching values in the id column for all of the other data_ tables.

Here is my code:

mysql> DELIMITER //
mysql> CREATE PROCEDURE this()
    -> BEGIN
    -> DECLARE v1 INT;
    -> SET v1 = 33;
    -> WHILE v1 < 132 DO
    -> INSERT INTO data_banking (id) VALUES(v1);
    -> SET v1 = v1+1;
    -> END WHILE;
    -> END//
Query OK, 0 rows affected (0.00 sec)

Then when I CALL the this(); Procedure I get the following error:

mysql> call this();
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails             (`oms_clients`.`data_banking`, CONSTRAINT `data_banking_FK` FOREIGN KEY (`id`) REFERENCES  `data_client_id` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)

I tried just running standalone INSERTs into the data_ tables like this: INSERT into data_banking (id) VALUES (34);

and it worked setting all the columns with defaults to NULL or their respective SET defaults...

1

There are 1 best solutions below

1
On BEST ANSWER

There's nothing wrong with your stored procedure.

The problem is that you can't insert a run into data_banking unless the SAME id also exists in data_client_id. Each id, 33 through 132.

To fix the problem, remove the constraint, or make sure the foreign key dependency is resolved.

Here's a good link with some useful tips:

Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails