在存储过程中使用变量作为列名?

时间:2021-09-09 10:06:25

Here I wrote a mysql procedure which select all text type field of specified database 'wp'

这里我写了一个mysql程序,它选择指定数据库'wp'的所有文本类型字段

and I want to update every text type field row appending extra string via CONCAT function.

我想通过CONCAT函数更新附加额外字符串的每个文本类型字段行。

after I call test2 , error shows:

在我调用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 regards _tbl as a string but not a variable.

mysql将_tbl视为字符串而不是变量。

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 ;

1 个解决方案

#1


3  

You'll need to use prepared statements. Also see How To have Dynamic SQL in MySQL Stored Procedure

您需要使用预准备语句。另请参阅如何在MySQL存储过程中使用动态SQL

#1


3  

You'll need to use prepared statements. Also see How To have Dynamic SQL in MySQL Stored Procedure

您需要使用预准备语句。另请参阅如何在MySQL存储过程中使用动态SQL