All sorts of steps you have to do in RPG. This can be done in SQL a variety of simpler ways. SQL is adept at processing and analyzing groups of records in an entire file all at once.
CREATE TABLE zaddresses AS
( SELECT *
FROM addressFile
WHERE cust IN (SELECT cust
FROM orderHistory
GROUP BY cust
HAVING max(sufix)='000'
)
)
WITH DATA
NOT LOGGED INITIALLY;
CREATE TABLE zorderHst AS
( SELECT *
FROM orderHistory
WHERE cust IN (SELECT cust
FROM zaddresses
)
)
WITH DATA
NOT LOGGED INITIALLY;
There, you've defined your holding table and populated it in one single statement each. It does have some nested logic, but nonetheless only two statements.
To purge them
DELETE FROM addressfile
WHERE cust IN (SELECT cust FROM zaddresses);
DELETE FROM orderHistory
WHERE cust IN (SELECT cust FROM zaddresses);
A grand total of four SQL statements. (I wont even ask how many you'd have in your RPG program)
Once you understand SQL, you can think about processing entire files, not just record by record instructions. It's much simpler to get things done, and it's almost always faster when done well.
(You may hear arguments about performance under particular circumstances, but most often they simply aren't using SQL as well as they should. If you write poor RPG, it performs badly too. ;-)