1. 程式人生 > >mysql 巢狀遊標的使用

mysql 巢狀遊標的使用

BEGIN
	DECLARE iEmail varchar(50);#引數iEmail的型別一定要和存入裡面的資料型別一致
	DECLARE iUserId int;
	DECLARE NOTFOUND int DEFAULT 0;


	DECLARE mycursor CURSOR FOR SELECT email FROM table;
	DECLARE mycursor1 CURSOR FOR SELECT userId FROM table1 WHERE email=iEmail;#iEmail是從第一個遊標獲得的資料

	DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' set NOTFOUND=1;
	OPEN mycursor;
	FETCH mycursor INTO iEmail;
	WHILE (NOTFOUND = 0 AND iEmail IS NOT NULL) DO

		OPEN mycursor1;
		FETCH mycursor1 INTO iUserId;
		WHILE(NOTFOUND=0 AND iUserId IS NOT NULL)	DO
			#在這裡寫處理的程式碼
			FETCH mycursor1 INTO iUserId;
		END WHILE;
		CLOSE mycursor1;
		SET NOTFOUND=0;

	FETCH mycursor INTO iEmail;
	END WHILE;
	CLOSE mycursor;
END