在 MySQL 中:如何将表名作为存储过程和/或函数参数传递?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2977356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 16:11:53 来源:igfitidea点击:
In MySQL: How to pass a table name as stored procedure and/or function argument?
提问by randomx
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 语句中使用参数作为表名需要什么语法?这甚至可能吗?
回答by a1ex07
Prepared statementsare 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 $$
回答by Getachew Mulat
You can do it like this:
你可以这样做:
DROP PROCEDURE IF EXISTS `getDataUsingSiteCode`;
DELIMITER $$
CREATE PROCEDURE `getDataUsingSiteCode`(
IN tab_name VARCHAR(40),
IN site_ VARCHAR(255)
)
BEGIN
SET @site_code = site_;
SET @sql_ =CONCAT('SELECT * FROM ',tab_name,' WHERE site=?');
PREPARE statement_ FROM @sql_;
EXECUTE statement_ using @site_code;
END$$
DELIMITER ;