DYNAMIC RESULT SETS 1
LANGUAGE SQL
BEGIN


          BEGIN


            DECLARE GLOBAL TEMPORARY TABLE SESSION.programWithAlias
			(
                 ProgramID     INTEGER,
				 ProgramName   VARCHAR(256),
				 ProgramTypeID INTEGER,
				 OccurID       INTEGER,
				 AncestorID    INTEGER,
				 Ancestor      VARCHAR(256)
			) WITH REPLACE 
              ON COMMIT PRESERVE ROWS
			  NOT LOGGED;

             INSERT INTO SESSION.programWithAlias (ProgramID, ProgramName, ProgramTypeID, OccurID, AncestorID, Ancestor)
             SELECT t.ProgramID, t.ProgramName, t.ProgramTypeID, t.OccurID, t.AncestorID, t.AncestorName
	         FROM TABLE(
			            fGetProgram_Ancestor_Aliases( CAST(NULL AS INTEGER) )
			         )t
			;

	            BEGIN


					    DECLARE crs CURSOR WITH RETURN FOR
						SELECT  DISTINCT
						        isr.SetName,
					            prg.ProgramName AS ProgramName,
					            st.Description AS Statement_Type,
					            COUNT(st.Description) AS Statement_Count,
					            prg.Ancestor,
								pth.PathStr
					     FROM StatementReference sr
					          INNER JOIN OccurrencesStmt os ON sr.OccurID = os.OccurID
					          INNER JOIN IdmsSubschemaSets isr ON sr.ResourceID = isr.ID
					          INNER JOIN SESSION.programWithAlias prg ON os.ProgID = prg.ProgramID
							  INNER JOIN Statements st ON sr.StatementType = st.StatementType
							  LEFT OUTER JOIN
													 (
														SELECT  1 AS Flag,
																pgx.ProgramName, pgx.ProgramTypeID
														 FROM SESSION.programWithAlias pgx
														 GROUP BY pgx.ProgramName, pgx.ProgramTypeID
														 HAVING COUNT(*) > 1
													 ) x ON prg.ProgramName = x.ProgramName AND prg.ProgramTypeID = x.ProgramTypeID
							  LEFT OUTER JOIN Paths pth ON pth.PathID = os.PathID AND x.Flag = 1
					     WHERE sr.ResourceType = 78
					     GROUP BY isr.SetName, prg.ProgramName, st.Description, prg.Ancestor, pth.PathStr
					     ORDER BY isr.SetName, prg.Ancestor, prg.ProgramName, pth.PathStr;

				         OPEN crs;
				
                END;

        END;
		
END	
