Home Forums SQL Server 7,2000 T-SQL How can we calculate Age of employee? RE: How can we calculate Age of employee?

  • declare @birthday datetime

    declare @ToDate datetime

    DECLARE @smonth TINYINT, @sday TINYINT, @syear SMALLINT

    DECLARE @emonth TINYINT, @eday TINYINT, @eyear SMALLINT

    DECLARE @months TINYINT, @days TINYINT, @years SMALLINT

    DECLARE @tdate SMALLDATETIME

    set @birthday = '15 feb 1969'

    --set @retireage = 65

    set @birthday = @birthday--getdate()

    set @ToDate = getdate()--dateadd(year, +@retireage, @birthday)

    --print @ToDate

    SET @smonth = MONTH(@birthday)

    SET @sday = DAY(@birthday)

    SET @syear = YEAR(@birthday)

    SET @emonth = MONTH(@ToDate)

    SET @eday = DAY(@ToDate)

    SET @eyear = YEAR(@ToDate)

    SET @years = @eyear - @syear

    SET @months = 0

    SET @days = 0

    IF (@emonth >= @smonth)

    SET @months = @emonth - @smonth

    ELSE

    BEGIN

    SET @years = @years - 1

    SET @months = @emonth + 12 - @smonth

    END

    IF (@eday >= @sday)

    SET @days = @eday - @sday

    ELSE

    BEGIN

    IF (@months > 0)

    SET @months = @months - 1

    ELSE

    BEGIN

    SET @years = @years - 1

    SET @months = @months + 11

    END

    SET @tdate = DATEADD(yy,@years,@birthday)

    SET @tdate = DATEADD(m,@months,@tdate)

    SET @days = DATEDIFF(d,@tdate,@ToDate)

    END

    print 'Accurate Age: (' +convert(varchar(11), @ToDate, 113) + ') ' +

    convert(varchar(3), @years) + ' Years ' + convert(varchar(3), @months) + ' Months ' + convert(varchar(3), @days) + ' Days ' +

    substring(CONVERT(VARCHAR(8),DATEADD(ss,datediff(second, @birthday, @todate),0),108), 1, 2) + ' Hours ' + substring(CONVERT(VARCHAR(8),DATEADD(ss,datediff(second, @birthday, @todate),0),108), 4, 2) + ' Minutes ' + substring(CONVERT(VARCHAR(8),DATEADD(ss,datediff(second, @birthday, @todate),0),108), 7, 2) + ' Seconds '