2019-02-24
閱讀量:
1047
如何在mysql中優(yōu)雅地為表同時(shí)新增10列?
問(wèn)題描述:
當(dāng)我們?cè)谑褂胹ql進(jìn)行批量處理的時(shí)候,例如為表新增10列,涉及了很多重復(fù)操作,對(duì)于重復(fù)操作,能否利用編程思想予以優(yōu)化呢?
解決思路:
- prepare、procedure和while...do的組合,即可實(shí)現(xiàn)復(fù)雜需求的實(shí)現(xiàn)
- 其中prepare是預(yù)處理語(yǔ)句;procedure是存儲(chǔ)過(guò)程,可以理解為封裝函數(shù);while...do...即循環(huán)的實(shí)現(xiàn)形式;delimiter是轉(zhuǎn)義字符,將“;”暫時(shí)用“$$”替代
drop procedure if exists t;
delimiter $$
create procedure t()
begin
declare i int;
declare num varchar(2);
set i =1;
set @sqltext='';
while i<10 do
set num=cast(i as char);
set @sqltext = concat(@sqltext,' add c',num,' char(1) not null, ');
set i=i+1;
end while;
set @sqltext=concat('alter table aaa ',@sqltext,'add c10 char(1) not null;');
end $$
delimiter ;
call t();
select @sqltext;
prepare t from @sqltext;
execute t;
select * from aaa;






評(píng)論(0)


暫無(wú)數(shù)據(jù)
CDA考試動(dòng)態(tài)
CDA報(bào)考指南
推薦帖子
0條評(píng)論
1條評(píng)論
0條評(píng)論