MySQL-存储过程OUT变量返回null [英] Mysql - Stored procedure OUT variable return null
问题描述
我的表结构是:
DROP TABLE IF EXISTS `child`;
CREATE TABLE `child` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `map_parent_child`;
CREATE TABLE `map_parent_child` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`parent_id` int(11) NOT NULL,
`child_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_parent_child` (`parent_id`,`child_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `parent`;
CREATE TABLE `parent` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
我已经创建了一个存储过程,例如
I have create a stored procedure like
DELIMITER $$
DROP PROCEDURE IF EXISTS `test`.`sp_parent`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_parent`(
IN parent_name VARCHAR(255),
IN child_name VARCHAR(255),
OUT parent_id INT(11))
BEGIN
DECLARE parent_id INT DEFAULT 0;
DECLARE child_id INT DEFAULT 0;
START TRANSACTION;
INSERT INTO `parent` (`name`) VALUES(parent_name);
SET parent_id = LAST_INSERT_ID();
INSERT INTO `child` (`name`) VALUES(child_name);
SET child_id = LAST_INSERT_ID();
INSERT INTO `map_parent_child` (`parent_id`,`child_id`) VALUES(parent_id,child_id);
commit;
END$$
DELIMITER ;
CALL sp_parent("test", "test", @parentid);
但是当我尝试使用select来获取输出变量时,我会得到NULL,但是所有INSERT语句都可以正常工作并将记录添加到数据库表中.
But when i try to fetch output variable using select then i get NULL however all INSERT statement work fine and adding record into the database table.
SELECT @parentid;
我在这里想念什么?
推荐答案
您可能已经解决了这个问题,但是我注意到存储过程的第一件事是您有一个与输出同名的局部变量变量(parent_id
).在我看来,您是在设置局部变量的值,而不是返回变量的值,因此调用方永远不会看到正确的值.
You might have already solved this by now, but the first thing I noticed about your stored procedure is that you have a local variable with the same name as the output variable (parent_id
). It looks to me that you're setting the value of the local variable rather than the return variable, so the caller never sees the correct value.
也许删除局部parent_id
变量声明将解决您的问题.
Perhaps removing the local parent_id
variable declaration will solve your problem.
这篇关于MySQL-存储过程OUT变量返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!