我正在尝试设置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');
最佳答案
在这个上面使用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;
Prepared Statements
关于mysql - 使用MySQL用户定义的变量在UPDATE语句上连接表名,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17889028/