DateDiff function returns the difference between to dates
Suppose we have employee table and it has following rows and columns
Id
|
Name
|
Description
|
JoiningDate
|
1
|
Test1
|
Executive
|
10/5/2013 0:00
|
2
|
Test2
|
S.Executive
|
10/5/2012 0:00
|
3
|
Test3
|
Team Lead
|
10/5/2012 0:00
|
4
|
Test4
|
Jr Engineer
|
10/11/2014 0:00
|
Calculate the Employee joining Year, month and days
select name,
datediff(year,JoiningDate,getdate())
Year
,
datediff(year,JoiningDate,getdate())
month
,datediff(DAY,JoiningDate,getdate())
day
from Employee
where joiningdate
is
not
null
Calculate the age Sql server in years-month and days
Declare
@dateofbirth datetime
Declare @years
int
declare @months
int
declare @days
int
declare @temp
date
set @dateofbirth='1983-04-27';
set @temp
=@dateofbirth
set @years
=
(select
DATEDIFF(yy,
@temp,
GETDATE())-
CASE
WHEN
(MONTH(@dateofbirth)
>
MONTH(GETDATE()))
OR
(MONTH(@dateofbirth)
=
MONTH(GETDATE())
AND
DAY(@dateofbirth)
>
DAY(GETDATE()))
THEN 1
ELSE 0
END)
SET
@temp =
DATEADD(yy,
@years, @temp)
SET
@months =
DATEDIFF(m,
@temp,
GETDATE())
-
CASE
WHEN
DAY(@dateofbirth)
>
DAY(GETDATE())
THEN 1
ELSE 0
END
SET
@temp =
DATEADD(m,
@months, @temp)
SET
@days =
DATEDIFF(d,
@temp,
GETDATE())