AS set NOCOUNT ON;
IF OBJECT_ID('tempdb..#programWithAncestor') IS NOT NULL DROP TABLE #programWithAncestor
			 SELECT * INTO #programWithAncestor 
			 FROM   fGetProgram_Ancestor_Aliases (NULL)

SELECT DISTINCT 
	pa.ProgramName AS ProgramName, 
	Count(distinct OccurrencesStmt.OccurID) AS CallCount, pa.AncestorName AS Ancestor, pa.ProgramID, pa.AncestorID
FROM (StatementReference RIGHT JOIN OccurrencesStmt ON StatementReference.OccurID=OccurrencesStmt.OccurID) 
RIGHT JOIN #programWithAncestor pa ON OccurrencesStmt.ProgID=pa.ProgramID
WHERE (StatementReference.ResourceType=5)
	And (pa.OccurID<>0)
	And (pa.ProgramID In (Select * from #numeric_param_temp))
GROUP BY pa.AncestorName, pa.ProgramName, pa.ProgramID, pa.AncestorID
ORDER BY pa.AncestorName, pa.ProgramName