Wed, Jul
0 New Articles

Practical RPG: Work Files and EXTFILE

  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Sometimes the only answer to a problem is a work file, and ILE RPG makes it really easy to use one.


Work files aren't exactly sexy. With it being so easy to embed SQL into RPG, work files seem absolutely passé. Even back in the olden days, the joy of OPNQRYF allowed us to avoid the need for work files. (If you find yourself suddenly twitching and muttering to yourself, take a breath; this article is not about OPNQRYF!) Today we revisit the concept of work files and see where they still makes sense and just how easily they fit into the new world of ILE.


If They Didn't Want Us to Use Work Files…

…then they wouldn't have made them so darned easy to use! Seriously, the various nuances of the dcl-f specification make it so easy to use work files that you'll never need another OVRDBF (which was always a problem, especially with OPNQRYF). But before I delve into those capabilities, let's first discuss why you might need work files in the first place. It's true that the idea of small files being passed from one step of a job to another is out of fashion these days, and for the most part I agree with that sentiment. Happily, you no longer write data entry programs that dump data into a file only to be sorted using FMTDTA and sort specifications. (And if you were twitching over OPNQRYF, I can only imagine what FMTDTA did to you!) But the rise of SQL has given us situations where that old, hoary concept still has some real value.


Let's take the concept of a complex report. SQL is fantastic at joining and aggregating data, and as long as the data points exist to link the records, you should have no problem grabbing all the records using an SQL statement. And if that's all there was to the task, you could create an SQL cursor, spin through the data, and generate the report. But situations exist where that simply doesn't address the requirement.


The simplest case is when the data isn't printed but is instead directed to a file to be used later, either in an external reporting tool or simply to get pulled down by the user into a spreadsheet. Yes, you could generate a spreadsheet using one of the great tools out there (like Scott Klement's HSSF API), but the users may already have a spreadsheet where they simply want our data. Having a single file on the system in that case doesn't work because one user could wipe out another user's data. Instead, the easy answer is to create a work file unique by either name or member.


Another case occurs when you need more in-depth intermediate calculations than SQL is comfortable with. As an example, you may want to perform a complex data analysis that relies on prices. The goal is to find invoice lines for a certain customer where the actual price is significantly different from the expected price. You may need to look at several places (a customer-item record, a catalog, and a price agreements file) to determine whether there are price agreements in place before being able to get the expected price for a given order line. That's not something easily done in SQL, and even if it were, it probably wouldn't be the sort of thing you want to do for every row. Instead, you might grab all the item lines for the customer and stuff them into a work file. Then you run an RPG program to get the expected price for each line and at the same time calculate the percentage difference, updating columns in the work file. Finally, you create an SQL cursor to sort those records by percentage. Yes, this can all be done in SQL (the most extreme case being that you have to write a stored procedure to get the price), but the overhead could be quite extensive.


Note that I'm not advocating work files for every situation or even for a lot of them. I'm just saying that they can come in handy and that ILE RPG makes it particularly easy to handle them.


Using a Member

Case one is the simplest: add a new member. In your ILE RPG program, all you have to do is specify the EXTMBR keyword on the file specification. The trick is to get that member name into the program. This is the easiest technique:


      dcl-f WORKFILE keyed extmbr(iMbr);

      dcl-pi *n;

       iMbr char(10);



You create a file named WORKFILE in one of your primary database libraries. You add a member and add records to that member. You might use the job number or the user ID, or allow the user to specify a member. Whatever you do, keep track of the member and then pass it in to your RPG program as a parameter. By taking advantage of the EXTMBR keyword on the file specification, you can instruct RPG to open the appropriate member as specified in the input parameter.


Using a File in QTEMP

However, you probably know that members aren't exactly SQL-friendly. You have to run the ADDPFM command to add a member and then create an ALIAS to that member. The ALIAS sticks around forever until you drop it, as does the member. You can remove some of the permanence issues by using QTEMP, but if you're going to do that, I suggest simply moving to QTEMP in the first place. Create the file in QTEMP, either with the same name or a different name (which you choose depends on the application and to a lesser degree on your library list). Using the same name is the easiest. Here's the code for that technique:


      dcl-f WORKFILE keyed extfile('QTEMP/WORKFILE');


No parameters of any kind. The program will look specifically to QTEMP for the file regardless of your library list. You can of course simply set your library list correctly, and you won't even need the EXTFILE keyword. However, let's say you want to allow for a little more flexibility in the file name. Theoretically, you might want two different versions of the file that you can switch between.


      dcl-f WORKFILE keyed extfile(iFile);

      dcl-pi *n;

       iFile char(21);



In this case, you pass in the fully qualified named of the file rather than the member. No ALIAS is required. The name of the file is inconsequential; just make sure you pass it in qualified and blank-padded. For example, let's say you have two files, WORKFILE1 and WORKFILE2, in QTEMP. You can use 'QTEMP/WORKFILEA' as your input parameter to point to WORKFILE1 (and obviously change it to point to WORKFILE2). Just populate two copies of WORKFILE in QTEMP and then call this program with the appropriate value in the first parameter.


Variations on the Theme

The work file wouldn't have to be in QTEMP; it could be in another library but with a unique name. Or even a unique name and member; every combination can be used. Note, though, that these all require the name to be known when the program starts. What if you want to calculate the name dynamically? Here's a case where the member name is generated from the date.


      dcl-f WORKFILE keyed extmbr(wMbr) usropn;

      dcl-s wMbr char(10);


      wMbr = 'MBR' + %char(%date:*ymd0);

      open WORKFILE;


In this case, the program will attempt to open member MBRyymmdd, where yymmdd is today's date. Because the member name isn't known until after the program starts, you'll need to open the file manually; add the USROPN keyword to the file specification and then use the OPEN opcode to open the file once you've generated the member name.


When the Time Is Right…

As I said at the beginning, work files aren't often the right tool for the job, but in those cases where they fit the requirement, ILE RPG makes it very easy to implement them. And now that you know how to use work files, in subsequent articles I'll try to spend some time on how to generate them.

Joe Pluta

Joe Pluta is the founder and chief architect of Pluta Brothers Design, Inc. He has been extending the IBM midrange since the days of the IBM System/3. Joe uses WebSphere extensively, especially as the base for PSC/400, the only product that can move your legacy systems to the Web using simple green-screen commands. He has written several books, including Developing Web 2.0 Applications with EGL for IBM i, E-Deployment: The Fastest Path to the Web, Eclipse: Step by Step, and WDSC: Step by Step. Joe performs onsite mentoring and speaks at user groups around the country. You can reach him at This email address is being protected from spambots. You need JavaScript enabled to view it..

MC Press books written by Joe Pluta available now on the MC Press Bookstore.

Developing Web 2.0 Applications with EGL for IBM i Developing Web 2.0 Applications with EGL for IBM i
Joe Pluta introduces you to EGL Rich UI and IBM’s Rational Developer for the IBM i platform.
List Price $39.95

Now On Sale

WDSC: Step by Step WDSC: Step by Step
Discover incredibly powerful WDSC with this easy-to-understand yet thorough introduction.
List Price $74.95

Now On Sale

Eclipse: Step by Step Eclipse: Step by Step
Quickly get up to speed and productivity using Eclipse.
List Price $59.00

Now On Sale



Support MC Press Online


Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: