tags:

views:

41

answers:

2

I need to delete records in a table if the current date is greater than the record creation date + a preset number of days (defined by @numberOfDays). I am using the following SQL statement but am not sure if it’s very efficient. Is there a better way?

I am using MS SQL 2008 server.

DELETE
FROM deviceManager.Test2
WHERE DATEADD(day, @numberOfDays, deviceManager.Test2.GeneratedAt_UTC) < SYSDATETIMEOFFSET()

@numberOfDays is an int with a value of 10

A: 

Seems OK to me, I can't think of a better way off the top of my head.

Francis Upton
A: 

Probably better to adjust the current date instead of every record in the table. Change the logic to "record creation date is before current datetime - @numberOfDays."

This is more efficient - one calculation instead of many.

Brian Frantz
Can you tell me how I would cast an int to a day so that I can do the current datetime - number of days ?
Retrocoder
Try `day < DATEADD(SYSDATETIMEOFFSET(), -@numberOfDays, deviceManager.Test2.GeneratedAt_UTC)` (unless you have a DATESUB function available).
eswald