Domanda

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

È stato utile?

Soluzione 2

try this:

select 8-DATEpart(w, closed_time) AS Days_Until_Purged from DB1 ...

Altri suggerimenti

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.

This should solve your problem

SET DATEFIRST 1
Select DATEDIFF(dd,GETDATE(),DATEADD(DAY , 7-DATEPART(WEEKDAY,GETDATE()),GETDATE()))
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top