Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 datediff argument

Author  Topic 

DMWCincy
Starting Member

11 Posts

Posted - 2006-07-20 : 14:56:52
Just wanted to know how you guys handled this question. Need to know the datediff in Years and Months of two dates. The datediff function doesn't work. Look at the following example:

declare @Startdate as datetime
set @Startdate = '10/1/2004'

select datediff(yy, @Startdate, getdate()) as Years, datediff(mm,@startdate, getdate()) as Months


This comes up with 2 Years and 21 months where the true difference is 1 yr 9 mnths. I came up with the following that will work(thanks to how SQL handles default datatypes for numbers):


declare @Startdate as datetime
set @Startdate = '10/1/2004'

select datediff(mm, @Startdate, getdate())/12 as Years, datediff(mm,@startdate, getdate()) - (datediff(mm, @Startdate, getdate())/12)*12 as Months


A coworker says there has to be a better way of doing this but can't come up with a better solution. Off the top of my head, I can't think of any other way to make this simpler which is why I'm asking you guys to help settle the argument.

Thanks, DMW

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2006-07-20 : 16:41:41
You mean like this?
declare @Startdate as datetime 
set @Startdate = '10/1/2004'

select datediff(mm, @Startdate, getdate()) / 12 Years,
datediff(mm, @Startdate, getdate()) % 12 Months



Peter Larsson
Helsingborg, Sweden
Go to Top of Page

Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)

7020 Posts

Posted - 2006-07-20 : 17:50:02
Maybe what you are really after is Age. For example, what would the difference be between 2004/10/30 and 2006/07/01? Would it be 1 year 9 months, or 1 year 8 months? If you would want the second, you need to calculate Age.

This function returns age in format YYYY MM DD.
Age Function F_AGE_YYYY_MM_DD:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=62729





CODO ERGO SUM
Go to Top of Page
   

- Advertisement -