30

例如,这不起作用:

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

4

2 回答 2

40

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

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 $$
于 2010-06-04T20:03:37.783 回答
4

你可以这样做:

 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 ;
于 2019-12-11T09:28:25.917 回答