SQLUSA
BI TRIO 2008
FREE TRIAL
CLICK HERE TO ORDER

SQL Server 2008 Best Practices
SQL Server 2005 Best Practices

How to calculate employment service time and age?

Execute the following SQL Server T-SQL example script in Management Studio Query Editor to calculate the difference between two dates in years, months and days.

-- SQL calculate length of service in years, months, days - SQL calculate age

-- SQL calculating duration between two dates

-- SQL datediff datetime function - SQL dateadd datetime function

USE AdventureWorks;

DECLARE  @EndDate             DATETIME,

         @Anniversary         DATETIME,

         @StartDate           DATETIME,

         @YYDelta             INT,

         @MMDelta             INT,

         @DDDelta             INT

 

SET @StartDate = '2000-01-01'

 

SET @EndDate = Getdate()

 

SET @Anniversary =

      Dateadd(yy,Datediff(yy,@StartDate,@EndDate),@StartDate)

 

SET @YYDelta = Datediff(yy,@StartDate,@EndDate) -

(CASE

   WHEN @Anniversary > @EndDate THENELSE 0   END)

 

SET @MMDelta = Month(@EndDate - @Anniversary) - 1

 

SET @DDDelta = Day(@EndDate - @Anniversary) - 1

 

SELECT Years  = @YYDelta,

       Months = @MMDelta,

       [Days] = @DDDelta

GO

 

/* Results

 

Years       Months      Days

9           1           19

*/

------------

The World Leader in SQL Server 2008 Training
The future is just a CLICK away. Your future!
 
SQLUSA.com Home Page

Copyright 2005-2010, SMI Corp. All Rights Reserved.

SQL Server 2008 is a program product of Microsoft Corporation.
SQL Server 2005 is a program product of Microsoft Corporation.
SQL Server 2000 is a program product of Microsoft Corporation.