简体   繁体   English

MySQL存储过程动态选择带变量

[英]Mysql stored procedure dynamic select with out variable

When I didn't use out variable, the stored procedure worked correctly, but when I execute the stored procedure with out variable, this error shows up: 当我不使用out变量时,存储过程可以正常工作,但是当我使用out变量执行存储过程时,将显示此错误:

MySQL said: #1327 - Undeclared variable: sp_result MySQL说:#1327-未声明的变量:sp_result

Code: 码:

CREATE DEFINER=`root`@`localhost` PROCEDURE `test3`(OUT `sp_result` INT(11), IN `sp_where_param` VARCHAR(100), IN `sp_where_value` VARCHAR(100), IN `sp_table_name` VARCHAR(100))
NO SQL
BEGIN
DECLARE tbl_id VARCHAR(100);

SET tbl_id = CONCAT(sp_table_name,'_id');

SET @temp1=CONCAT('SELECT count(',tbl_id,') INTO sp_result FROM ',sp_table_name,' WHERE ',sp_where_param,' = \'',sp_where_value,'\'');
PREPARE stmt1 FROM @temp1;
EXECUTE stmt1;

END

Maybe without out variable also doesn't work :( 也许没有out变量也不起作用:(

Try to use user variable - 尝试使用用户变量-

CREATE DEFINER = 'root'@'localhost'
PROCEDURE test3 (OUT `sp_result` int(11), IN `sp_where_param` varchar(100), IN `sp_where_value` varchar(100), IN `sp_table_name` varchar(100))
NO SQL
BEGIN
  DECLARE tbl_id varchar(100);

  SET tbl_id = CONCAT(sp_table_name, '_id');

  SET @temp1 = CONCAT('SELECT COUNT(', tbl_id, ') INTO @sp_result FROM ', sp_table_name, ' WHERE ', sp_where_param, ' = \'', sp_where_value, '\'');

  PREPARE stmt1 FROM @temp1;
  EXECUTE stmt1;
  DEALLOCATE PREPARE stmt1;

  set sp_result = @sp_result;

END

...and add DEALLOCATE PREPARE statement. ...并添加DEALLOCATE PREPARE语句。

it should be- 它应该是-

SET tbl_id = CONCAT(sp_table_name,'_id');
SET @temp1=CONCAT('SELECT count(',tbl_id,') INTO

like this 像这样

SET @tbl_id:= CONCAT(sp_table_name,'_id');
SET @temp1:=CONCAT('SELECT count(',tbl_id,') INTO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM