begin
-- 循环标志
declare stopflag int default 0;
-- 出错标志
DECLARE t_error INTEGER DEFAULT 0;
declare m_userId bigint default 0;
declare m_customerId bigint default 0;
declare m_status int default 0;
declare m_goodId bigint default 0;
declare m_count int default 0;
DECLARE cur1 CURSOR for select goodId,count from applyformitem where applyFormId=m_applyFormId;
declare continue handler for not found set stopflag=1;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET t_error=1;
-- 开启事务
START TRANSACTION;
set m_result=0;
-- 打开游标
OPEN cur1;
select userId,customerId,status into m_userId,m_customerId,m_status from applyform where id=m_applyFormId;
IF m_status=1 THEN
-- 已经兑换
set m_result=-1;
set t_error=1;
ELSE
-- 尚未兑换
FETCH cur1 INTO m_goodId,m_count;
while(stopflag=0) DO # 如果游标还没到结尾,就继续循环
begin
UPDATE customer set rePoints=rePoints-(select points from good where id=m_goodId)*m_count where id=m_customerId;
UPDATE customer set drawRePoints=drawRePoints-(select points from good where id=m_goodId)*m_count where id=m_customerId;
UPDATE inventory set reCount=reCount-m_count where orgId=(select orgId from user where id=m_userId) and goodId=m_goodId;
if (select rePoints from customer where id=m_customerId)<0 THEN
-- 客户积分不足
set m_result=-2;
set t_error=1;
end if;
if (select drawRePoints from customer where id=m_customerId)<0 THEN
-- 抽奖积分不足,设置为0
UPDATE customer set drawRePoints=0 where id=m_customerId;
end if;
if (select reCount from inventory where orgId=(select orgId from user where id=m_userId) and goodId=m_goodId)<0 THEN
-- 库存积分不足
set m_result=-3;
set t_error=1;
end if;
FETCH cur1 INTO m_goodId,m_count;
end;
end while;
end if;
-- 关闭游标
CLOSE cur1;
UPDATE applyform set status=1,updateTime=now() where id=m_applyFormId;
IF t_error = 1 THEN
ROLLBACK;
ELSE
set m_result=1;
COMMIT;
END IF;
/*开始初始化变量*/
END