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

时间:2010-06-04 19:56:39

标签: sql mysql stored-procedures mysql-error-1146

例如,这不起作用:

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语句中将参数用作表名需要什么语法?这甚至可能吗?

2 个答案:

答案 0 :(得分:30)

Prepared statements就是您所需要的。

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 :(得分:1)

您可以这样做:

 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 ;