在存储过程中使用变量作为列名?
这里我写了一个mysql程序,它选择指定数据库'wp'的所有text
类型字段
,我想更新每个附加的text类型字段行通过CONCAT函数额外字符串。
在我 call test2 后,错误显示:
Query : call test2()
Error Code : 1146
Table 'wp._tbl' doesn't exist
Execution Time : 00:00:00:000
Transfer Time : 00:00:00:000
Total Time : 00:00:00:000
---------------------------------------------------
mysql 将 _tbl 视为字符串,但不是变量。
那么我可以纠正这个问题吗?
代码:
DELIMITER $$
USE `wp`$$
DROP PROCEDURE IF EXISTS `test2`$$
CREATE
PROCEDURE `test2`()
BEGIN
DECLARE _tbl VARCHAR(100);
DECLARE _cl VARCHAR(100);
DECLARE notFound INT DEFAULT 0;
DECLARE cur CURSOR FOR SELECT table_name,column_name FROM information_schema.columns WHERE table_schema = 'wp' AND data_type ='text';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET notFound =1;
OPEN cur;
WHILE notFound = 0 DO
FETCH cur INTO _tbl,_cl;
UPDATE _tbl SET _cl = CONCAT(_cl,'extra string goes here.....');
IF NOT noFound THEN SET notFound = 0;
END IF;
END WHILE;
CLOSE cur;
END$$
DELIMITER ;
Here I wrote a mysql procedure which select all text
type field of specified database 'wp'
and I want to update every text type field row appending extra string via CONCAT function.
after I call test2 , error shows:
Query : call test2()
Error Code : 1146
Table 'wp._tbl' doesn't exist
Execution Time : 00:00:00:000
Transfer Time : 00:00:00:000
Total Time : 00:00:00:000
---------------------------------------------------
mysql regards _tbl as a string but not a variable.
So can I correct this?
code:
DELIMITER $
USE `wp`$
DROP PROCEDURE IF EXISTS `test2`$
CREATE
PROCEDURE `test2`()
BEGIN
DECLARE _tbl VARCHAR(100);
DECLARE _cl VARCHAR(100);
DECLARE notFound INT DEFAULT 0;
DECLARE cur CURSOR FOR SELECT table_name,column_name FROM information_schema.columns WHERE table_schema = 'wp' AND data_type ='text';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET notFound =1;
OPEN cur;
WHILE notFound = 0 DO
FETCH cur INTO _tbl,_cl;
UPDATE _tbl SET _cl = CONCAT(_cl,'extra string goes here.....');
IF NOT noFound THEN SET notFound = 0;
END IF;
END WHILE;
CLOSE cur;
END$
DELIMITER ;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要使用准备好的语句。
另请参阅如何在 MySQL 存储过程中使用动态 SQL
You'll need to use prepared statements.
Also see How To have Dynamic SQL in MySQL Stored Procedure