Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stored procedure error on CALL

I am trying to call a procedure which compiles successfully but on calling I get this error:

Query: call proc5

Error Code: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NULL' at line 1

This is my Stored procedure:

DELIMITER $$

CREATE DEFINER = `root` @`localhost` PROCEDURE `proc5` () 
BEGIN
  DECLARE done BOOL DEFAULT FALSE ;
  DECLARE tablename VARCHAR (100) ;
  DECLARE tracktables CURSOR FOR 
  SELECT 
    TABLE_NAME 
  FROM
    information_schema.TABLES 
  WHERE TABLE_SCHEMA = 'db1' ;
  DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = TRUE ;
  OPEN tracktables ;
  myloop :
  LOOP
    FETCH tracktables INTO tablename ;
    IF done 
    THEN CLOSE tracktables ;
    LEAVE myloop ;
    END IF ;
    SET @s = CONCAT(
      'INSERT INTO db2.test1 SELECT * FROM ',
      @tablename
    ) ;
    PREPARE stmt1 FROM @s ;
    EXECUTE stmt1 ;
    DEALLOCATE PREPARE stmt1 ;
  END LOOP ;
END $$

DELIMITER ;

Actually, I want to select all the tables from a database and insert those tables into one table which is in another database using MySQL Cursors. And when I call this stored procedure I get the above error.

like image 999
Sathish D Avatar asked Apr 28 '26 06:04

Sathish D


1 Answers

The problem is that you are mixing declared variables and impromtu @vars.

var -> tablename does not equal var -> @tablename.

Change the set line to:

SET @s = CONCAT(
  'INSERT INTO db2.test1 SELECT * FROM `'
  ,tablename
  ,'`'
) ;

Now it should work.

The backticks ` should not be needed, but are there just in case.

like image 78
Johan Avatar answered May 01 '26 04:05

Johan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!