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

SELECT SqlTables.TableName,  
 pa.ProgramName, 
 Statements.Description,
 Count(DISTINCT OccurrencesStmt.OccurID) AS stmtCount, pa.AncestorName, Paths.PathStr
FROM (
          (
             (
              StatementReference INNER JOIN OccurrencesStmt ON StatementReference.OccurID = OccurrencesStmt.OccurID
             ) INNER JOIN Statements ON OccurrencesStmt.StatementType = Statements.StatementType
          ) INNER JOIN #programWithAncestor pa 
					ON OccurrencesStmt.ProgID = pa.ProgramID
        ) INNER JOIN SqlTables ON StatementReference.ResourceID = SqlTables.SqlTableID
		 LEFT JOIN ( SELECT 1 AS Flag, ProgramName, ProgramTypeID	FROM #programWithAncestor
					GROUP BY ProgramName, 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 (StatementReference.ResourceType = 1 AND (SqlTables.TableName in (Select * from #string_param_temp)))
GROUP BY SqlTables.TableName, pa.AncestorName, pa.ProgramName, Statements.Description, Paths.PathStr
ORDER BY SqlTables.TableName, pa.AncestorName, pa.ProgramName, Paths.PathStr, Statements.Description