Possible Duplicate:
How to calculate age in T-SQL with years, months, and days
On a project I was working on, I was required to calculate a persons age when they join the system; after looking on the internet I found various ways this could be done, but most of them had slight issues when it involved a Leap-Year.
The solution below is how I calculate number of years past / age. Hope this helps others
You need to add the following method to your database:
CREATE FUNCTION [dbo].[fnCalAge] (@DiffFrom DATE, @DiffTo DATE) RETURNS INT
AS
BEGIN
DECLARE @NumOfYears INT
SET @NumOfYears = (SELECT
DATEDIFF(YEAR, @DiffFrom, @DiffTo) +
CASE
WHEN MONTH(@DiffTo) < MONTH(@DiffFrom) THEN -1
WHEN MONTH(@DiffTo) > MONTH(@DiffFrom) THEN 0
ELSE
CASE WHEN DAY(@DiffTo) < DAY(@DiffFrom) THEN -1 ELSE 0 END
END)
IF @NumOfYears < 0
BEGIN
SET @NumOfYears = 0;
END
RETURN @NumOfYears;
END
You then call it in your SQL Query, similar to the following:
SET DATEFORMAT dmy
SELECT dbo.fnCalAge(CAST('20/06/1987' AS DATE), CAST('20/06/2013' AS DATE))
assuming @bDate is datetime of birthdate and @today is todays date, then...
Declare @bDay Date = '31 dec 2000'
Declare @today Date = cast(getdate() as date)
Select datediff(Year, @bDay, @today) -
case When datepart(dayofYear, @today) <
datepart(dayofYear, @bDay) Then 1 Else 0 End
Replace hiredate with DOB for age. Replace sysdate with your date such as to_date('28-DEC-2012') :
SELECT empno, ename, hiredate, TRUNC(MONTHS_BETWEEN(sysdate, hiredate)/12) years_of_service
FROM scott.emp
/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With