Working with DateTime SQL
Updated: 21 May 2010 | 1 comment
This issue has been solved. See solution.
Does anyone know of a simple method by which I can return aging numbers based on a datetime field in my Altiris database? I have it working now except it is not quite specific enough. I would like to return the results similar to '43 years 8 mons 3 days'...
I found this website that listed an 'age(timestamp)' function, but this either A).does not work or B). is not being implemented properly by me. Either is possible given that I am very new to Altiris and to SQL.
I am currently returning a result set that tells me 5.9 years, etc... using the following sql statement:
Select warmd.[Start Date], round((CAST(getdate() - warmd.[Start Date]as float)/365),2,0) as 'Age'
from dbo.Inv_Warranty_and_Maintenance_Details warmd
Please help me if possible...my boss would really appreciate it! Me too.
discussion Filed Under:
Comments
Not necessarily simple, but. . .
The page you linked is actually to Postregsql, an open-source database, and the functions listed are not available in Microsoft SQL. If you're relatively inexperienced in SQL, I urge you to TEST THIS FIRST and, if at all possible, have a DBA help you to get it in place.
Grab the code from the marked solution on the following page starting with 'CREATE FUNCTION' and ending with the last 'END'. . .:
http://social.msdn.microsoft.com/forums/en-US/tran...
Change the line reading:
RETURN CAST(@YEAR AS VARCHAR) + 'Y:' + RIGHT('00'+CAST(@Month AS VARCHAR),2) + 'M:'+ RIGHT('00'+CAST(@Day AS VARCHAR),2) + 'D'
to
RETURN
CASE
WHEN @YEAR = 1
THEN CAST(@YEAR AS VARCHAR) + ' Year, '
WHEN @YEAR > 1
THEN CAST(@YEAR AS VARCHAR) + ' Years, '
ELSE ''
END +
CASE
WHEN @MONTH = 1
THEN CAST(@MONTH AS VARCHAR) + ' Month, '
WHEN @MONTH > 1
THEN CAST(@MONTH AS VARCHAR) + ' Months, '
ELSE ''
END +
CASE
WHEN @DAY = 1
THEN CAST(@DAY AS VARCHAR) + ' Day'
WHEN @DAY > 1
THEN CAST(@DAY AS VARCHAR) + ' Days'
ELSE '0 Days'
END
Once you've loaded the function into your SQL database, your query will now look like:
I hope this helps!
Would you like to reply?
Login or Register to post your comment.