我想将3分钟步骤的时间戳值(给定开始日期和结束日期)插入到只有一个时间戳列的表中。
我目前从sql server切换到mysql。我知道如何在SQL中使用以前的数据库,但我不确定后者。感谢。
这是我当前(不工作)悲惨的尝试:
DELIMITER //
CREATE PROCEDURE test()
begin
declare StartTS TIMESTAMP DEFAULT null;
declare EndTS TIMESTAMP DEFAULT null;
set StartTS = '2012-01-01 00:00:00';
set EndTS = '2014-01-01 00:00:00';
start transaction;
while StartTS < EndTS do
insert into timestamps (TimeStampEntry) values (StartTS);
SET StartTS = StartTS + INTERVAL 3 MINUTE;
end while;
commit;
end
//
DELIMITER ;
call test();
PS:
create table TimeStamps (
Id INTEGER NOT NULL AUTO_INCREMENT,
TimeStampEntry DATETIME,
primary key (Id)
)
当前的sproc:
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `myProc`(IN t1 timestamp, IN t2 timestamp)
BEGIN
WHILE t1 <= t2 DO
INSERT INTO timestamps (TimeStampEntry) Values (t1) ;
SET t1 = DATE_ADD(t1, INTERVAL 180 SECOND);
#SET t1 = t1 + INTERVAL 180 SECOND;
END WHILE;
END
呼叫:
CALL myProc('2010-01-01 00:00:00', '2014-01-01 00:00:00');
答案 0 :(得分:3)
尝试这样的事情:
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;
CALL myProc(now(), ADDDATE(NOW(), INTERVAL 15 MINUTE));
http://sqlfiddle.com/#!2/5672e/9
或者改变你的行:
SET StartTS = StartTS + INTERVAL 3 MINUTE;
到
SET StartTS = ADDDATE(StartTS, INTERVAL 3 MINUTE);