2015-05-07 69 views
0

我正在嘗試在MySQL中編寫一個存儲過程,該存儲過程根據指定的前綴(在本例中爲'migrate_')刪除和重命名錶。代碼應該遞歸地重命名以'migrate_'開頭的所有表,直到不再有任何表,但是,在嘗試運行時出現錯誤。重命名錶準備好的語句

BEGIN 

SELECT COUNT(*) INTO @num_migrate 
FROM information_schema.tables a 
WHERE a.table_name LIKE 'migrate_%'; 

IF (@num_migrate > 0) THEN 
    SELECT concat('USE `md_rails`; DROP TABLE IF EXISTS `', 
      Replace(tbls.table_name,'migrate_',''), '`; ', 
     'RENAME TABLE `', tbls.table_name, '` TO `', 
      Replace(tbls.table_name,'migrate_',''), '`;') INTO @b 
    FROM information_schema.tables tbls 
    WHERE tbls.table_name LIKE 'migrate_%' LIMIT 1; 
    PREPARE stmt FROM @b; 
    EXECUTE stmt; 
    CALL handle_migrated_tables(); 
END IF; 


END 

我得到的錯誤是:

Error Code: 1064. You have an error in your SQL syntax; check the manual 
that corresponds to your MySQL server version for the right syntax to use 
near 'DROP TABLE IF EXISTS second_test; RENAME TABLE migrate_second_test TO 
second_tes' at line 1 

我試着運行從自己的select語句生成的代碼,它做什麼,我需要的,但由於某種原因它不在準備好的聲明中不喜歡它。

任何幫助將不勝感激!

+1

您在SQL查詢語句2,儘量把它分解 –

+0

你確定你可以'PREPARE'多條語句? [文檔](https://dev.mysql.com/doc/refman/5.6/en/prepare.html)似乎暗示你不能。不過,你可以創建一個存儲過程。你也只是在這裏迭代*,而不是遞歸*。 – tadman

+0

@tadman,存儲的proc名稱是'handle_migrated_tables',對不起,我沒有在開始時指定。 –

回答

1

Lashane沒錯!如果有人想知道,這裏是最後的(工作)代碼:

CREATE PROCEDURE `handle_migrated_tables`() 
    BEGIN 
     SET max_sp_recursion_depth=50; 

     SELECT COUNT(*) INTO @num_migrate 
     FROM information_schema.tables a 
     WHERE a.table_name LIKE 'migrate_%'; 

     IF (@num_migrate > 0) THEN 

      SELECT tbls.table_name INTO @tbl 
      FROM information_schema.tables tbls 
      WHERE tbls.table_name LIKE 'migrate_%' LIMIT 1; 

      SET @a = concat('DROP TABLE IF EXISTS md_rails.', Replace(@tbl, 'migrate_', '')); 
      PREPARE stmt FROM @a; 
      EXECUTE stmt; 
      DEALLOCATE PREPARE stmt; 

      SET @b = concat('RENAME TABLE md_rails.', @tbl, ' TO ', Replace(@tbl, 'migrate_', '')); 
      PREPARE stmt FROM @b; 
      EXECUTE stmt; 
      DEALLOCATE PREPARE stmt;   

      CALL handle_migrated_tables(); 
     END IF; 


    END