2013-07-26 55 views
1

我試圖在UPDATE語句的表名上設置前綴。我必須在多個數據庫上運行這個UPDATE語句幾十次,每個數據庫都有不同的表前綴。使用MySQL用戶定義變量在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'); 

回答

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;