DYNAMIC RESULT SETS 1
LANGUAGE SQL
ss: BEGIN

-- clean up temp table if exists 
		BEGIN
			DECLARE CONTINUE HANDLER FOR SQLSTATE '42704'
			BEGIN END;
			
			COMMIT;
			DROP TABLE SESSION.programWithAlias;
			
		 END;


          BEGIN


            DECLARE GLOBAL TEMPORARY TABLE SESSION.programWithAlias
			( 
                 ProgramID     INTEGER,
				 ProgramName   VARCHAR(256),
				 ProgramTypeID INTEGER,
				 OccurID       INTEGER,
				 AncestorID    INTEGER,
				 Ancestor      VARCHAR(256)
			) 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.RecordName,
					            prg.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 IdmsSubschemaRecords 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 = 77
					     GROUP BY isr.RecordName, prg.ProgramName, st.Description, prg.Ancestor, pth.PathStr
					     ORDER BY isr.RecordName, prg.Ancestor, prg.ProgramName, pth.PathStr; 

				         OPEN crs;
				END;

        END;				
				

END ss	




