I’m writing a procedure in MySQL that reads entries from a view, and inserts rows into another table depending on various conditions. In this context, I have up to 4 possible size_id variables, named my_size_1, my_size_2, my_size_3 and my_size_4. If they do not have a value, they are NULL. Writing the following expression in my stored proc results in a SQL error:
-- Insert recommendation options --
INSERT INTO `size_recommendation_options`
VALUES (my_size_recommendation_id, my_size_1);
IF my_size_2 IS NOT NULL THEN
INSERT INTO `size_recommendation_options`
VALUES (my_size_recommendation_id, my_size_2);
END;
IF my_size_3 IS NOT NULL THEN
INSERT INTO `size_recommendation_options`
VALUES (my_size_recommendation_id, my_size_3);
END;
IF my_size_4 IS NOT NULL THEN
INSERT INTO `size_recommendation_options`
VALUES (my_size_recommendation_id, my_size_4);
END;
…however, removing the IF statements fixes the error. That is, the following will run just fine:
-- Insert recommendation options --
INSERT INTO `size_recommendation_options`
VALUES (my_size_recommendation_id, my_size_1);
INSERT INTO `size_recommendation_options`
VALUES (my_size_recommendation_id, my_size_2);
INSERT INTO `size_recommendation_options`
VALUES (my_size_recommendation_id, my_size_3);
INSERT INTO `size_recommendation_options`
VALUES (my_size_recommendation_id, my_size_4);
Why is that? This isn’t the end of the world – I can just add a DELETE FROM size_recommendation_options WHERE size_id IS NULL afterwards, but all of the unnecessary inserts slow down the stored proc considerably. Why is the first block invalid SQL?
Thanks.
IFblocks must be closed withEND IF:http://dev.mysql.com/doc/refman/5.6/en/if-statement.html
In your case: