我可以在标量函数中使用公用表表达式(CTE)吗?
我试图使用它来获取单个浮点值,但始终为null
这是我的功能代码,用于计算每位员工的总工作时间:
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
上面的代码以正确的方式运行,如果我在一个查询中使用它(不在函数中),给我预期的结果,那么有什么不对?
答案 0 :(得分:2)
我找到了解决方案,这是一个小错误,我必须添加:
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
而不是:
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