如何使用此查询将动态表名称传递给mySQL过程?

时间:2015-12-29 06:40:14

标签: mysql stored-procedures

我有创建过程,当我手动传递表名时,它的工作正常,但是当我传递动态表名时,它说 dbname.tblname不存在

DELIMITER $$
CREATE
PROCEDURE `lmsonline`.`delProc`(tblName VARCHAR(20),sr INT)    
BEGIN
DELETE FROM tblName WHERE srno=sr; 
SET @num := 0;
UPDATE tblName SET srno = @num := (@num+1);
ALTER TABLE tblName AUTO_INCREMENT = 1;
END$$
DELIMITER ;

并执行我CALL delProc('beginner',6);

3 个答案:

答案 0 :(得分:1)

一种方法是使用这样的预备语句。

DELIMITER $$
CREATE
PROCEDURE `delProc`(tblName VARCHAR(20),sr INT)    
BEGIN
  SET @SQL := CONCAT('DELETE FROM ', tblName,' WHERE srno=',sr);
  PREPARE stmt FROM @SQL;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;      

  SET @num := 0;
  SET @SQL := CONCAT('UPDATE ', tblName,' SET srno = @num := (@num+1)');
  PREPARE stmt FROM @SQL;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;      

  SET @SQL := CONCAT('ALTER TABLE ', tblName,' AUTO_INCREMENT = 1');
  PREPARE stmt FROM @SQL;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;      
END$$
DELIMITER ;

答案 1 :(得分:0)

尝试在表名周围使用[],有时会发生与系统名称相同的系统表。 e.x. [初学者]。

感谢。

答案 2 :(得分:0)

    CREATE PROCEDURE `lmsonline`.`delProc`(IN tblName VARCHAR(20),sr INT)    
    BEGIN
      SET @SQL := CONCAT('DELETE FROM ', tblName,' WHERE srno=',sr);  
   PREPARE stmt3 FROM @t1;
     EXECUTE stmt3;
     DEALLOCATE PREPARE stmt3;
    END$$
    DELIMITER ;
    ...try this way ,if not working check whether table exists or deleted by mistake or else.

    Thanks