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
2009-07-10 17:34:37
That doesn't correspond to the default behaviour of the yearfrac function...
Guffa
2009-07-10 17:45:15
@Guffa - good call, hadn't noticed the difference.
2009-07-10 18:37:48
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
2009-07-10 18:44:31
+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
2009-07-10 17:43:37