开发者

How to send table name as Mysql Store procedure

开发者 https://www.devze.com 2023-03-18 11:56 出处:网络
I write a store procedure.But it don\'t take the table name as a parameter.Now how i send a table name as aparameter.Pls see my proc below:

I write a store procedure.But it don't take the table name as a parameter.Now how i send a table name as aparameter.Pls see my proc below:

DELIMITER $$
USE `db_test`$$
DROP PROCEDURE IF EXISTS `test_proc`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `test_proc`(IN newsInfoTable VARCHAR(100))
BEGIN              开发者_如何学JAVA
    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 ;

Calling parameter:

USE db_test;
CALL test_proc('tbl_news_list');

But the ERROR is: Table 'db_test.newsinfotable' doesn't exist

How solve this problem.Pls help.


Use prepared statements in your procedure body:

SET @s = CONCAT('SELECT ... FROM ', newsInfoTable);
PREPARE stmt FROM @s;
EXECUTE stmt;
//.....
DEALLOCATE PREPARE stmt;

Your code should look like :

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;

Also, I don't see any reasons you need to use @news variable...

0

精彩评论

暂无评论...
验证码 换一张
取 消