Mysql 函式進行相似表的增刪欄位的操作

2021-09-25 02:44:17 字數 1717 閱讀 2707

碰到分表的庫,裡面好多表都是分出來的,如cms_news_1,cms_news_2,cms_news_3 。。。反正就是好多好多

要同時給這麼多表增加乙個字段 city_id。手動乙個表乙個表的增加,估計幾個百錶下來,必定會有出入的。

找捷徑,用mysql的可編譯的函式—儲存過程 來寫一下。

找出相似的表,取出表名,進行迴圈。

declare taskcursor cursor for select table_name from information_schema.tables where table_schema='庫名' and table_name like  'cms_news%' ;  

open taskcursor;

fetch taskcursor into tablename;

為了防止有的表,已經存在了該字段,這裡有個判斷。

注:這裡如果有加庫名,有時會連帶查詢別的庫,返回結果就不對了!

if not exists (

select 1 from information_schema.columns where table_schema='庫名' and table_name = 'tablename' and column_name = 'city_id' )then

....

end if;

完整**:
delimiter //

drop procedure if exists customeraddfield//

create procedure customeraddfield()

begin

declare tablename varchar(100) default '';

declare done int default 0;

declare taskcursor cursor for select table_name from information_schema.tables where table_schema='庫名' and table_name like 'cms_news%' ;

declare continue handler for not found set done = 1;

open taskcursor;

repeat

fetch taskcursor into tablename;

if not done then

if not exists (

select 1 from information_schema.columns where table_schema='庫名' and table_name = 'tablename' and column_name = 'city_id' )then

set @sql2=concat('alter table ',tablename,' add city_id int(8) default 100000');

prepare stmt from @sql2;

execute stmt;

end if;

end if;

until done end repeat;

close taskcursor;

end//

delimiter;

call customeraddfield();

mysql 表的增刪改查

1.建立表 create table 表名 欄位名1 型別 寬度 約束條件 欄位名2 型別 寬度 約束條件 欄位名3 型別 寬度 約束條件 1.在同一張表中,欄位名不能相同 2 寬度和約束條件可選 3.欄位名和型別是必須的 2.檢視表 檢視表結構 desc 表名 檢視表的詳細資訊 show crea...

mysql基本操作之建表並進行增刪查改

1 準備 開啟服務 確保安裝mysql並配置好環境變數,開啟終端輸入命令 在mac下mysql.server start,在windows下net start mysql,提示啟動成功,如圖1所示。圖12 建立資料庫 開啟服務成功後,繼續輸入mysql uroot p,並輸入密碼,進入mysql s...

mysql增刪改查鍊錶 鍊錶的增刪改查

include include 先定義鍊錶裡面的元素。typedef struct nodemynode 定義整個鍊錶。typedef struct linkmylink int isempty to mylink mylink mylink 判斷鍊錶是否為空。int push to mylinki...