13
Wed, Nov
5 New Articles

Exploring a Few More Complex Trigger Scenarios

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

In order to make a "trigger happy" database, let's explore a few more complex scenarios.

By Rafael Victória-Pereira

Creating simple triggers was covered in Introducing Database Triggers, and the introduction to complex trigger scenarios was presented in Exploring More Complex Trigger Scenarios. Let's cover a few more scenarios and review what you've learned.

Editor's Note: This article is excerpted from chapter 9 of SQL for IBM i: A Database Modernization Guide, by Rafael Victória-Pereira.

Using Triggers to Compose and Fill Columns

This time the request for help didn’t come from the Dean’s office, for a change. The manager of one of the university’s Web applications (who happens to be the Dean’s niece) asked for our help in preventing “that awful content” from being displayed by the application she manages. After a quick chat, we figured out that those “N/A” default values that we assigned to certain text columns were the cause of her discomfort. We could simply alter the default values and be done with it, but let’s take this opportunity to do something else with triggers: we’re going to compose and fill a column if, and only if, certain conditions are met. This is not a case of “change a column whenever the record is updated.” It’s a bit more refined than that, but still simple enough to follow and reproduce in similar (and potentially more complex) scenarios you will find in your own applications.

Let’s start with something simple: the Departments table contains one of those “N/A” filled columns: the department description. Earlier in this chapter, you saw how to condition the activation of a trigger, so the code for this trigger should be fairly easy to understand:

Exploring Even More Complex Trigger Scenarios - Figure 1

While the declaration of the trigger and the rest of the “header” should be familiar by now, the body (the line between the BEGIN and END statements) might confuse you, because you’re looking at a change of a column’s value. Don’t worry: there’s no INSERT or UPDATE action following it. That’s because the INSERT/UPDATE is not necessary. Note that the trigger is activated before the update takes place. This means that any changes made to the table’s columns values will be made final when the trigger ends and the actual UPDATE operation is performed. That’s why there’s a SET statement in the body of the trigger, but no UPDATE statement following it.

However, if this was all you could do, it wouldn’t be very useful! In a real-life scenario, you might want to use more complex values—computed or composed using other columns’ values, for instance.

Let’s see how that works with a trigger that replaces the “N/A” of the Courses table’s Description column with some nicely composed text: “A <department name> department course, managed by <Teacher Rank> <Teacher Name>.” This trigger is a bit longer and complex, but it follows the same basic principles as the previous one. The difference is that there are some parts of the description that come from other tables. I’ll show you how that translates to code in a moment, but first, let’s look at the trigger’s header part:

Exploring Even More Complex Trigger Scenarios - Figure 2

It’s very similar to the previous one. Actually, the only change is the table name, which went from TBL_Departments to TBL_Courses. The next part is the body of the trigger, where all the real action takes place. It starts with the declaration of the variables, which will temporarily hold the names of the department, rank, and teacher:

Exploring Even More Complex Trigger Scenarios - Figure 3

Then comes the code to fill each of these variables with the necessary information, based on the Course Director and Course Department ID columns:

Exploring Even More Complex Trigger Scenarios - Figure 4

Here, I’m using SELECT ... INTO statements to fill the variables with the appropriate information. I could store the teacher rank and name in the same variable, but I chose not to overcomplicate the SELECT statements.

The next step is to fill in the new description, just like I did in the previous example. The difference is this time around I’m going to compose the new value using the variables above:

Exploring Even More Complex Trigger Scenarios - Figure 5

This code is available in the chapter’s downloadable source code, along with working examples of both this and the previous triggers in action. Even though I didn’t show it, you can also perform the same type of changes on numeric columns. You can use all of SQL’s power, including UDFs, to compute or compose a column’s new value.

Using what I presented in this section, you should be able to create your own column- value–changing triggers. If you need additional practice, find all the columns with the “N/A” default value and build triggers to change them appropriately!

Using INSTEAD OF Triggers to Supercharge Views

Views are a great way to hide the database complexity from the user, because they offer a much simpler structure. With a view, you can gather information from as many tables as you’d like and display them as if they all belonged to the same table. But so far, that’s the only thing you can do with views: display information.

However, you can use INSTEAD OF triggers to supercharge your views, or, in other words, allow the users to use those views to insert, update, or delete records in the underlying tables. Back in Chapter 5, I created a view named Student Information View. In case you don’t remember, here is its source code:

Exploring Even More Complex Trigger Scenarios - Figure 6

This view takes information from the Students and Persons tables and displays it to the user, as if all belonged to the same table. Let’s start by creating a trigger that allows the user to update most of the information from the view. I say most because the majority of the columns in this view are from the Persons table. The only two that are not are the student’s ID and status. An INSTEAD OF trigger can only be created over a view, and you need to specify the operation that activates the trigger.

Let’s look at the source code of the trigger that will enable the UPDATE operation over this view, piece by piece, as usual, starting with the “header” part:

Exploring Even More Complex Trigger Scenarios - Figure 7

Apart from the INSTEAD OF UPDATE ON UMADB_CHP5.VIEW_STUDENT_INFO part, it looks pretty standard. The important thing to understand here is that this line tells the database engine to execute the code in the body of the trigger instead of (hence the name of the trigger type) failing the statement and returning an error, which would be the case in a view without such a trigger. In this particular case, what I want is that the columns from the Persons table receive the values specified in an UPDATE statement over the View_ Student_Info view. For that to happen, the body of my trigger has to “tell” the database engine what to do. In this case, it must map the view columns to the respective Persons table columns in an UPDATE statement, which here is rather simple, because the columns have the same names, as you can see in the body of the trigger:

Exploring Even More Complex Trigger Scenarios - Figure 8

However, there is a small intermediate step: finding the right Person ID. This is necessary because the view doesn’t have the Person ID, which means that I have to get it from somewhere. In this case, I’ll use the Person ID from the Students table (Tbl_ PersonsPerson_Id). I’ll store it in a temporary variable named W_Person_Id, which I’ll then use in the UPDATE statement. Also note that the UPDATE statement is simply mapping the view columns (prefixed UPDATED.) to the respective Persons table columns (prefixed PERSONS.).

In summary, what’s happening here is that I’m telling the database engine that when someone tries to update a view (which is not possible under normal circumstances), it should update a table instead. More specifically, I’m telling the database engine that an UPDATE statement issued over the View_Student_Info view actually updates the TBL_ Persons table, using the UPDATE statement in the trigger’s body section.

Let’s try it! Say I want to change the name of the student with the ID equal to 1 from “Dalton, Joe” to “Dalton, Jack”. With this trigger in place, I can use the student information view to do that:

Exploring Even More Complex Trigger Scenarios - Figure 9

The database engine will note that I’m trying to update a view, so it will check for INSTEAD OF triggers for this operation. It will find our newly created TRG_Update_ View_Student_Info trigger, which will take over and issue an UPDATE over the Persons table instead. For the end user, this is totally transparent. It’s yet another way to hide complexity—and you can use it for INSERT and DELETE statements as well.

Now let’s see a slightly more complex example. Chapter 5’s code also included another view: Course Information. This is a more complete and complex view, spanning four tables (whereas the Teachers and Persons table are used twice), showing a lot of course-related information that is not actually part of the Courses table. Here’s the view’s source code:

Exploring Even More Complex Trigger Scenarios - Figure 10

Note that to display both the course director and teaching assistant’s names, the SELECT statement uses the Persons and Teachers tables with different aliases. This is an important detail to consider when building the trigger, which will allow us to update that view. In the end, I want to be able to update the Courses table’s Name and Description columns, or the Department’s Name column, or the Teacher and TA’s Name columns, stored in the Courses, Departments, and Persons tables, respectively.

Given that we’re talking about quite a few tables here, it’s a good idea to devise a mechanism that limits the updates to the bare minimum. In other words, it’s a good idea to issue an UPDATE statement if the value of the respective table was actually changed. For instance, it doesn’t make sense to execute an UPDATE statement over the Departments table if the department name wasn’t changed. It’s also important to mention that even though the Course ID is a column of the view, it doesn’t make much sense to change it, because it’s an ID column, generated automatically by the database engine.

Having said that, let’s start dissecting the code! Because the header part is very similar to the previous trigger’s, I’ll show it with the first part of the trigger’s body:

Exploring Even More Complex Trigger Scenarios - Figure 11

This piece of code is nearly the same as the previous trigger’s (I actually copy-pasted it and did some changes). The main difference is that there are three temporary variables instead of just one. This is because of the tables that the trigger will have to update. Let’s see how each of these variables is set:

Exploring Even More Complex Trigger Scenarios - Figure 12

It’s a long statement, but it’s not very complicated. Still, let’s review it in detail. The main table is the Courses table, which I’m accessing using the Course_Id column from the view to get the data that will let me connect to the other tables. Once I have the appropriate Courses record, I can use its TBL_DepartmentsDepartment_Id to get the link to the Departments table and store that value in the W_Department_Id temporary variable. That’s the easy part.

The course director and teaching assistant (TA) names are a bit more complicated, because the Courses record only stores the respective teacher IDs. However, the names of the teachers are not stored in the Teachers table, but in the Persons table, so I need to access the respective record from the Persons table. How? Via the TBL_PersonsPerson_Id of the Teachers table. The tricky part is that I need to do this twice: for the course director and the teaching assistant. That’s why I’m using the Teachers and Persons tables twice, with different aliases (DIRECTOR and DIRECTOR_PERSON for the Course Director, and TA and TA_PERSON for the Teaching Assistant). This will allow me to store the respective person IDs in the W_Course_Director_Person_Id and W_Course_TA_Person_Id temporary variables.

If you look at the previous trigger, you’ll see that the next step is to perform the update. However, this situation is a bit more complex, because I have more than one table, and I want to limit the updates to the bare minimum. To do that, I’ll check if the column’s value was actually changed, by comparing the before and after values for the respective column. If they are different, I’ll issue the respective UPDATE statement. Let’s see how that translates to code, using the Department Name:

Exploring Even More Complex Trigger Scenarios - Figure 13

As you see in this piece of code, the before and after values are stored in the ORIGINAL and UPDATED records, respectively. Checking whether the department name was changed is a simple thing to do, with this statement:

Exploring Even More Complex Trigger Scenarios - Figure 14

If this comparison returns true, then I issue my UPDATE statement, just like I did in the previous trigger. The rest of the code is simply a rehash of this idea, with the necessary adjustments to make it work for the rest of the columns:

Exploring Even More Complex Trigger Scenarios - Figure 15

Here you see how and where those temporary variables are used: they serve the sole purpose of finding the right record to update in the respective tables. Keep in mind that this is not a real-life example, because I’m updating columns from other tables without performing any checks. That sort of validation will be discussed in the next chapter. For now, I just wanted to show you a more complex example of an INSTEAD OF trigger with multiple updates, performed selectively.

Use Triggers with Care

Because this last trigger probably left your head spinning, I won’t hammer you with more code. Instead, I want to share a few notions about triggers that you must always remember when creating or changing existing triggers.

Triggers Are Like Salt

Triggers are like salt or any other condiment: if you use just enough it helps, but adding too much will ruin everything. This is particularly true in two different aspects: performance and control. From a performance perspective, you have to keep in mind that a trigger is another piece of code that will be executed whenever the operation that activated runs. For instance, inserting 1,000 rows in a table with a trigger with a for each row definition will cause the execution of that trigger 1,000 times! Even worse, this trigger’s actions can affect other tables, which in turn may have triggers of their own, causing “trigger storms” or “trigger cascades.”

This brings us to the aspect of control. Triggers are not always obvious, and most people tend to look for problems in applications or “regular” SQL routines (read: SPs and UDFs) when something is not working as it should. Triggers can be stealthy, so it’s important to have them well documented in terms of functionality and scope. My advice is that you keep your triggers’ source code along with the other SQL routines’ sources, preferably in a QSQLSRC file in your sources library, or whichever version of it you use.

The cascading triggers also make debugging a bit more difficult, because they might change column values in unexpected ways or, even worse, prevent modifications without warning. They can also lead to unexpectedly locked objects or, in a nightmarish scenario, unexplainable deadlocks. Keeping strict control over your triggers and, most importantly, defining a (company/shop-wide) proper and strict trigger usage policy is of paramount importance.

However, don’t get me wrong: I’m not suggesting that you shouldn’t use triggers. I’m just saying that you should use just enough of them—like salt.

In these articles, you’ve learned ...

I don’t know how many times I wrote the word “trigger,” but it sure was a lot. I couldn’t have done it any other way, because triggers were the focus of this chapter. Let’s review what was discussed:

  • I explained what triggers are and why you should use
  • I explained the anatomy of a trigger, detailing each
  • I presented a handful of “regular” trigger examples, as well as trigger usage scenarios (data validation, auditing, and automated composition/filling of information).
  • Then I explained the INSTEAD OF trigger philosophy and how to use these special triggers to make views updatable.
  • Finally, I presented a few reasons you should be careful with the use of triggers.

As a final note, let me add that there’s a lot more to know about triggers. I barely scratched the surface. The idea was to introduce this tool without overwhelming you with all the technical details. You can consider this the minimum working knowledge you need to use triggers. However, if you really want to use them on a large scale, consider reading more about this topic. IBM has a great Redbook covering this and other SQL- related topics: Stored Procedures, Triggers, and Functions in DB2. Look it up: it’s very informative!

 

Rafael Victoria-Pereira

Rafael Victória-Pereira has more than 20 years of IBM i experience as a programmer, analyst, and manager. Over that period, he has been an active voice in the IBM i community, encouraging and helping programmers transition to ILE and free-format RPG. Rafael has written more than 100 technical articles about topics ranging from interfaces (the topic for his first book, Flexible Input, Dazzling Output with IBM i) to modern RPG and SQL in his popular RPG Academy and SQL 101 series on mcpressonline.com and in his books Evolve Your RPG Coding and SQL for IBM i: A Database Modernization Guide. Rafael writes in an easy-to-read, practical style that is highly popular with his audience of IBM technology professionals.

Rafael is the Deputy IT Director - Infrastructures and Services at the Luis Simões Group in Portugal. His areas of expertise include programming in the IBM i native languages (RPG, CL, and DB2 SQL) and in "modern" programming languages, such as Java, C#, and Python, as well as project management and consultancy.


MC Press books written by Rafael Victória-Pereira available now on the MC Press Bookstore.

Evolve Your RPG Coding: Move from OPM to ILE...and Beyond Evolve Your RPG Coding: Move from OPM to ILE...and Beyond
Transition to modern RPG programming with this step-by-step guide through ILE and free-format RPG, SQL, and modernization techniques.
List Price $79.95

Now On Sale

Flexible Input, Dazzling Output with IBM i Flexible Input, Dazzling Output with IBM i
Uncover easier, more flexible ways to get data into your system, plus some methods for exporting and presenting the vital business data it contains.
List Price $79.95

Now On Sale

SQL for IBM i: A Database Modernization Guide SQL for IBM i: A Database Modernization Guide
Learn how to use SQL’s capabilities to modernize and enhance your IBM i database.
List Price $79.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

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: