0

In SQL Server, trying to write a age-off report for inventory purposes. Each week, the inventory system marks thousands of rows for deletion. This takes place on Sundays @ 06:00:00 as part of weekly SQL DB purge schedule.

Using (yyyy-mm-dd hh:mm:ss:ms) format for closed_time, how can I calculate the numbers of days between that date, until next Sunday of the current week? And to be more elaborate, is there a way to narrow it down to the exact DD:HH:MM? The problem is the each client's Sunday DB schedule for purge varies. So that might be difficult to compute. Might be easier to just calculate whole days until Sunday 00:00:00. I tried using the DATEDIFF function with no success.

SELECT
Yada

DATEDIFF(DAY, closed_time,DW) AS  Days_Until_Purged

FROM DB1

WHERE closed_time DESC

Thx in advance

Brad Fox
  • 685
  • 6
  • 19
Doctorj77
  • 115
  • 2
  • 2
  • 11
  • This states `MS SQL Server`, but is also labelled `MySQL`? *(Which has very different date-time functions available)* – MatBailie Mar 10 '14 at 15:02

3 Answers3

1

If you choose any Sunday in the past (Such as 06:00 Sunday 2nd January 2000), you can calculate time that has GONE BY since then.

Then, if you take that and do modulo 7-days you get the time that has gone by since the most recent Sunday.

Then, if you do 7 - time_gone_by_since_last_sunday you get the time until the next sunday.

I'm going to do this in minutes to cope with a client that has a setting of 06:30.

DECLARE
  @batch_processing_time SMALLDATETIME
SET
  @batch_processing_time = '2000-01-02 06:00'

SELECT
  (60*24*7) - DATEDIFF(minute, @batch_processing_time, closed_time) % (60*24*7)
FROM
  yourTable

That's the number of minutes from each record's closed_time until the next @batch_processing_time.

Divide by (24*60) to get it in days.

MatBailie
  • 83,401
  • 18
  • 103
  • 137
0

try this:

select 8-DATEpart(w, closed_time) AS Days_Until_Purged from DB1 ...
Jayvee
  • 10,670
  • 3
  • 29
  • 40
  • 1
    When using `DATEPART` always be sure to mention the importance of the `DATEFIRST` setting on the server. – MatBailie Mar 10 '14 at 15:14
0

This should solve your problem

SET DATEFIRST 1
Select DATEDIFF(dd,GETDATE(),DATEADD(DAY , 7-DATEPART(WEEKDAY,GETDATE()),GETDATE()))
Raphael
  • 1,677
  • 1
  • 15
  • 23