Sun, Mar
0 New Articles

The API Corner: Monitoring Data Changes within Your Database

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


Triggers open up a world of possibilities in terms of what an application can do "under the covers."

Recently, over on Midrange.com, an absolutely wonderful resource run by David Gibbs for users and developers of the IBM i system, a developer reported having a problem related to using triggers. Basically, what he wanted to do was detect an update to a given file and then, unbeknownst to the application program performing the update, change the value of one or more fields within the updated record. This article is very loosely based on the response I provided to his problem. The "very loosely based" is essentially the difference between my posted 10-minute quick response and a 30-minute "let's dig a little deeper" answer.

Triggers, if you are not familiar with them, represent an exit point within the system where you can have an application program called whenever certain changes are made to a record within a file. The changes that can cause the program to be called can be inserting a new record, updating an existing record, deleting a record, or even just reading a record. Today, we'll look at what's required to write a trigger program to handle insert, update, and delete activity over a given file.

The file we will use for demonstration purposes is MYFILE. The DDS definition we'll use is this:

R MYRECORD              

  MYKEY         10A     

  MYCHARFLD     10A     

  MYPKDFLD       5P 0   

  MYZNDFLD       9S 0   

  MYINTFLD       9B 0   

K MYKEY                 

MYFILE is just a run-of-the-mill keyed physical file with a variety of data types (character, packed decimal, binary, etc.) in use for various fields. The file could be defined using DDS as shown or created using other mechanisms such as an SQL Create Table statement. Assuming the previous DDS is stored in member MYFILE of source file QDDSSRC, you can create the file using the Create Physical File (CRTPF) command as shown below.


Skipping over for the moment how we tell the system to call our trigger program when a given change to a record occurs, the system will pass the program two parameters. The first parameter contains information about the current operation (for instance, the name of the file being maintained, the type of operation update/write/delete/read, offsets within the parameter of where to find a copy of the original and/or new record being operated on, the original and/or new record, etc.) and the second parameter the length of the first parameter. These two parameters are introduced in the Knowledge Center under the topic How trigger programs work with specific layout definitions under Trigger buffer sections and Trigger buffer field descriptions. With these links as resources, here is our sample trigger program MYFILETRG.

h dftactgrp(*no)                                           


dMyFileTrg        pr                                       

d TrgBfr                              likeds(QDBTB)        

d LenTrgBfr                     10i 0 const                


dMyFileTrg        pi                                       

d TrgBfr                              likeds(QDBTB)        

d LenTrgBfr                     10i 0 const                


d BeforePtr       s               *                        

d Before        e ds                  qualified            

d                                     based(BeforePtr)     

d                                     extname(MYFILE)      


d AfterPtr        s               *                        

d After         e ds                  qualified            

d                                     based(AfterPtr)      

d                                     extname(MYFILE)      


d Insert          c                   '1'             

d Delete          c                   '2'             

d Update          c                   '3'             


d CalledAfter     c                   '1'             

d CalledBefore    c                   '2'             


 /copy qsysinc/qrpglesrc,trgbuf                       





     when TrgBfr.QDBFilN02 <> 'MYFILE';               

          dsply 'MyFileTrg called for wrong file';    


     when ((TrgBfr.QDBTT = CalledBefore) and          

           (TrgBfr.QDBTE = Insert));                  


          AfterPtr = %addr(TrgBfr) + TrgBfr.QDBNRO;   

          dsply ('Key ' + %trimr(After.MyKey) +                    

                 ' added. MyIntFld: ' +                            



     when ((TrgBfr.QDBTT = CalledBefore) and                       

           (TrgBfr.QDBTE = Update));                               


          BeforePtr = %addr(TrgBfr) + TrgBfr.QDBORO;               

          AfterPtr = %addr(TrgBfr) + TrgBfr.QDBNRO;                


          dsply ('Value before update: ' + %char(Before.MyPkdFld));

          dsply ('Value after update: ' + %char(After.MyPkdFld));  


          After.MyPkdFld += 1;                                     

          dsply ('Value after trigger: ' + %char(After.MyPkdFld)); 


     when ((TrgBfr.QDBTT = CalledBefore) and                       

           (TrgBfr.QDBTE = Delete));                               


          BeforePtr = %addr(TrgBfr) + TrgBfr.QDBORO;               

          dsply ('Key ' + %trimr(Before.MyKey) +        

                 ' deleted. MyZndFld: ' +               




          dsply ('MyFileTrg failure. Time: ' +          

                 TrgBfr.QDBTT +                          

                 ' Type: ' +                            





  *inlr = *on;                                          




The program defines the two parameters passed by the system when calling a trigger program as TrgBfr and LenTrgBfr. TrgBfr is defined as being LIKEDS(QDBTB) with QDBTB being an IBM-provided data structure definition (found in QSYSINC/QRPGLESRC, member TRGBUF) for the fixed location fields of the trigger buffer.

As this trigger program will be working with one specific file, MYFILE, it also defines two based data structures. These data structures, Before and After, correspond to the original and new record images, respectively. The data structures are defined using EXTNAME(MYFILE) so that RPG will generate the subfields of Before and After using the field descriptions of MYFILE. The data structures are basedusing pointer variables BeforePtr and AfterPtr, respectivelyso that the trigger program can directly access the before and after record images without having to move/substring the record values from where they are located in the TrgBfr parameter to non-based variables within the program.

For convenience, the program also defines five named constants. These constants provide for more meaningful reading/documentation of the program with, for instance, the constant 'Insert' corresponding to the value '1' of the Trigger Event (QDBTB subfield QDBTE, which documents that a '1' represents an Insert operation to the file).

The processing within the trigger program is quite straightforward. The program enters a SELECT group where it first checks if the file being passed is indeed MYFILE. If it isn't, an error message is DSPLYed.

If the trigger program has been called before an insert operation then AfterPtr is set to the address of the new record image by taking the address of the TrgBfr parameter and adding the offset to the copy of the record representing the new record (TrgBfr.QDBNRO). The value of the fields MyKey and MyIntFld are then DSPLYed.

If the trigger program has been called before an update operation, then BeforePtr is set to the address of the original record image by taking the address of the TrgBfr parameter and adding the offset to the copy of the record representing the original record (TrgBfr.QDBORO) and AfterPtr is set to the address of the new record image. The original value of MyPkdFld and the updated value of MyPkdFld are then DSPLYed. Recalling that the original request on Midrange was to update a field within the trigger program, the program then also adds 1 to the updated MyPkdFld value and DSPLYs this new value.

If the trigger program has been called before a delete operation, then BeforePtr is set to the address of the original record image, and the MyKey and MyIntFld values of what are being deleted are DSPLYed.

If the trigger program has been called for some OTHER reason than those handled by previous WHEN checks, then the program DSPLYs a failure message with the message, including the unexpected time and event values.

The program, having served its purpose, then ends.

Assuming the trigger program source is in member MYFILETRG of source file QRPGLESRC, you can create the program using this command:


Having created the trigger program, we'll now register MYFILETRG with the MYFILE file previously created. This registration is done using the Add Physical File Trigger (ADDPFTRG) command.

The two following commands will cause our trigger program to be called before any insert/write and delete operations on MYFILE, respectively.




This command will have our trigger program called after any insert/write activity on MYFILE:


This command will have our trigger program called before any update operations on MYFILE. In addition, the trigger program will be capable of changing the values of the MYFILE record prior to the system actually writing the updated record (the original request on Midrange). This ability to update record values is due to our specifying the ALWREPCHG(*YES) parameter value.


Now let's do some maintenance of file MYFILE.

For brevity, I'm going to use SQL to insert, update, and then delete a record from MYFILE. You could also use RPG file I/O, a utility such as DFU, or whatever means you normally use to maintain your databases.

Using STRSQL, I run the following SQL statements:

Insert into MyFile Values('A', 'TextA', 1, 2, 3) 

Update MyFile Set MyPkdFld = 13 where MyKey = 'A'

Delete from MyFile

When running the previous statements, several messages will be generated by the trigger program MYFILETRG. These messages will be:

DSPLY  Key A added. MyIntFld: 3 

DSPLY  MyFileTrg failure. Time: 1 Type: 1  

DSPLY  Value before update: 1             

DSPLY  Value after update: 13             

DSPLY  Value after trigger: 14            

DSPLY  Key A deleted. MyZndFld: 2          

The first and second messages are generated when the SQL INSERT statement is run. The first message is due to the WHEN operation with a trigger time (TrgBfr.QDBTT) of before and a trigger event (TrgBfr.QDBTE) of Insert. The second message is due to OTHER operation as none of the WHEN operations handle a trigger time of after and a trigger event of Insert.

The third, fourth, and fifth messages are generated when the SQL UPDATE statement is run. These DSPLYs are due to the WHEN operation with a trigger time of before and a trigger event of Update. The messages reflect the original value of MyPkdFld, the user application program updated value of MyPkdFld, and the trigger program updated value of MyPkdFld, respectively. If you happen to display MYFILE after the SQL UPDATE statement runs, you'll find that MyPkdFld is indeed set to 14 in the database.

The last message reflects when the SQL DELETE statement was run. The message is due to the WHEN operation with a trigger time of before and a trigger event of Delete.

Triggers are that simple to use, and they open up a world of possibilities in terms of what an application can do "under the covers." The approach taken with trigger program MyFileTrg is one way to implement a trigger. In future articles, we can look at other (to my way of thinking, more flexible) methods.

As usual, if you have any API questions, send them to me at This email address is being protected from spambots. You need JavaScript enabled to view it..

Bruce Vining

Bruce Vining is president and co-founder of Bruce Vining Services, LLC, a firm providing contract programming and consulting services to the System i community. He began his career in 1979 as an IBM Systems Engineer in St. Louis, Missouri, and then transferred to Rochester, Minnesota, in 1985, where he continues to reside. From 1992 until leaving IBM in 2007, Bruce was a member of the System Design Control Group responsible for OS/400 and i5/OS areas such as System APIs, Globalization, and Software Serviceability. He is also the designer of Control Language for Files (CLF).A frequent speaker and writer, Bruce can be reached at This email address is being protected from spambots. You need JavaScript enabled to view it.. 

MC Press books written by Bruce Vining available now on the MC Press Bookstore.

IBM System i APIs at Work IBM System i APIs at Work
Leverage the power of APIs with this definitive resource.
List Price $89.95

Now On Sale



Support MC Press Online

$0.00 Raised:

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: