rosa.tarraga
rosa.tarraga

Reputation: 165

Comparing dates in a trigger MYSQL

I am creating a "before insert" trigger. What I need to do, is compare if the new row has a difference of 60 second (or 1 minute) with the last row (taking into account time).

My code is the following:

    CREATE TRIGGER before_insert_detection 
    BEFORE INSERT ON detection
    FOR EACH ROW
    BEGIN

         Declare oldDate date;
         Declare newDate date;
         Declare timediff int;

         SELECT DATE_DETECTION into oldDate
         FROM DETECTION ORDER BY DATE_DETECTION desc limit 1;

         SET newDate = NEW.DATE_DETECTION;
         SET timediff = (TIMESTAMPDIFF(SECOND, oldDate, newDate)) < 60;

         IF timediff = 1 
            THEN SIGNAL SQLSTATE '02000' SET MESSAGE_TEXT = "Same detection less than a minute 
            ago";END IF; 
     END;;

So if the difference between 2 dates is less than a minute, timediff must be 1, and the message should raise. But that never happens... No rows are inserted, no matter time...

Examples of inserts:

INSERT INTO DETECTION VALUES (1, '2019-10-15 12:00:01');

inserted OK

INSERT INTO DETECTION VALUES (2, '2019-10-15 12:00:20');

inserted OK, and it should not happen...

Any help?

Thanks in advance!! :)

Upvotes: 0

Views: 719

Answers (1)

P.Salmon
P.Salmon

Reputation: 17655

I cannot reproduce your problem if olddate and newdate are defined as datetime.

 drop trigger if exists t;

drop table if exists t;
create table t(id int auto_increment primary key,date_detection datetime); 
delimiter $$
CREATE TRIGGER t 
    BEFORE INSERT ON t
    FOR EACH ROW
    BEGIN

         Declare oldDate datetime;
         Declare newDate datetime;
         Declare timediff int;

         SELECT DATE_DETECTION into oldDate
         FROM t ORDER BY DATE_DETECTION desc limit 1;

         SET newDate = NEW.DATE_DETECTION;
         SET timediff = (TIMESTAMPDIFF(SECOND, oldDate, newDate)) < 60;

         IF timediff = 1  THEN 
                SIGNAL SQLSTATE '02000' SET MESSAGE_TEXT = 'Same detection less than a minute ago';

            END IF; 
     END $$

delimiter ;

MariaDB [sandbox]> set @olddate = '2019-10-15 12:00:01';
Query OK, 0 rows affected (0.00 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> insert into t (date_detection) values (@olddate);
ERROR 1643 (02000): Same detection less than a minute ago
MariaDB [sandbox]> set @newdate = '2019-10-15 12:00:20';
Query OK, 0 rows affected (0.01 sec)

MariaDB [sandbox]> insert into t (date_detection) values (@newdate);
ERROR 1643 (02000): Same detection less than a minute ago

Upvotes: 1

Related Questions