1
我可以在標量函數中使用公共表表達式(CTE)嗎?標量函數中的CTE
我試圖用它來得到一個浮點值,但始終是空
這裏是我的功能代碼,每名員工計算總的工作時間:在
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
上面的代碼運行正確的方式,並給我預期的結果,如果我在單個查詢中使用它(不在函數中),那麼有什麼問題?
是的,爲什麼不呢?我還有一個問題:爲什麼你沒有嘗試過呢? –
我做了一個小小的研究,他們都在討論僅在表值函數中使用它..我嘗試使用它已經獲得單個值,但值始終爲空 –
是的,你可以。如果您遇到問題,請發佈您的SQL和預期結果。 – fez