简体   繁体   中英

In MySQL: How to pass a table name as stored procedure and/or function argument?

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?

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

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 ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM