日期:2014-05-16  浏览次数:20476 次

利用存储过程修改字段类型
今天遇到需要把一个时间类型的字段改为整形,但是又不能破坏原有的数据,即截取年份作为整形保存。设计了一段存储过程完成了这个小小任务:
alter table p_artist drop column birthday ;
alter table p_artist Add  column birthday int default 0 after kind;

基本原理:先是备份了一份数据到另一个表中,然后从另一个表中取到对应的年份倒回来,保证数据没有被破坏;
存储过程如下:
CREATE PROCEDURE updateartist ()
BEGIN
DECLARE birthday_temp int;
DECLARE temp_id bigint(20);
DECLARE find boolean default true;
DECLARE cur1 cursor for select YEAR(bt.birthday),bt.id from test.p_artist bt left join boss.p_artist tp on bt.id=tp.id;
DECLARE continue handler for not found set find=false;

open cur1;

while find = true do
        fetch cur1  INTO birthday_temp,temp_id;
if birthday_temp is NULL then
set birthday_temp=0;
end if;
if find=true then 
update boss.p_artist set birthday = birthday_temp where id=temp_id;
end if; 
end while; 
close cur1;
END;