0

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 :(

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

you're right :) .can you tell me what's user variable ? what's different when we use @ ?
There are: user variables - which are accessible in a session, declared variables - which are declared with a DECLARE command and accessible in BEGIN...END clause, and procedure/function parameters - which can be used in procedure/function only. It seems that parameters cannot be used in prepared statements; so, I suggested user variable.
Great but how to set the type of a user variable? In my tests floats are being rounded to int values using this code.
0

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

1 Comment

i do everything you said but still doesn't work.ERROR : MySQL said: #1327 - Undeclared variable: sp_result

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.