- CREATE function dbo.Age
- (@dob datetime)
- returns varchar(50)
- as
- BEGIN
- DECLARE @date datetime, @tmpdate datetime, @years int, @months int, @days int
- DECLARE @Age varchar(50)
- set @Age=''
- SELECT @tmpdate = @dob
-
- SELECT @years = DATEDIFF(yy, @tmpdate, GETDATE()) - CASE WHEN (MONTH(@dob) > MONTH(GETDATE())) OR (MONTH(@dob) = MONTH(GETDATE()) AND DAY(@dob) > DAY(GETDATE())) THEN 1 ELSE 0 END
- SELECT @tmpdate = DATEADD(yy, @years, @tmpdate)
- SELECT @months = DATEDIFF(m, @tmpdate, GETDATE()) - CASE WHEN DAY(@dob) > DAY(GETDATE()) THEN 1 ELSE 0 END
- SELECT @tmpdate = DATEADD(m, @months, @tmpdate)
- SELECT @days = DATEDIFF(d, @tmpdate, GETDATE())
-
- set @Age=convert(varchar(50),@years)+' Years '+convert(varchar(50),@months)+' Months '+convert(varchar(50),@days)+' Days';
- return @Age
- END
Function Execution:
- select dbo.Age('1992-08-22')
Result:
22 Years 10 Months 21 Days