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

时间:2020-12-17 08:50:27

For instance, this does not work:

例如,这是行不通的:

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

DELIMITER ;
CALL countRows('my_table_name');

Produces:

生产:

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

However, this works as expected:

然而,这和预期的一样:

SELECT COUNT(*) as ct FROM my_table_name;

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

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

1 个解决方案

#1


24  

Prepared statements are what you need.

准备好的陈述是你所需要的。

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 $$

#1


24  

Prepared statements are what you need.

准备好的陈述是你所需要的。

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 $$