我疯狂地试图快速完成这项功能。我在员工和经理之间有员工层级关系。这是我的功能
CREATE FUNCTION [dbo].[EmployeeHierarchy] (
@PeriodIds AS [pit].[PeriodIds] READONLY,
@EmployeeId int
)
RETURNS TABLE
AS
RETURN
(
WITH relation AS
(
SELECT @EmployeeId as EmployeeId, (SELECT MIN(PeriodId) FROM @PeriodIds) as PeriodId, 0 AS LEVEL
UNION ALL
SELECT r.EmployeeId, r.PeriodId, LEVEL + 1 AS LEVEL
FROM (SELECT EmployeeId, ManagerId, PeriodId FROM dbo.EmployeeManagerRelation) r
INNER JOIN relation T
ON r.ManagerId = T.EmployeeId
INNER JOIN @PeriodIds P
ON p.PeriodId = r.PeriodId
WHERE r.ManagerId <> r.EmployeeId
AND r.PeriodId = T.PeriodId
)
SELECT DISTINCT EmployeeId, LEVEL FROM relation
)
如果我在函数外运行它需要0秒但是一旦我调用该函数,它就需要永远。我重建索引,更新统计信息。我也执行这个命令:
DBCC DROPCLEANBUFFERS WITH NO_INFOMSGS;
DBCC FREEPROCCACHE WITH NO_INFOMSGS;
DBCC FREEPROCCACHE
但没有任何作用,任何想法是什么问题?如果它的参数嗅探,我不知道该怎么办,因为我不能创建变量,在它不是内联函数之前我也有同样的问题,我不知道该怎么办,因为其他客户端因此而混淆使用相同,但这不一致
这就是我调用函数的方式:
DECLARE @PeriodIds AS [pit].[PeriodIds]
INSERT INTO @PeriodIds
SELECT [PeriodId]
FROM dbo.[Period]
WHERE PeriodMonth = 1
and PeriodYear = 2015
SELECT EmployeeId FROM [dbo].[EmployeeHierarchy](@PeriodIds, 322)