I have a stored procedure in which I'm trying to loop over a number of IDs in a table and insert them into another table... problem is the ID turns out as NULL in the loop.
For debugging purposes I have created a table called test, it has two columns named var_name and value. I also made a stored procedure like this:
CREATE DEFINER=`root`@`localhost` PROCEDURE `myProcedure`(@parent INT(11))
BEGIN
INSERT INTO `test`
(`var_name`, `value`)
VALUES
('parent', @parent);
INSERT INTO test (`var_name`, `value`)
SELECT 'id', `id`
FROM `mytable`
WHERE `parent` = @parent;
END
The table mytable has a lot of columns but id is the primary key and obviously NOT NULL, parent allows NULL. The id, parent and value columns are all INT(11).
The following statement:
CALL myProcedure(1);
Produces the following result in test:
+----------+-------+
| var_name | value |
+----------+-------+
| 'parent' | 1 |
| 'id' | NULL |
| 'id' | NULL |
| 'id' | NULL |
| 'id' | NULL |
| 'id' | NULL |
| 'id' | NULL |
+----------+-------+
The number of 'id' rows match the number of rows in mytable with parent = 1, but value is always NULL. Running the following query:
SELECT `id` FROM `mytable` WHERE `parent` = 1;
Produces the expected result:
+----+
| id |
+----+
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
+----+
What's going on here?