Tuesday, February 14, 2012

Calculating Overdue Days

I have table with three columns: 1) TodaysDate,
2)DueBackDate,
3) DaysOverdue
The problem I am having is creating a formula in MS SQL, so that whenthe 'DueBackDate' column is more than todays date, I want the'DaysOverdue' column to be incremented accordingly.
I have tried creating an SQL Query something like this:
UPDATE rental
SET DaysOverdue = DaysOverdue + 1
WHERE ({ fn NOW() } > DueBackDate)
But the problem with this that it only increments the 'DaysOverdue'field by 1. When I want it to basically subtract todays date by'DueBackDate'.
I have tried to also create a formula within MS SQL but I come up witherrors. I have done something like this in Access which worked. TheFormula looked like this:
IIF(Now()>[DueBackDate],int(Now()-[DueBackDate]),0)
Is there a way to convert this formula so that is would work in MS SQL?
Thanks.
I now found a solution by using the DatePart Function.
Stick out tongue [:P]
|||DatePart or DateDiff?
|||When I used DatePart, my SQL Query was like this:
UPDATE table
SET DaysOverdue = DATEPART(dd, { fn NOW() }) - DATEPART(dd, DueBackDate)
WHERE ({ fn NOW() } > DueBackDate)

|||The funny thingabout programming is that there are usually several ways to solve thesame problem. You might consider using the DATEDIFF functioninstead. It was made for exactly this purpose. And use thebuilt-in GETDATE() function instead of{ fn NOW() }.
I was thinking of something like this, which should perform better for you:
DECLARE @.today datetime
SELECT @.today = GETDATE()
UPDATE
table
SET
DaysOverdue = DATEDIFF(dd,DueBackDate,@.today)
WHERE
@.today > DueBackDate

I opted to storethe current date/time in a @.today variable, so that I could be certainthat the same exact date/time would be used for the entirestatement. This would be important should the execution periodcross a date boundary, plus there's no reason for SQL to have todetermine the current date twice for each row (which I believe wouldhappen at least).


|||Thanks!
I'll try that out.
I can say that it looks more efficient than my previous query!
Thanks again!

No comments:

Post a Comment