如何在MVql程序中使用从Cursor返回的值作为表名?
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语句?
答案 0 :(得分: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;
详细了解here。
但请注意,您无法参数化表名和列名。这仅适用于值。