ALTER FUNCTION [dbo].[GetDurationYear_Month_Day]
(
@FromDate DATETIME, @ToDate DATETIME
)
RETURNS NVARCHAR(300)
AS
BEGIN
DECLARE @date datetime, @tmpdate datetime, @years int, @months int, @days int
Declare @currentdatetime datetime
--SELECT @date = '15-Jun-1986'
set @date = @FromDate
set @currentdatetime = @ToDate
--SELECT
-- @date = REPLACE(CONVERT(Date,e.DateOfBirth,103),' ','-'),
-- @currentdatetime = REPLACE(CONVERT(Date,e.FirstJoiningDate,103),' ','-')
-- FROM Employee as e WHERE e.EmployeeId = 26380 --12390
SELECT @tmpdate = @date
SELECT @years = DATEDIFF(yy, @tmpdate, @currentdatetime) - CASE WHEN (MONTH(@date) > MONTH(@currentdatetime)) OR (MONTH(@date) = MONTH(@currentdatetime) AND DAY(@date) > DAY(@currentdatetime)) THEN 1 ELSE 0 END
SELECT @tmpdate = DATEADD(yy, @years, @tmpdate)
SELECT @months = DATEDIFF(m, @tmpdate, @currentdatetime) - CASE WHEN DAY(@date) > DAY(@currentdatetime) THEN 1 ELSE 0 END
SELECT @tmpdate = DATEADD(m, @months, @tmpdate)
SELECT @days = DATEDIFF(d, @tmpdate, @currentdatetime)
RETURN CAST(@years AS VARCHAR(4)) + '-' + CAST(@months AS VARCHAR(4)) + '-' + CAST(@days AS VARCHAR(4))
END
No comments:
Post a Comment