This function return is a single float value, but it always is null. Why?
Function to calculate the total working hour per employee:
ALTER FUNCTION GetTotalWorkingHour
(
@StartDate datetime,
@EndDate datetime,
@EmpID nvarchar(6) = null
)
RETURNS float
AS
BEGIN
DECLARE @Result float;
WITH
CTE_Start
AS
(
SELECT EmpID ,SUM(DATEDIFF(minute, (CAST(att.[date] AS datetime) + att.[Time]), @StartDate) *
CASE WHEN Funckey = 'EMPIN' THEN +1 ELSE -1 END) AS SumStart
FROM PERS_Attendance AS att
WHERE (EmpID = @EmpID OR @EmpID IS NULL) AND att.[date] < @StartDate GROUP BY EmpID
)
,CTE_End
AS
(
SELECT EmpID ,SUM(DATEDIFF(minute, (CAST(att.[date] AS datetime) + att.[Time]), @EndDate) * CASE WHEN Funckey = 'EMPIN' THEN +1 ELSE -1 END) AS SumEnd
FROM PERS_Attendance AS att
WHERE (EmpID = @EmpID OR @EmpID IS NULL) AND att.[date] < @EndDate GROUP BY EmpID
)
SELECT @Result =
(CTE_Start.SumStart - ISNULL(CTE_End.SumEND, 0) / 60.0) --AS SumHours
FROM
CTE_End
LEFT JOIN CTE_Start ON CTE_Start.EmpID = CTE_End.EmpID
RETURN @Result
END
GO
the above code run in a correct way and give me the expected result if i use it in a single query(not in function), so what's wrong?
i found the solution, it was a small bug, i must add:
SELECT @Result =
(SumEnd - ISNULL(SumStart, 0)) / 60.0 --AS SumHours
FROM
CTE_End
LEFT JOIN CTE_Start ON CTE_Start.EmpID = CTE_End.EmpID
RETURN @Result
instead of:
SELECT @Result =
(CTE_Start.SumStart - ISNULL(CTE_End.SumEND, 0) / 60.0) --AS SumHours
FROM
CTE_End
LEFT JOIN CTE_Start ON CTE_Start.EmpID = CTE_End.EmpID
RETURN @Result
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