使用MySQL用户定义的变量在UPDATE语句上连接表名

时间:2013-07-26 19:03:35

标签: mysql sql concat

我正在尝试为UPDATE语句的表名设置前缀。我必须在多个数据库上运行此UPDATE语句几十次,每个数据库都有不同的表前缀。

下面的代码不起作用,但这是我想要实现的目标。

SET @prefix = 'prefix_';
SET @old = "old_value";
SET @new = "new_value";
UPDATE CONCAT(@prefix, 'table1') SET some_field = REPLACE(some_field, @old, @new);
UPDATE CONCAT(@prefix, 'table2') SET some_field = REPLACE(some_field, @old, @new);
UPDATE CONCAT(@prefix, 'table3') SET some_field = REPLACE(some_field, @old, @new);

手动编写将是......

UPDATE prefix_table1 SET some_field = REPLACE(some_field, 'old_value', 'new_value');
UPDATE prefix_table2 SET some_field = REPLACE(some_field, 'old_value', 'new_value');
UPDATE prefix_table3 SET some_field = REPLACE(some_field, 'old_value', 'new_value');

1 个答案:

答案 0 :(得分:3)

使用Dynamic SQL

SET @prefix = 'prefix_';
SET @old = "old_value";
SET @new = "new_value";

SET @sql1 = CONCAT('UPDATE ', @prefix, 'table1 SET some_field = REPLACE(some_field,?,?)');
SET @sql2 = CONCAT('UPDATE ', @prefix, 'table2 SET some_field = REPLACE(some_field,?,?)');
SET @sql3 = CONCAT('UPDATE ', @prefix, 'table3 SET some_field = REPLACE(some_field,?,?)');

PREPARE stmt1 FROM @sql1;
PREPARE stmt2 FROM @sql2;
PREPARE stmt3 FROM @sql3;

EXECUTE stmt1 USING @old, @new;
EXECUTE stmt2 USING @old, @new;
EXECUTE stmt3 USING @old, @new;

DEALLOCATE PREPARE stmt1;
DEALLOCATE PREPARE stmt2;
DEALLOCATE PREPARE stmt3;