Pregunta

I am trying to create a PHP query to delete SQL table rows if the order_date column is a over a year old. I would also like a second query where table rows will be deleted if the same column is a day old.

To go more in depth, the order_date column is in my current table, tracking_orders, and was created using part of a query: order_date datetime NOT NULL DEFAULT GETDATE(),. The tracking_orders table currently looks like this:

order_date  tracking_order  account_id
Apr 7 2014 3:49PM   1   1
Apr 7 2014 3:51PM   2   1

The day I am asking this question is April 8th 2014, so I am trying to make a query to delete rows if the order_date data is Apr 7 2013, and another query to delete rows if the order_date data is Apr 7 2014. Also, if the data is more than 1 year old, I would still like it to delete. For example, Apr 7 2012.

For a code example, I am looking for something like this:

$sql = 'DELETE * from tracking_orders WHERE order_date == DATE_SUB(getdate(), INTERVAL 1 YEAR)';

And something like this, to delete after one day:

$sql = 'DELETE * from tracking_orders WHERE order_date == DATE_SUB(getdate(), INTERVAL 1 DAY)';

Note: the above doesn't work because DATE_SUB is MySQL syntax, and I am working with MSSQL.

Thank you for any help. All help is greatly appreciated.

¿Fue útil?

Solución

Try this:

DELETE from tracking_orders 
WHERE DATEDIFF(dy,order_date, getdate()) = 1 
OR DATEDIFF(yy,order_date, getdate()) > 1

The first condition in where checks for a difference of 1 day, and the second for a difference greater than 1 year. Note that this is going strictly by the calendar so the below will also return 1 even though time difference is less than 24 hours:

select datediff (dy, '2013-01-01 23:00:00.000', '2013-01-02 22:00:00.000')

To check for 24 hour difference only use DATEDIFF(hh,order_date, getdate()) = 1

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top