DYNAMIC RESULT SETS 1
LANGUAGE SQL
ss: BEGIN

					    DECLARE crs CURSOR WITH RETURN FOR
						SELECT  pa.AliasName AS ProgramName,
					            f.LogicalName AS FileName,
					            st.Description AS Statement_Type,
					            COUNT(os.OccurID) AS Expr1,
					            prg.Ancestor,
								prg.ProgramID,
								x.ProgramID AS AncestorID,
					            (prg.Ancestor || pa.AliasName) AS k
					     FROM StatementReference sr
					            INNER JOIN OccurrencesStmt os ON sr.OccurID = os.OccurID
					            INNER JOIN Files f ON sr.ResourceID = f.FileID
					            INNER JOIN Programs prg ON os.ProgID = prg.ProgramID
								INNER JOIN ProgramAliases pa ON prg.ProgramID = pa.ProgramId AND pa.AliasType = 0
					            INNER JOIN Statements st ON sr.StatementType = st.StatementType
								LEFT OUTER JOIN
											 (
												 SELECT prax.AliasName AS ProgramName,
														prgx.ProgramID,
														prgx.ProgramTypeID
												 FROM ProgramAliases prax
													  INNER JOIN Programs prgx ON prax.ProgramId = prgx.ProgramID
												 WHERE prax.AliasType = 0
											  ) x ON prg.Ancestor = x.ProgramName
															   AND x.ProgramTypeID NOT IN (15, 16, 19)
					     WHERE sr.ResourceType = 9
					           AND (f.TypeCode <> 32 OR f.TypeCode IS NULL)
					           AND prg.ProgramTypeid NOT IN (9, 13, 19)
					     GROUP BY prg.Ancestor,
					              pa.AliasName,
								  prg.ProgramID,
								  x.ProgramID,
					              f.LogicalName,
					              st.Description
					     ORDER BY k,
						          prg.ProgramID,
					              f.LogicalName;
						
						
				        OPEN crs;
				

END ss	




