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  mq.QueueName,
						        pa.ProgramName,
	                            st.Description,
	                            COUNT(os.OccurID) AS StmtCOUNT,
								pth.PathStr
					     FROM   StatementReference sr
					             INNER JOIN MQQueues mq ON sr.ResourceID = mq.QueueID
					             INNER JOIN OccurrencesStmt os ON sr.OccurID = os.OccurID
								 INNER JOIN SESSION.programWithAlias pa ON os.ProgID = pa.ProgramId 
					             INNER JOIN Statements st ON sr.StatementType = st.StatementType
								 LEFT OUTER JOIN
							                 (
							                    SELECT  1 AS Flag,
										                pgx.ProgramName,
										                pgx.ProgramTypeID
										         FROM Programs pgx
										         GROUP BY pgx.ProgramName, pgx.ProgramTypeID
										         HAVING COUNT(*) > 1
											 ) x ON pa.ProgramName = x.ProgramName
											        AND pa.ProgramTypeID = x.ProgramTypeID
							  LEFT OUTER JOIN Occurrences occ ON occ.OccurID = pa.OccurID						
							  LEFT OUTER JOIN Paths pth ON 	pth.PathID = occ.PathID AND x.Flag = 1
					     WHERE sr.ResourceType = 81
						       AND UPPER(mq.QueueName) IN (SELECT UPPER(Param) FROM SESSION.string_param_temp) 
					     GROUP BY pa.ProgramName,
					              mq.QueueName,
					              st.Description,
								  pth.PathStr
					     ORDER BY  mq.QueueName, pa.ProgramName, pth.PathStr ;

				         OPEN crs;
				
                END;
				
		END;
		
END ss	



