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

SELECT Programs_1.ProgramName AS l, pa.ProgramName as k, StatementReference.StartRow as m, Programs_1.ProgramTypeID as n, pa.ProgramID as i
FROM #programWithAncestor pa
INNER JOIN OccurrencesStmt ON pa.ProgramID = OccurrencesStmt.ProgID INNER JOIN StatementReference ON OccurrencesStmt.OccurID = StatementReference.OccurID
INNER JOIN #programWithAncestor AS Programs_1 ON StatementReference.ResourceID = Programs_1.ProgramID
INNER JOIN Occurrences on Occurrences.OccurID=pa.OccurID INNER JOIN Paths on Occurrences.PathID=Paths.PathID
WHERE (StatementReference.ResourceType = 5)
AND Programs_1.OccurID=0
AND pa.OccurID <> 0
AND (pa.AncestorName is null OR pa.AncestorName='')
AND (pa.ProgramID in (Select * from #numeric_param_temp))
AND (Programs_1.ProgramTypeID <> -1
	 OR ( Programs_1.ProgramTypeid=-1
	 		and StatementReference.StartRow not in (SELECT DISTINCT StartRow FROM #calling_temp 
			WHERE ProgramName = pa.ProgramName AND Ancestor = pa.AncestorName AND PathStr=Paths.PathStr)
	    )
	)
UNION
SELECT Programs_1.ProgramName AS l, pa.AncestorName as k, StatementReference.StartRow as m, Programs_1.ProgramTypeID as n, Programs_1.ProgramID as i
FROM #programWithAncestor pa
INNER JOIN OccurrencesStmt ON pa.ProgramID = OccurrencesStmt.ProgID INNER JOIN StatementReference ON OccurrencesStmt.OccurID = StatementReference.OccurID
INNER JOIN #programWithAncestor AS Programs_1 ON StatementReference.ResourceID = Programs_1.ProgramID
INNER JOIN Occurrences on Occurrences.OccurID=pa.OccurID INNER JOIN Paths on Occurrences.PathID=Paths.PathID
WHERE (StatementReference.ResourceType = 5)
AND Programs_1.OccurID=0
AND pa.OccurID <> 0
AND pa.AncestorName is not null AND pa.AncestorName <> '' AND pa.ProgramTypeID in (15,16)
AND (pa.ProgramID in ( select DISTINCT p1.programid from programs as p1 , ProgramAliases as p2 where p1.ancestor=p2.AliasName 
and p2.ProgramId in (Select * from #numeric_param_temp)
))
AND (Programs_1.ProgramTypeID <> -1
	 OR ( Programs_1.ProgramTypeid=-1
	 		and StatementReference.StartRow not in (SELECT DISTINCT StartRow FROM #calling_temp 
			WHERE ProgramName = pa.ProgramName AND Ancestor = pa.AncestorName AND PathStr=Paths.PathStr)
	    )
	)
ORDER BY n, l, k,i, m
