DYNAMIC RESULT SETS 1
LANGUAGE SQL
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),
				 ProgramNameU  VARCHAR(256),
				 ProgramTypeID INTEGER,
				 OccurID       INTEGER,
				 AncestorID    INTEGER,
				 Ancestor      VARCHAR(256)
			) ON COMMIT PRESERVE ROWS
			  NOT LOGGED;

             INSERT INTO SESSION.programWithAlias (ProgramID, ProgramName, ProgramNameU, ProgramTypeID, OccurID, AncestorID, Ancestor)
             SELECT t.ProgramID, t.ProgramName, UPPER(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  sqt.TableName,
					            pgm.ProgramName,
					            st.Description,
					            COUNT(DISTINCT os.OccurID) AS stmtCount,
					            pgm.Ancestor,
								pth.PathStr
					     FROM StatementReference sr 
					            INNER JOIN OccurrencesStmt os ON sr.OccurID = os.OccurID
					            INNER JOIN Statements st ON os.StatementType = st.StatementType
					            INNER JOIN SESSION.programWithAlias pgm ON os.ProgID = pgm.ProgramID
					            INNER JOIN SqlTables sqt ON sr.ResourceID = sqt.SqlTableID
								LEFT OUTER JOIN
													 (
														SELECT  1 AS Flag,
																pgx.ProgramNameU, pgx.ProgramTypeID
														 FROM SESSION.programWithAlias pgx
														 GROUP BY pgx.ProgramNameU, pgx.ProgramTypeID
														 HAVING COUNT(*) > 1
													 ) x ON pgm.ProgramNameU = x.ProgramNameU AND pgm.ProgramTypeID = x.ProgramTypeID
							    LEFT OUTER JOIN Paths pth ON pth.PathID = os.PathID AND x.Flag = 1
					     WHERE  sr.ResourceType = 1
					            AND UPPER(sqt.TableName) IN (SELECT UPPER(Param) FROM SESSION.string_param_temp)
					     GROUP BY sqt.TableName,
					              pgm.Ancestor,
					              pgm.ProgramName,
					              st.Description,
								  pth.PathStr
					     ORDER BY sqt.TableName,
					              pgm.Ancestor,
					              pgm.ProgramName,
								  pth.PathStr,
					              st.Description;


				       OPEN crs;
				
                END;
				
		END;

		
END