I'm getting crazy trying to make this function fast. I have an employee hierarchy relation between employee and manager. Here is my function
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
)
If I run this outside the function it takes 0 seconds but as soon as I call the function, it takes forever. I rebuild indexes, update statistics. I also execute this commands:
DBCC DROPCLEANBUFFERS WITH NO_INFOMSGS;
DBCC FREEPROCCACHE WITH NO_INFOMSGS;
DBCC FREEPROCCACHE
But nothing works, any idea what's the issue? If it's parameter sniffing, I don't know what to do because I can't create variables, before it wasn't an inline function and I have same issue, I don't know what to do, it's confuse because so other clients use the same but this is not consistent
This is how I call the function :
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)