navid
navid

Reputation: 823

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:

MySQL said: #1327 - Undeclared variable: 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 :(

Upvotes: 0

Views: 5308

Answers (2)

Devart
Devart

Reputation: 122032

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.

Upvotes: 1

Suresh Kamrushi
Suresh Kamrushi

Reputation: 16086

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

Upvotes: 0

Related Questions