--mysql
drop procedure if exists `bb`;
create procedure `bb`()
begin
declare v_saleorder_orgid varchar(100);
declare v_saleorder_braid varchar(100);
declare v_value varchar(100);
declare _done TINYINT(1) default 0;
declare _all TINYINT(1) default 0;
declare _count TINYINT(1) default 0;
declare _index TINYINT(1) default 0;
declare cur_brand cursor for select organizeid,brandid from `table1` order by statistics_date,saledayid;
declare continue handler for SQLSTATE '02000' set _done = 1;
select count(1) into _all from table1;
open cur_brand;
loop_xxx:loop
fetch cur_brand into v_saleorder_orgid,v_saleorder_braid;
set _index=_index+1;
if(_index>_all) THEN
leave loop_xxx;
end if;
select count(1) into _count from table2 where ORGANIZEID=v_saleorder_orgid and BRANDID=v_saleorder_braid LIMIT 0,1;
if(_count>0) THEN
select BRANDNAME INTO v_value from table2 where ORGANIZEID=v_saleorder_orgid and BRANDID=v_saleorder_braid LIMIT 0,1;
update table1 set BRANDNAME=v_value where ORGANIZEID=v_saleorder_orgid and BRANDID=v_saleorder_braid;
end if;
set v_value=0;
end loop;
end;
call `bb`();