Question

Within a trigger before I insert some data into a table, I would want it to check, whether the difference of dates of events I am entering is greater than or equal to 1 day. There can only be one event in one club taking place each day.

Sample story

If there already is 2014-01-01 19:00:00 date in database and I'm trying to insert another record with 2014-01-01 date (hour does not matter), it should not allow it.

Partial code from the trigger

DECLARE k INT DEFAULT 0;

/* This is where I get the error, ABS is to make it always positive to go through  
checking, so that it wont matter whether the NEW date is before or after */

SELECT ABS(DATEDIFF(DATE_FORMAT(`performance_date`, '\'%Y-%m-%d %H:%i:%s\''), 
DATE_FORMAT(NEW.`performance_date`, '\'%Y-%m-%d %H:%i:%s\''))) INTO k;

/* Below code is out of scope for this question */

IF k = 0 THEN
    SIGNAL SQLSTATE '58005'
    SET MESSAGE_TEXT = 'Wrong! Only 1 performance in 1 club is allowed per day! Change your date, or club!';
END IF;

Error Code: 1054. Unknown column 'performance_date' in 'field list'

I've tried something as simple as:

...DATEDIFF(`performance_date`, NEW.`performance_date`)
Was it helpful?

Solution

You can use a SELECT ... INTO var_list query to COUNT how many entries are already in the database that match your times:

I'm assuming that you mean one entry per day, and I'm assuming that the performance_date column is of DATETIME or TIMESTAMP type.

DECLARE k INT DEFAULT 0;

/* Count number of performances occurring on the same date as the 
   performance being inserted */
SELECT COUNT(*)
FROM tbl
WHERE performance_date
BETWEEN DATE(NEW.`performance_date`)
AND DATE(DATE_ADD(NEW.`performance_date`, INTERVAL 1 DAY))
INTO k;

/* If k is not 0, error as there is already a performance */
IF k != 0 THEN
    SIGNAL SQLSTATE '58005'
    SET MESSAGE_TEXT = 'Wrong! Only 1 performance in 1 club is allowed per day! Change your date, or club!';
END IF;

For clarity, if you have a performance with performance_date as 2014-01-01 19:00:00, and you insert a new performance with date 2014-01-01 08:30:00 (for example) then the above code will run this query, which will return a COUNT of 1, which will then cause the trigger to give that error:

SELECT COUNT(*)
FROM tbl
WHERE performance_date
BETWEEN DATE("2014-01-01 08:30:00") AND DATE(DATE_ADD("2014-01-01 08:30:00", INTERVAL 1 DAY))
# The line above will become:
# BETWEEN "2014-01-01" AND "2014-01-02"
INTO k
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top