我有创建过程,当我手动传递表名时,它工作得很好,但是当我通过动态表名时,它表示dabn.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);

最佳答案

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

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 ;

08-26 07:27