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  pgm.ProgramName,
						                 isss.SetName,
						                 st.Description AS Statement_Type,
						                 COUNT(st.Description) AS Statement_Count,
						                 pgm.Ancestor,
										 pgm.ProgramID,
										 pgm.AncestorID
						     FROM StatementReference sr
						            INNER JOIN OccurrencesStmt os ON sr.OccurID = os.OccurID
						            INNER JOIN SESSION.programWithAlias pgm ON os.ProgID = pgm.ProgramID
						            INNER JOIN Statements st ON sr.StatementType = st.StatementType
						            INNER JOIN IdmsSubschemaSets isss ON sr.ResourceID = isss.ID
						     WHERE sr.ResourceType = 78
						     GROUP BY pgm.Ancestor,
						              pgm.ProgramName,
						              isss.SetName,
						              st.Description,
									  pgm.ProgramID,
									  pgm.AncestorID
						     ORDER BY pgm.Ancestor,
						              pgm.ProgramName,
									  pgm.ProgramID,
						              isss.SetName,
						              st.Description;

				      OPEN crs;
					  
				END;
         				
		END;		

END ss	


