0

This question is related to:

SO question

It uses this code:

CREATE PROCEDURE myProc(IN t1 timestamp, IN t2 timestamp)
BEGIN

  WHILE t1 <= t2 DO
INSERT INTO test (ts) Values (t1)  ;
    SET t1 = DATE_ADD(t1, INTERVAL 3 MINUTE);
  END WHILE;
END;

invoke like this:

CALL myProc(now(), ADDDATE(NOW(), INTERVAL 15 MINUTE));

which is extremely slow. Is there any way to speed this up (e.g. do things differently)?

4

2 回答 2

1

I think wrapping this in a transaction would improve things.... something like:

CREATE PROCEDURE myProc(IN t1 timestamp, IN t2 timestamp)
BEGIN

DECLARE EXIT HANDLER FOR SQLEXCEPTION 
BEGIN
      ROLLBACK;
END;

START TRANSACTION;

   WHILE t1 <= t2 DO
      INSERT INTO test (ts) Values (t1)  ;
      SET t1 = DATE_ADD(t1, INTERVAL 3 MINUTE);
   END WHILE;

COMMIT;

END

I just threw that together and haven't tested it but I think that might help.

于 2012-10-10T13:02:23.500 回答
1

I think you can speed-up your procedure by using temporary table. Here's the plan:

  • create tmp table
  • fill tmp table with data you want to insert
  • do one INSERT query that requires disk writing/index rebuilding

Somethin like this:

CREATE PROCEDURE myProc(IN t1 timestamp, IN t2 timestamp)
BEGIN
  CREATE TEMPORARY TABLE tmp (ts timestamp);
  WHILE t1 <= t2 DO
    INSERT INTO tmp SET ts = t1;
    SET t1 = DATE_ADD(t1, INTERVAL 3 MINUTE);
  END WHILE;
  INSERT INTO test (ts) SELECT ts FROM tmp;
  DROP TABLE tmp;
END;
于 2012-10-10T14:26:15.647 回答