批量修改MySQL表字首

2021-06-01 20:48:48 字數 1877 閱讀 6212

在資料庫設計中,對於某個特定的專案,一般對其所有的資料表指定相同的表字首,如wordpress的資料表都是以wp_開頭的,discuz的資料表都是以dz_開頭的。這樣不但便於區分,更重要的作用在於可以避免將多個專案部署到同乙個資料庫時可能出現的表同名衝突。

那麼,有如下這種情況時:

使用者a和使用者b都使用wordpress程式,現在他們想將程式放在一起,但是主機上只分配了乙個資料庫給他們,意味著他們的資料需要存放在乙個資料庫,問題是他們先前已經建立好了wordpress的資料庫,並且使用了相同的表字首,都使用了wp_,那麼,怎樣批量修改表字首呢。

通過php指令碼顯然可以做到,在mysql中修改表名的語句為

rename table oldname to newname

這裡,我嘗試採用純sql語句來實現,搗鼓了一陣子,於是有了下面這個儲存過程:

-- @author xueyu

-- @desc modify the prefix of table name in db

-- @example

---- use dbname;

-- show tables;

-- source ~/change_prefix.sql;

---- call change_prefix('old_', 'new_', 'dbname');

---- show tables;

-- drop procedure if exists change_prefix;--

delimiter //

drop procedure if exists change_prefix //

create procedure change_prefix(in oldpre varchar(200), in newpre varchar(200), in dbname varchar(200))

begin

declare done int default 0;

declare oldname varchar(200);

declare cur cursor for select table_name from information_schema.tables where table_schema= dbname and table_name like concat(oldpre,'%');

declare continue handler for not found set done = 1;

open cur;

repeat

fetch cur into oldname;

if not done then

set @newname = concat(newpre, trim(leading oldpre from oldname));

set @sql = concat('rename table ',oldname,' to ',@newname);

prepare tmpstmt from @sql;

execute tmpstmt;

deallocate prepare tmpstmt;

end if;

until done end repeat;

close cur;

end //

delimiter ;

使用方法很簡單,直接匯入這個指令碼,然後執行

call change_prefix(

'old_'

,'new_'

,'db_name'

);

call change_prefix

('','added_'

,'db_name'

);同理,第二個引數留空可以去掉指定的表字首。

mysql批量修改表字首

以wordpress資料庫表為例。先登入你的phpmyadmin中,選中你的wordpress資料庫,選擇sql出現如下圖,然後輸入sql命令 select concat alter table table name,rename to table name,from information sch...

mysql 替換 字首 批量修改mysql表字首

header content type text html charset utf 8 設定好相關資訊 dbserver 127.0.0.1 連線的伺服器一般為localhost dbname test 資料庫名 dbuser root 資料庫使用者名稱 dbpassword root 資料庫密碼 ...

怎麼批量修改mysql資料庫表字首

怎麼批量修改mysql資料庫表字首 在資料庫設計中,對於某個特定的專案,一般對其所有的資料表指定相同的表字首,如wordpress的資料表都是以wp 開頭的,discuz的資料表都是以dz 開頭的。這樣不但便於區分,更重要的作用在於可以避免將多個專案部署到同乙個資料庫時可能出現的表同名衝突。www....