使用Mysql存储过程更新和插入表行

时间:2017-09-12 11:54:57

标签: mysql stored-procedures cursor

我有一个包含70000记录的table book_meetings,我想将这些数据迁移到另一个表中,对此我进行了少量修改,我创建了一个Mysql存储过程。记录将插入新表中,但值设置为null。 我只从book_meetings表中选择了四列,并希望将它们插入表中。

id int
date date
meet_at time
duration_in_hours decimal

我想要的是根据以上值计算start_dateend_date

例如:

if date ="2017-09-08" , meet_at is "09:00:00" and duration_in_hours is 1.5

然后start_date will be "2017-09-08 09:10:00"

end_date= start_date_duration_in_hour
end_date will be "2017-09-08 09:10:00"

start_date = concat date and meet_at 
end_date = start_date + duration_in_hours

and insert this values in new table

如果还有其他更好的主意,请建议

CREATE PROCEDURE book_meetings8()
BEGIN
      -- Declare local variables
     DECLARE done BOOLEAN DEFAULT 0;
     DECLARE meet_at TIME;
     DECLARE start_date DATETIME;
     DECLARE tmp_date VARCHAR(255);
     DECLARE end_date DATETIME;
     DECLARE end_recurring_date DATE;
     DECLARE date1 DATE ;
     DECLARE id INTEGER(11);
     DECLARE duration DECIMAL(8,2);
     DECLARE minutes INTEGER(11);


    -- Declare the cursor
      DECLARE iter CURSOR
     FOR
       SELECT  id,date, meet_at,duration_in_hours FROM 
      book_meetings LIMIT 100;
   -- Declare continue handler
     DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;

  -- Open the cursor
     OPEN iter;
  -- Loop through all rows
     REPEAT
  -- Get order number

     FETCH iter INTO id,date1,meet_at,duration;
     SET minutes = duration  * 60;
     SET start_date = CAST(date1 as char) + " "+CAST(meet_at as 
    char);  
     SET end_date = CAST(start_date as datetime) + INTERVAL 
minutes MINUTE;     

    INSERT INTO 
  book_meetings_1(start_date,end_date)
  VALUES(start_date,end_date);
  -- End of loop
  UNTIL done END REPEAT;
 -- Close the cursor
 CLOSE iter;
  END;

1 个答案:

答案 0 :(得分:0)

我已用单个SQL语句解决了上述问题(无需存储过程立即插入和更新所有记录)

INSERT INTO temp_diary.book_meetings ( id,start_date,end_date) SELECT  id,CONCAT(`date`, ' ', `meet_at`) as start_date,DATE_ADD(concat(date,' ',meet_at), INTERVAL `duration_in_hours` HOUR) as end_date FROM  estate.book_meetings;