mysqlmysql-error-1146

Using a variable as a column name in a stored procedure?


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 ;

Solution

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