I need to construct a single transaction / stored procedure that takes in two lists of foreign keys and inserts new rows into a table from those foreign keys.
Specifically, I have a table that has order_ids and item_ids corresponding to the order. I need to add to this table when orders are submitted.
To summarize in code, I would like to do:
DELIMITER ##
BEGIN
CREATE STORED PROCEDURE addOrder(IN itemIds VARCHAR(255), IN orderIds VARCHAR(255))
// ----- SQL Equivalent of -----
// for (int i = 0; i < itemIds.length; ++i)
// INSERT INTO Items_Ordered(item_id, order_id) VALUES(itemIds[i], order_ids[i]);
// -----------------------------
END ##
DELIMITER ;
So in Java, I could then just do something like:
String listOfItems = '1, 2, 6, 7, 8';
String listOfOrders = '2, 1, 99, 82, 7';
PreparedStatement ps = connection.prepareCall("CALL addOrder(" + listOfItems + ", " + listOfOrders + ")");
ps.executeUpdate();
Any ideas?
EDIT #1:
I really, really, really don’t like this hacky solution: Pass array into a stored procedure
EDIT #2:
Another solution I was thinking was to create a temporary table in the stored procedure with the input, but I don’t know how to do that either.
Create a string split function along these lines:
http://kedar.nitty-witty.com/blog/mysql-stored-procedure-split-delimited-string-into-rows
Then you can split your comma separated string into discreet values for insertion.