1. 程式人生 > >mysql儲存過程和遊標遍歷

mysql儲存過程和遊標遍歷

DELIMITER $$ 
CREATE PROCEDURE alarm_replay_insert_procedure()
BEGIN
  -- 定義變數 
  DECLARE _nowTime DATETIME;
  DECLARE _id INT;
  DECLARE _name VARCHAR(50);
  DECLARE stop_flag TINYINT;
 
  -- 遍歷資料結束標誌    
  DECLARE done INT DEFAULT FALSE;    
  DECLARE cur CURSOR FOR SELECT id,`name` FROM  `user`;

  -- 將結束標誌繫結到遊標  
   DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
   DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET stop_flag=1;

 -- 為變數賦值  
 SET _nowTime = NOW();
 SET stop_flag = 0;

 OPEN cur; -- 開啟遊標
 FETCH cur INTO _id, _name;
 WHILE stop_flag<>1 DO -- 若遊標有下一條記錄,迴圈
    INSERT INTO user_replay(id,`name`, `time` ) VALUES(_id,_name,_nowTime);
    FETCH cur INTO _id, _name;
  END WHILE;
 CLOSE cur; -- 關閉遊標

END $$    
DELIMITER ;