在 MySQL 中:如何将表名作为存储过程和/或函数参数传递?

例如,这不起作用:

DELIMITER //
CREATE PROCEDURE countRows(tbl_name VARCHAR(40))
  BEGIN
    SELECT COUNT(*) as ct FROM tbl_name;
  END //

DELIMITER ;
CALL countRows('my_table_name');

产生:

ERROR 1146 (42S02): Table 'test.tbl_name' doesn't exist

但是,这按预期工作:

SELECT COUNT(*) as ct FROM my_table_name;

在 select 语句中使用参数作为表名需要什么语法?这甚至可能吗?

What syntax is required to use an argument as a table name in a select statement? Is this even possible?

推荐答案

准备好的陈述正是您所需要的.

CREATE  PROCEDURE `test1`(IN tab_name VARCHAR(40) )
BEGIN
 SET @t1 =CONCAT('SELECT * FROM ',tab_name );
 PREPARE stmt3 FROM @t1;
 EXECUTE stmt3;
 DEALLOCATE PREPARE stmt3;
END $$

相关文章