Simple Age Calculation

I was helping someone with some SQL stuff and needed to give them a function to calculate someone's age.  Rooted around a bunch of places and finally just ended up re-writing it. So this is mostly to have it on hand. This function is needed because DateDiff doesn't check if they've had their birthday this year.

CREATE FUNCTION CalculateAge (
    @Start smalldatetime
    , @End smalldatetime
    )
RETURNS int
AS
BEGIN
    -- Declare the return variable here
    DECLARE @Age int

    SET @Age = DateDiff(year, @Start, @End)
    IF DateAdd(year, @Age, @Start) > @End
        SET @Age = @Age - 1

    RETURN @Age

END
GO

VB Version

Public Function Age(ByVal value As Date, ByVal d As Date) As Integer
    Age = DateDiff(DateInterval.Year, value, d)
    If value.AddYears(Age) > d Then Age = Age - 1
    Return Age
End Function

Comments

shital said…

Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well.

PMP Certification

Popular posts from this blog

Migrating Legacy Apps to the New SimpleMembership Provider

Get Asp.Net Profile properties from Sql

JavaScript function to automatically add slashes to date