The code in Example 1-1 loops from 1 to 20 and checks if the numbers are even or odd. The latter is done using the MOD function and the result is written into a table called temp. A cursory glance at the listing allows us to figure most of this out. Some confusion might also arise from these few, perhaps unfamiliar-looking lines:
- DECLARE
- IF
- END IF
- END LOOP
- COMMIT
These are just standard PL/SQL; DECLARE is used to create new variables for later use in the code. The END IF is simply a demarcation point for the opening IF statement. The END LOOP is similarly a demarcation point for the end of the LOOP operation. The COMMIT marks the end of a transaction and is required to write any updates to persistent storage (i.e., the database).
Another item in Example 1-1 that might give you pause is the use of the rather strange-looking assignment operator:
x
:
=
x
+
100
;
I recall showing some PL/SQL code to a Java developer a few years ago who said, “What’s that weird-looking assignment?” The extra colon before the equals sign was the source of the confusion. It’s interesting to see what causes cognitive dissonance. This assignment statement is functionally very similar to the equivalent operation in Java (and C), except in Java there is, of course, no colon in the assignment.
In this case, we are adding 100 to the value of x. The use of the assignment operator in PL/SQL merely reflects the origins of the language. PL/SQL was first released back in 1992 and is loosely based on Ada. PL/SQL often reminds me of the old Pascal language. For any reader interested in programming language history, PL/SQL is also quite similar to the IBM proprietary language Extended Structured Query Language (ESQL). It’s quite common for the authors of different programming languages to influence each other; for example, Java has only relatively recently added support for functional programming.
So, that’s the first example of PL/SQL done and dusted. The code is pretty straightforward and readable—in my opinion, it’s more readable than a lot of the often convoluted constructs found in both modern Java and JavaScript.
Reading source code is one of the most important skills any developer can acquire. This is particularly true in the current era, when so much development work involves a lot of code integration in multiple languages using a range of frameworks, platforms, and libraries. It’s not uncommon to labor over a programming problem for days and then find that the fix lies in adding or changing a single line of code or even just modifying some configuration data. Learning PL/SQL can help in extending your skill set and in producing resilient code. Let’s look at another example.