mysql 存储过程

BEGIN
declare startDate VARCHAR(50);
declare regionName VARCHAR(200);
declare companyName VARCHAR(200);
declare departmentName VARCHAR(200);
declare pos VARCHAR(200);
declare regionId bigint;
declare userId bigint;
declare oldId bigint;

#定义游标结束
declare stop int default 0;

#定义游标

declare cur CURSOR FOR (SELECT DATE_FORMAT(u.startDate,'%Y-%m-%d %H:%i:%s') startDate ,u.region_id regionId , u.id userId,
r.`name` regionName,c.`name` companyName,d.`name` departmentName,u.pos pos
FROM `ck_user` u
INNER JOIN ck_user_region r on r.id=u.region_id
left JOIN ck_user_company c on c.id=u.company_id
left JOIN ck_user_department d on d.id=u.department_id
where u.region_id is not null and u.startDate is not null);

#设置结束
declare CONTINUE HANDLER FOR SQLSTATE '02000' SET stop=1;

DELETE FROM ck_user_growth_recorditem;
DELETE FROM ck_user_growth_record;

#打开游标
OPEN cur;
FETCH cur INTO startDate,regionId,userId,regionName,companyName,departmentName,pos;
WHILE stop <> 1 DO
#循环
INSERT into ck_user_growth_record(createTime,creater_id,region_id)
VALUES(startDate,userId,regionId);
set oldId=last_insert_id();

INSERT into ck_user_growth_recorditem(content,createTime,growthType,creater_id,userGrowthRecord_id)
VALUES(regionName,startDate,1,userId,oldId);
if companyName is not null &&companyName!=''then
INSERT into ck_user_growth_recorditem(content,createTime,growthType,creater_id,userGrowthRecord_id)
VALUES(companyName,startDate,2,userId,oldId);

end if;
if departmentName is not null &&departmentName!=''then
INSERT into ck_user_growth_recorditem(content,createTime,growthType,creater_id,userGrowthRecord_id)
VALUES(departmentName,startDate,3,userId,oldId);

end if;
if pos is not null &&pos!=''then
INSERT into ck_user_growth_recorditem(content,createTime,growthType,creater_id,userGrowthRecord_id)
VALUES(pos,startDate,6,userId,oldId);

end if;

 

#下一个
FETCH cur INTO startDate,regionId,userId,regionName,companyName,departmentName,pos;
END WHILE;

CLOSE cur;
END

posted @ 2015-12-01 11:48  凡尘网络  阅读(205)  评论(0编辑  收藏  举报