mysql中使用光標的demo

    第一次用遊標,寫了個demo,此遊標蛋疼的實現了從test1表逐條複製數據到同樣的表結構的test2,等價於insert into test2 select * from test1;

DROP TABLE IF EXISTS `test1`;
CREATE TABLE `test1` (
  `id` int(11) NOT NULL auto_increment,
  `type` int(11) default NULL,
  `order1` int(11) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- ----------------------------
-- Records of test1
-- ----------------------------
INSERT INTO `test1` VALUES ('1', '1', '1');
INSERT INTO `test1` VALUES ('2', '1', '1');
INSERT INTO `test1` VALUES ('3', '1', '1');
INSERT INTO `test1` VALUES ('4', '1', '1');


DROP TABLE IF EXISTS `test2`;
CREATE TABLE `test2` (
  `id` int(11) NOT NULL auto_increment,
  `type` int(11) default NULL,
  `order1` int(11) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 

create procedure curdemo()
begin
               declare stop_flag int DEFAULT 0;//聲明一個標記,當遊標狀態爲最後一條記錄時,修改該變量
	declare id int default 0;
	declare type int default 0;
	declare order1 int default 0;
	declare cur1 cursor for select * from test1;
                declare CONTINUE HANDLER FOR SQLSTATE '02000' SET stop_flag=1;  
	open cur1;//打開遊標

                fetch cur1 into id,type,order1;讀取數據到遊標
                while stop_flag<>1 DO//若遊標有下一條記錄,循環
	insert into test2 values(id,type,order1);
                 fetch cur1 into id,type,order1;
                 end while;
                close cur1;//關閉遊標
end

 這個測試相當蛋疼.......

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章