0

如何使用从 Cursor 返回的值作为 mysql 过程中的表名?

DECLARE cur CURSOR FOR
select table_name, column_name
    from information_schema.columns
    where table_schema = 'foo' and table_name like 'bar%';
OPEN cur;

loop1: LOOP

FETCH cur
INTO table_val, column_val;

IF no_more_rows THEN
  CLOSE cur;
  LEAVE loop1;
END IF;
update table_val SET column_val ...

这会引发错误foo.table_val doesnt exist。如何获取要传递给 select 语句的实际表名?

4

2 回答 2

1

换成update table_val SET column_val ..._

SET @sql = CONCAT('UPDATE ', table_val, ' SET ', column_val, ' = whatever WHERE...');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

在此处阅读更多相关信息。

但请注意,您不能参数化表名和列名。这仅适用于值。

于 2012-11-08T11:52:31.983 回答
0

我也将分享我的修复。希望它也会对某人有所帮助。

-- set to "$$" as we have ";" inside of Procedure. MySQL will be confused.(is this part of Procedure or should I run it now?)
DELIMITER $$

CREATE PROCEDURE UpdateTable()
BEGIN

    DECLARE done INT DEFAULT FALSE;
    DECLARE _table_name CHAR(255);
    DECLARE cur CURSOR FOR
            SELECT table_name FROM information_schema.tables
            WHERE table_schema = 'db_name' AND table_type = "BASE TABLE";
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

    OPEN cur;
    My_loop: LOOP
        FETCH cur INTO _table_name;
        SET @my_table_name = _table_name;

        IF done THEN
          LEAVE My_loop;
        END IF;

        SET FOREIGN_KEY_CHECKS = 0;

        SET @stmt = CONCAT('ALTER TABLE ', @my_table_name, ' CONVERT TO CHARACTER SET utf8;'); 
        PREPARE stmt1 FROM @stmt; 
        EXECUTE stmt1; 
        DEALLOCATE PREPARE stmt1;   
        
        SET FOREIGN_KEY_CHECKS = 1;
            
    END LOOP;
    CLOSE cur;

END$$

-- set to normal. ";" 
DELIMITER ;
于 2022-03-03T20:19:00.130 回答