1. 程式人生 > >Mysql 儲存過程批量建表

Mysql 儲存過程批量建表

CREATE DEFINER=`root`@`%` PROCEDURE `createTables`()
  begin
    declare i int;
    declare suffix varchar(20);
    declare createsql varchar(2048);
    set i = 0;
    while i < 100 do
      set suffix = hex(i);
      if length(suffix)<=1 then
      set suffix = concat('0',hex(i));
      end if;
      set suffix = lower(suffix);
      set createsql = concat('CREATE TABLE table_',suffix,'(
                              `id` int(11) NOT NULL AUTO_INCREMENT COMMENT \'自增主鍵\',
                              `uuid` varchar(32)  NOT NULL COMMENT \'業務\',
                              PRIMARY KEY (`id`)
                              ) ENGINE=InnoDB DEFAULT CHARSET=utf8');
      set @createsql = createsql;


      prepare stmt from @createsql;
      execute stmt;
      set i = i + 1;
    end while;
end

裡面用到了幾個mysql自帶的函式:

1. hex(number): 十進位制轉成16進位制

2. length(string) : 字串長度

3. concat(str1,str2) : 字串拼接

4. lower(str) : 字串轉小寫