I have a table with start_date and end_date both datetime type.
I need a trigger that calculate the elapsed minutes between both dates and update the result on the duration field on the same table when the end_date is updated.
For some reason all I try gives me Syntax error.
I'm using phpMyAdmin sql window to do it.
Please help.
CREATE TRIGGER 'my_trigger'
BEFORE UPDATE ON `table`
FOR EACH ROW
BEGIN
IF NEW.end_date IS NOT NULL THEN
SET NEW.duration = (UNIX_TIMESTAMP(NEW.end_date) - UNIX_TIMESTAMP(OLD.start_date)) / 60
END IF;
END //
Related
I am setting up a trigger which reads a timestamp column and adds 7 days to it and then puts the newly calculated date into another column in the same table. The timestamp column is called date_requested and the new column is called return_date. Here is my code so far.
Thanks in advance
DELIMITER //
CREATE TRIGGER external_requests_date_trig BEFORE INSERT ON external_requests
FOR EACH ROW
BEGIN
SET NEW.return_date = DATE_ADD(NEW.date_requested, INTERVAL 7 DAY);
END//
DELIMITER ;
I am using MySql via terminal. Below is the command I have used to create table but it is showing date in YYYY-MM-DD HH:MM:SS (example: 2018-05-25 14:12:47)
create table test (foo int, ts timestamp default CURRENT_TIMESTAMP);
But I want by default it take yesterday date every time I insert data in (YYYY-MM-DD) format.
Please help me to find the command.
Thanks,
Amit
According to the official MySQL documentation https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add, you can do like this:
If you want to store the "yesterday" on creation:
ts TIMESTAMP NOT NULL DEFAULT NOW() - INTERVAL 1 DAY
If you want to store the "yesterday" on every update:
ts TIMESTAMP NOT NULL DEFAULT NOW() ON UPDATE NOW() - INTERVAL 1 DAY
According to this answer Select records from NOW() -1 Day:
NOW() returns a DATETIME.
And INTERVAL works as named, e.g. INTERVAL 1 DAY = 24 hours.
So if your script is cron'd to run at 03:00, it will miss the first
three hours of records from the 'oldest' day.
To get the whole day use CURDATE() - INTERVAL 1 DAY. This will get
back to the beginning of the previous day regardless of when the
script is run.
Hope it helps!
DEFAULT values in MySQL must be constants. They can't be functions or expressions (with the exception of CURRENT_TIMESTAMP).
Source: http://dev.mysql.com/doc/refman/5.6/en/data-type-defaults.html
In addition you can add a trigger to your table for your requirement
Simply Create a Table without constraint
create table test (foo int, ts timestamp );
Then add a trigger to this table
CREATE TRIGGER settime
BEFORE INSERT on test
FOR EACH ROW BEGIN
IF new.`ts ` is null THEN
SET new.`ts ` = DATE_ADD(NOW(), INTERVAL -1 DAY);
END IF;
END;
I have the following stored procedure to calculate running averages. However when called, it runs forever.
delimiter //
CREATE PROCEDURE run_avg(date_start DATE,date_end DATE,pol_id TINYINT,sta_id TINYINT)
NOT DETERMINISTIC
CONTAINS SQL
BEGIN
TRUNCATE average_table;
WHILE date_start <= date_end DO
INSERT INTO average_table(value_avg)
SELECT AVG(a.value) as val
FROM (SELECT value FROM obs_all_unik
WHERE start_time >=date_start
AND start_time < date_start + INTERVAL 8 HOUR
AND polutant_id=pol_id
AND station_id=sta_id) AS a;
SET date_start = date_start + INTERVAL 1 HOUR;
END WHILE;
END;//
delimiter ;
Any ideas?
INDEX(station_id, polution_id, start_date)
would help performance.
It seems wrong to insert just the averages into the table without also inserting these values: station_id, polution_id, start_date.
The endless loop was due to a wrong definition of date_start as DATE. Since I tried to increment by hours it was returning one and the same value. I changed it to TIMESTAMP and now the problem is gone.
I am trying to create a trigger using the date add function in mysql using phpadmin and getting a syntax error; my goal is to automatically add a date in the estimated finish date column ie 'fin_dt' which is 14 days from the date the order is placed. Ie current date plus 14 days. I have come up with the following mysql state but get an error:
DELIMITER $$
CREATE TRIGGER before_insert_orderin BEFORE INSERT ON order_in
BEGIN
SET NEW.fin_dt = SELECT DATE_ADD(CURDATE(), INTERVAL 14 DAY) ;
END $$
Your trigger syntax is wrong. You are missing for each row and also you do not need select to set the value. It should be as
delimiter //
create trigger before_insert_orderin before insert on order_in
for each row
begin
set new.fin_dt = date_add(curdate(),interval 14 day);
end ; //
delimiter ;
Your Trigger syntax near " SET NEW.fin_dt = SELECT DATE_ADD(CURDATE(), INTERVAL 14 DAY)"
SELECT DATE_ADD is Wrong. It should be as
CREATE TRIGGER `before_insert_orderin`
BEFORE INSERT ON `order_in`
FOR EACH ROW
SET NEW.fin_dt=DATE_ADD(NOW(), INTERVAL 14 DAY)
I hasn't been writing any MySql stored procedures before, so I don't know them at all. I have one database table which has some records in it. The main column is dateTime - when this record was saved in the database.
I have wrote the MySql stored procedure to select every record from the specified date:
CREATE PROCEDURE getMessages(IN dateFrom DATETIME)
SELECT * FROM EsbMessage WHERE dateTime <= dateFrom;
And this is the call:
CALL getMessages('2012-10-04 13:11:09');
This works correctly, it returns me the records from the specified date.
What I need to do is:
If the record is over one week old, I need to update the other
column.
If the record is over one year old, I need to delete that record.
I can easily do this programmatically, but in this case I have to do this using stored procedure.
So I'am thinking of something like this:
CREATE PROCEDURE updateMessages(IN dateFrom DATETIME)
BEGIN
SELECT * FROM EsbMessage WHERE dateTime <= dateFrom;
#for each message
#if the message is over one week old but not over one year old:
UPDATE EsbMessage SET body = '';
#if message is over one year old:
DELETE FROM EsbMessage WHERE dateTime = #message.dateTime
END
But I don't know how to use for loop in stored procedure, and how to write if statements depending on my requirements and the other thing I don't now how to count the dates in MySql. For e.g. If I have the current date then I need to subtract the 365 days from the current date.
Could somebody help me with this issue?
You wouldn't need a loop, just have your conditions in the WHERE clause:
#if the message is over one week old but not over one year old:
UPDATE EsbMessage SET body = ''
WHERE dateTime >= DATE_SUB(NOW(),INTERVAL 1 WEEK) AND dateTime <= DATE_SUB(NOW(),INTERVAL 1 YEAR);
#if message is over one year old:
DELETE FROM EsbMessage WHERE dateTime >= DATE_SUB(NOW(),INTERVAL 1 YEAR);
How to loop and to use if clauses is described here: http://www.mysqltutorial.org/stored-procedures-loop.aspx
I would do it without loops:
CREATE PROCEDURE updateMessages(IN dateFrom DATETIME)
BEGIN
UPDATE EsbMessage SET body = '' where dateTime <= dateFrom -(86400*7); //86400 = 1 day
#if message is over one year old:
DELETE FROM EsbMessage where dateTime <= dateFrom -(86400*365);
END