Home > Enterprise >  How can I execute a comand if condition is true (SQL)
How can I execute a comand if condition is true (SQL)

Time:12-21

I want to compare 2 dates and if there´s a difference bigger than 2 days I want to update the field "data_fecho" from the table.

Here's an example from the table

id message lastupdate data_fecho
1 Hello 2021-12-20 15:20:51 NULL
SELECT id,message,DATEDIFF(NOW(), lastupdate) AS dif FROM tickets;

Above I can get the difference between the dates but I can´t update it, doesn´t recognize dif

IF (dif > 2)
BEGIN
    UPDATE tickets set data_fecho=NOW()
END

CodePudding user response:

You could add a where clause to your update statement:

UPDATE tickets
SET    data_fecho = NOW()
WHERE  DATEDIFF(NOW(), lastupdate) > 2
  • Related