tags:

views:

105

answers:

2

How do I write the YearFrac function that comes with Excel in Sql 2005?

+3  A: 

Find out the distance between two dates using DateDiff, and then divide that value by 365

EDIT

You could, of course, create your own function to do the job:

create function yearfrac (@d1 datetime, @d2 datetime) returns float
as
begin
return abs(datediff(d, @d1, @d2)) / 365.00
end
David Hedlund
That doesn't correspond to the default behaviour of the yearfrac function...
Guffa
@Guffa - good call, hadn't noticed the difference.
right you are, guffa, i missed that one. in your version, though, you'd have to do something like my *365.00* solution above, to force the division to work with decimals, otherwise you'll always end up with 0.
David Hedlund
+1  A: 

For the default usage (two data parameters):

datediff(day, date1, date2) / 360.0

For the special case where the third parameter has the value 3:

datediff(day, date1, date2) / 365.0

Edit:
Added a decimal to make it a floating point operation.

Guffa
fyi, this truncates the return value.