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  SqlTables.TableName, JCLJob.JobName, pa.ProgramName, Program_Ancestor=pa.AncestorName, 
 Statements.Description, Count(OccurrencesStmt.OccurID) AS stmtCount, (pa.AncestorName + pa.ProgramName) as k, JCLJob.membername, Paths.PathStr 
FROM         JCLJob INNER JOIN  JCLStep ON JCLJob.JobID = JCLStep.JobID
				INNER JOIN ProgramsUsedInPgm ON ProgramsUsedInPgm.JclPgmID=JCLStep.CalledPgmID
				INNER JOIN #programWithAncestor pa  
				ON ProgramsUsedInPgm.ProgramID=pa.ProgramID
				INNER JOIN OccurrencesStmt ON OccurrencesStmt.ProgID = pa.ProgramID
				INNER JOIN Statements ON OccurrencesStmt.StatementType = Statements.StatementType
				INNER JOIN StatementReference ON StatementReference.OccurID = OccurrencesStmt.OccurID
				INNER JOIN SqlTables ON StatementReference.ResourceID = SqlTables.SqlTableID
				LEFT JOIN ( SELECT 1 AS Flag, p1.ProgramName, p1.ProgramTypeID	FROM  #programWithAncestor p1
					GROUP BY p1.ProgramName, p1.ProgramTypeID 	  HAVING COUNT(*) > 1) f 
					on pa.ProgramName = f.ProgramName and pa.ProgramTypeID = f.ProgramTypeID
				LEFT JOIN dbo.Paths ON Paths.PathID = OccurrencesStmt.PathID AND f.Flag = 1
 WHERE     JCLStep.CalledPgmID  > 0 AND StatementReference.ResourceType=1
  	AND (SqlTables.TableName in (Select * from #string_param_temp))
GROUP BY SqlTables.TableName, JCLJob.JobName, JCLJob.membername, pa.AncestorName, pa.ProgramName, Statements.Description, pa.ProgramTypeid, Paths.PathStr 
ORDER BY SqlTables.TableName, JCLJob.JobName, JCLJob.membername, k, Paths.PathStr , Statements.Description
