CREATE FUNCTION fnCalculateAge
(
@DOB DATETIME
)
RETURNS NVARCHAR(50)
AS
BEGIN
DECLARE @date DATETIME,
@years INT,
@months INT,
@days INT
SELECT @date = @DOB
SELECT @years = DATEDIFF(YEAR, @date, GETDATE()) - CASE WHEN (MONTH(@DOB) > MONTH(GETDATE())) OR (MONTH(@DOB) = MONTH(GETDATE()) AND DAY(@DOB) > DAY(GETDATE())) THEN 1 ELSE 0 END
SELECT @date = DATEADD(YEAR, @years, @date)
SELECT @months = DATEDIFF(MONTH, @date, GETDATE()) - CASE WHEN DAY(@DOB) > DAY(GETDATE()) THEN 1 ELSE 0 END
SELECT @date = DATEADD(MONTH, @months, @date)
SELECT @days = DATEDIFF(DAY, @date, GETDATE())
DECLARE @Age NVARCHAR(50)
SET @Age = Cast(@years AS NVARCHAR(4)) + ' Years ' + Cast(@months AS NVARCHAR(2))+ ' Months ' + Cast(@days AS NVARCHAR(2))+ ' Days Old'
RETURN @Age
End
SELECT dbo.fnCalculateAge('1990-03-20')'Your Age'
Your Age
|
26 Years 0
Months 1 Days Old
|
No comments:
Post a Comment