游标,存储过程 无 DELIMITER $$USE `eloan_tj`$$DROP PROCEDURE IF EXISTS `pro_d_tender_updatecount`$$CREATE DEFINER=`dba`@`%` PROCEDURE `pro_d_tender_updatecount`(IN pownerid INT)BEGIN -- 借款成功次数 i=循环标识符 DECLARE cid,i INT; -- 成功借
游标,存储过程DELIMITER $$ USE `eloan_tj`$$ DROP PROCEDURE IF EXISTS `pro_d_tender_updatecount`$$ CREATE DEFINER=`dba`@`%` PROCEDURE `pro_d_tender_updatecount`(IN pownerid INT) BEGIN -- 借款成功次数 i=循环标识符 DECLARE cid,i INT; -- 成功借款时间','号分割 2012-03-19,2012-03-19 DECLARE cdatestr TEXT; -- 两次时间 DECLARE dateS,dateE VARCHAR(50); SET i = 1; -- 借款成功次数,借款成功时间 SELECT COUNT(DISTINCT FROM_UNIXTIME(cdate,'%Y-%m-%d')),GROUP_CONCAT(DISTINCT FROM_UNIXTIME(cdate,'%Y-%m-%d') ORDER BY cdate) INTO cid,cdatestr FROM d_tender_repayment WHERE borrowerid = pownerid; SELECT GROUP_CONCAT(DISTINCT FROM_UNIXTIME(cdate,'%Y-%m-%d') ORDER BY cdate) gcdate INTO cdatestr FROM d_tender_repayment WHERE borrowerid = pownerid; WHILE i <= cid DO SELECT SUBSTRING_INDEX(cdatestr,',',i-1) INTO dateS; -- 上次时间 SELECT SUBSTRING_INDEX(cdatestr,',',i) INTO dateE; -- 这次时间 SET dateS = UNIX_TIMESTAMP(SUBSTRING_INDEX(dateS,',',-1));-- 上次','最后时间 SET dateE = UNIX_TIMESTAMP(SUBSTRING_INDEX(dateE,',',-1));-- 这次','最后时间 IF i = 1 THEN UPDATE d_tender SET bidding = 0 WHERE cdate <= dateE AND ownerid = pownerid; ELSE UPDATE d_tender SET bidding = i-1 WHERE cdate >= dateS AND cdate <= dateE AND ownerid = pownerid; END IF; SET i= i +1; END WHILE; -- 大于最后时间 UPDATE d_tender SET bidding = cid WHERE cdate >= dateE AND ownerid = pownerid; -- 未借款成功 UPDATE d_tender SET bidding = 0 WHERE bidding IS NULL; END$$ DELIMITER ; CALL pro_d_tender(94) SELECT ownerid,bidding,FROM_UNIXTIME(cdate,'%Y-%m-%d') FROM d_tender WHERE ownerid = 94 -- 2012-05-17 -- 2013-06-25 -- 2013-09-04 -- 2013-12-11 SELECT DISTINCT FROM_UNIXTIME(cdate,'%Y-%m-%d') gcdate FROM d_tender_repayment WHERE borrowerid =94; SELECT ownerid,bidding,FROM_UNIXTIME(cdate,'%Y-%m-%d') FROM d_tender WHERE ownerid = 416 -- 2012-03-19 -- 2012-09-19 SELECT DISTINCT FROM_UNIXTIME(cdate,'%Y-%m-%d') gcdate FROM d_tender_repayment WHERE borrowerid =416; UPDATE d_tender SET bidding = NULL CALL pro_updatecount SELECT * FROM d_tender DROP PROCEDURE IF EXISTS pro_updatecount; DELIMITER $$ CREATE PROCEDURE pro_updatecount() BEGIN -- 声明一个标志done, 用来判断游标是否遍历完成 DECLARE done INT DEFAULT 0; -- 声明一个变量,用来存放从游标中提取的数据 -- 特别注意这里的名字不能与由游标中使用的列明相同,否则得到的数据都是NULL DECLARE pownerid VARCHAR(50) DEFAULT NULL; -- 声明游标对应的 SQL 语句 DECLARE cur CURSOR FOR SELECT ownerid FROM d_tender GROUP BY ownerid; -- 在游标循环到最后会将 done 设置为 1 DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; -- 执行查询 OPEN cur; -- 遍历游标每一行 REPEAT -- 把一行的信息存放在对应的变量中 FETCH cur INTO pownerid; IF NOT done THEN -- 这里就可以使用 pownerid对应的信息了 CALL pro_d_tender_updatecount(pownerid); END IF; UNTIL done END REPEAT; CLOSE cur; END $$ DELIMITER ;