MySQL 儲存過程遊標巢狀,觸發器呼叫儲存過程
阿新 • • 發佈:2019-02-15
#儲存過程 drop procedure if exists update_pointer; CREATE PROCEDURE update_pointer(IN ckindId int) BEGIN #定義變數 DECLARE id int DEFAULT 0; #成績ID DECLARE score int DEFAULT 0; #成績 DECLARE sellID int DEFAULT 0; #價格ID DECLARE pid int DEFAULT 0; #價格ID DECLARE upGrades int DEFAULT 0; #分數上限 DECLARE downGrade int DEFAULT 0; #分數下限 DECLARE _done tinyint(1) DEFAULT 0; #是否未找到資料標記 /* 定義游標 */ DECLARE _Cur CURSOR FOR SELECT t_score.id, t_score.score, t_score.sellID FROM t_score WHERE t_score.kindId = ckindId; #使用者分數記錄查詢 DECLARE _Curprice CURSOR FOR SELECT t_priceinfo.id, t_priceinfo.`upGrade`, t_priceinfo.downGrade FROM t_priceinfo WHERE t_priceinfo.KindID = ckindId; #彩種價格查詢 DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET _done = 1; #錯誤定義,標記迴圈結束 /*開啟游標*/ OPEN _Cur; /*迴圈執行*/ FETCH _Cur INTO id, score, sellID; #獲取資料 WHILE _done = 0 DO #當存在資料的時候進行迴圈 OPEN _Curprice; #開啟遊標 FETCH _Curprice INTO pid, upGrades, downGrade; WHILE _done = 0 DO IF score >= downGrade AND score < upGrades THEN UPDATE t_score SET t_score.sellID = pid WHERE t_score.id = id AND t_score.kindId=ckindId; SET _done=1; END IF; FETCH _Curprice INTO pid, upGrades, downGrade; END WHILE; CLOSE _Curprice; #關閉遊標 SET _done = 0; FETCH _Cur INTO id, score, sellID; #獲取資料 END WHILE; END; #觸發器(Insert) DROP Trigger if exists t_princeInsert_on_priceinfo; create trigger t_princeInsert_on_priceinfo after insert on t_priceinfo for each row begin call update_pointer(NEW.kindID); end; #觸發器(Update) DROP Trigger if exists t_princeUpdate_on_priceinfo; create trigger t_princeUpdate_on_priceinfo after update on t_priceinfo for each row begin call update_pointer(NEW.kindID); end; #觸發器(Delete) DROP Trigger if exists t_princeDelete_on_priceinfo; create trigger t_princeDelete_on_priceinfo after delete on t_priceinfo for each row begin call update_pointer(OLD.kindID); end;