传递表名以从游标中选择语句

时间:2012-11-08 11:04:45

标签: mysql stored-procedures

如何在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语句?

1 个答案:

答案 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

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