我写了一个商店程序。但是它没有将表名作为参数。现在我如何将表名作为参数发送。请参阅下面的proc:
DELIMITER $$
USE `db_test`$$
DROP PROCEDURE IF EXISTS `test_proc`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `test_proc`(IN newsInfoTable VARCHAR(100))
BEGIN
SELECT news INTO @news
FROM newsInfoTable
WHERE CURDATE()=DATE_FORMAT(date_time,'%Y-%m-%d')
ORDER BY date_time DESC LIMIT 1;
SELECT @news;
END$$
DELIMITER ;
调用参数:
USE db_test;
CALL test_proc('tbl_news_list');
但是ERROR是:表'db_test.newsinfotable'不存在
如何解决这个问题。请帮助。
答案 0 :(得分:1)
在您的程序正文中使用prepared statements:
SET @s = CONCAT('SELECT ... FROM ', newsInfoTable);
PREPARE stmt FROM @s;
EXECUTE stmt;
//.....
DEALLOCATE PREPARE stmt;
您的代码应如下所示:
SET @sql_stam = CONCAT('SELECT news INTO @news FROM ',newsInfoTable,
' WHERE DATE_FORMAT(date_time,\'%Y-%m-%d\')
ORDER BY date_time DESC LIMIT 1');
...
SELECT @news;
此外,我认为您无需使用@news
变量...