两个插入语句都成功并在表registration
和registration_header
上正确插入。我唯一的问题是,它没有通过myOutParameter
返回正确的ID。
使用@var_registrationId
SET myOutParameter = @var_registrationId
的价值
我的语法错了吗?我知道我可以使用SET
CREATE DEFINER=`root`@`localhost` PROCEDURE `register`(IN parameter1 INT, IN parameter2 INT, OUT myOutParameter INT)
BEGIN
DECLARE var_registrationId INT;
DECLARE EXIT HANDLER FOR sqlexception
BEGIN
ROLLBACK;
RESIGNAL;
END;
START TRANSACTION;
-- first insert to registration table which generates a Primary key auto increment id
INSERT INTO registration(col1,col2) VALUES (parameter1, parameter2);
SELECT LAST_INSERT_VALUE() INTO var_registrationId; -- id of insert on registration table
insert into registration_header(registrationId,column)
VALUES(@var_registrationId,parameter1);
-- the next statement is not assigning the value of var_registrationId to the myOutParameter using SET
SET myOutParameter = @var_registrationId; -- this isn't working and returns 0
COMMIT;
END
我不知道出了什么问题。
我希望你能提供帮助。
提前致谢
答案 0 :(得分:1)
架构:
create schema blahx8; -- create a new db so as not to screw yours up
use blahx8; -- use the new db
-- drop table if exists registration;
create table registration
( id int auto_increment primary key,
col1 int not null,
col2 int not null
);
-- drop table if exists registration_header;
create table registration_header
( id int auto_increment primary key,
registrationId int not null,
`column` int not null -- pretty bad column name. Use back-ticks
);
存储过程:
DROP PROCEDURE IF EXISTS `register`;
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `register`
( IN parameter1 INT,
IN parameter2 INT,
OUT myOutParameter INT
)
BEGIN
DECLARE var_registrationId INT;
DECLARE EXIT HANDLER FOR sqlexception
BEGIN
ROLLBACK;
RESIGNAL;
END;
START TRANSACTION;
-- first insert to registration table which generates a Primary key auto increment id
INSERT INTO registration(col1,col2) VALUES (parameter1, parameter2);
SELECT LAST_INSERT_ID() INTO var_registrationId; -- id of insert on registration table
insert into registration_header(registrationId,`column`)
VALUES(registrationId,parameter1);
SET myOutParameter = var_registrationId; -- This is now happy
COMMIT;
SET @still_Alive=7; -- watch this thing !! Be careful
END$$
DELIMITER ;
测试:
SET @thisThing=-1;
CALL register(7,8,@thisThing);
select @thisThing; -- 1
CALL register(7,8,@thisThing);
select @thisThing; -- 2
CALL register(7,8,@thisThing);
select @thisThing; -- 3
select @still_Alive; -- 7
-- yikes, be carefull with User Variables. They are connection-based
-- still alive out here outside of stored proc (unlike Local Vars)
清理:
drop schema blahx8; -- drop new db, poof gone
本地变量(来自DECLARE)与几乎相似的用户变量(带有@
符号)不同。
我还修复了LAST_INSERT_ID()
。