我有一个SQL脚本,我需要转换为参数化存储过程。我过去只写过简单的函数,而不是带参数的复杂事务查询。
非常感谢任何帮助 - 以下简化查询。这个脚本实际上可以是包含事务和一些用户输入的任何内容。
-- 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;
我开始了,但后来我几乎陷入困境。我特别关注确保错误,如果发生错误,以某种方式使调用代码可见
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 ;
答案 0 :(得分:3)
花了大量的研究,试验和错误,但我认为我找到了一个很好的解决方案。
DELIMITER //
CREATE PROCEDURE my_procedure (IN parent_id int, IN identifier varchar(255), OUT out_user_id int)
BEGIN
-- local variable, set later after user is created
DECLARE user_id int;
-- rollback transaction and bubble up errors if something bad happens
DECLARE exit handler FOR SQLEXCEPTION, SQLWARNING
BEGIN
ROLLBACK;
RESIGNAL;
END;
START TRANSACTION;
-- 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
SELECT user_id INTO out_user_id;
END //
DELIMITER ;
我可以像这样使用它
-- run the procedure
CALL my_procedure(123, 'some_id', @user_id);
-- get the "return" value
SELECT @user_id as user_id;
这绝对是我写过的最复杂的存储过程。如果有人看到需要改进的地方,我会很高兴知道如何让它变得更好。