I have an SQL script that I need to convert to a parameterized stored procedure. I've only written simple functions in the past, never a complex transactional query with parameters.
Any help is greatly appreciated - simplified queries below. This script could really be anything containing a transaction and some user inputs.
-- transaction ensures i can clean up a mess, if one happens
begin;
-- parameters for the script; currently set manually before execution
set @parent_id := 123;
set @identifier := 'someid';
-- insert some row with user-specified values
insert into users (field1, field2) values (@parent_id, @identifier);
-- get the new id
set @user_id := last_insert_id();
-- do another insert
insert into usersmeta (user_id, field1, field2) values (@user_id, 1, 2);
-- if no errors happened yet, commit transaction
commit;
-- "return value"; some select query (could be 1 or many rows)
select users.id userid, usersmeta metaid
from users
join usersmeta on usersmeta.user_id = users.id;
I started with but then I pretty much got stuck. I'm especially concerned with ensuring errors, in the event they occur, are somehow made visible to the calling code
delimiter ;;
CREATE PROCEDURE mytask(IN parent_id INT(11), IN identifier VARCHAR(200))
BEGIN
SET @query = ???
PREPARE q FROM @query;
EXECUTE q;
DEALLOCATE PREPARE q;
END;;
delimiter ;