Question

I have tried with following code. But it shows error msg like this undeclared variable :nt.

CREATE DEFINER=`root`@`localhost` PROCEDURE `get_ntime`(in tb varchar(50),in d int, out nt varchar(50))
BEGIN
   SET @statment = concat('Select ntime into nt from ',tb);
   SET @date = CONCAT(' WHERE date = "', d, '"');
   SET @statmen = CONCAT(@statment, @date);
   PREPARE stmt FROM @statment;
   EXECUTE stmt;
   DEALLOCATE PREPARE stmt;
END
Was it helpful?

Solution

When used within single quotes nt will not be treated as variable but a literal.
Use local variable to set value into and assign the same to out param after execution.

Example:

DELIMITER //

CREATE DEFINER=`root`@`localhost` 
   PROCEDURE `get_ntime`( in tb varchar(50), in d int, out nt varchar(50) )
BEGIN
   SET @staetment = concat( 'Select ntime into @nTime from ', tb );
   -- SET @date = CONCAT( ' WHERE date = "', d, '"' );
   SET @date = CONCAT( ' WHERE date = ?' );
   SET @statement = CONCAT( @statement, @date );

   SET @dt := d;
   PREPARE stmt FROM @statement;
   -- EXECUTE stmt;
   EXECUTE stmt using @dt;
   DEALLOCATE PREPARE stmt;

   SET nt := @nTime;
END;
//

DELIMITER ;

OTHER TIPS

Prepared statements have session scope, mysql doesn't know you want to use your prepared statement inside stored procedure only. You deallocate the statement immediately, but it doesn't have to be always like that.

Thats why mysql simply disallows using anything that has less scope inside your prepared statement - as is the case with in and out parameters, which have a scope of stored procedure.

As a workaround mentioned in mysql prepare statement manual you can use user variable inside your prepared statement and then SET your out paremeter to that user variable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top