例如,这不起作用:
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语句中使用参数作为表名需要什么语法?这有可能吗?
准备好的语句是您所需要的。
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 $$