Cari Blog Ini

23 Juli 2012

Example of SQL Server Date Difference Calculation - YEARS


1. Find the number of YEARS between two dates with format Date - yyyy-mm-dd
-----------------------------------------------------------------------
-----code:start-----
-----------------------------------------------------------------------
DECLARE @d1 DATETIME, @d2 DATETIME
SELECT
    @d1 = '1997-01-01',
    @d2 = '2009-12-31'
   
SELECT
    DATEDIFF(year, @d1, @d2) AS YearDiff
-----------------------------------------------------------------------
-----code:end-----
-----------------------------------------------------------------------

Result Messages:
YearDiff
-----------
12



(1 row(s) affected)



2. Find the number of YEARS between two dates with format Date - mm/dd/yyyy
-----------------------------------------------------------------------
-----code:start-----
-----------------------------------------------------------------------
DECLARE @d1 DATETIME, @d2 DATETIME
SELECT
    @d1 = '1/1/1997',
    @d2 = '12/31/2009'
   
SELECT
    DATEDIFF(year, @d1, @d2) AS YearDiff
-----------------------------------------------------------------------
-----code:end-----
-----------------------------------------------------------------------

Result Messages:
YearDiff
-----------
12

(1 row(s) affected)



3. Find the number of YEARS between two dates with format Date - dd-mmm-yyyy
-----------------------------------------------------------------------
-----code:start-----
-----------------------------------------------------------------------
DECLARE @d1 DATETIME, @d2 DATETIME
SELECT
    @d1 = '01-Jan-1997',
    @d2 = '31-Dec-2009'
   
SELECT
    DATEDIFF(year, @d1, @d2) AS YearDiff
-----------------------------------------------------------------------
-----code:end-----
-----------------------------------------------------------------------

Result Messages:
YearDiff
-----------
12

(1 row(s) affected)


Source:
http://syntaxhelp.com/SQLServer/DATEDIFF