There Is a Better Way 3 – Resilient Software and PL/SQL

0 Comments

Example 1-2 illustrates a slightly different style of writing PL/SQL, which might be more familiar to developers used to mainstream languages. Again, some comments (which start with the characters “–”) are added to help in understanding it. As before, try to figure out what the code is doing before reading on.

Example 1-2. A more familiar code syntax

declare
n
number
(
10
)
:
=
1
;
— Notice the lack of spaces
begin
while
n
<=
10
— Notice the lack of spaces again!
loop
dbms_output
.
put_line
(
n
);
n
:
=
n
+
1
;
end
 
loop
;
end
;

Some items of note in Example 1-2 are:

  • The use of lowercase
  • Indentation using two spaces
  • The lack of spaces in the code statements
  • A call to dbms_output(), which allows you to display messages to screen
  • The use of end loop, which you also saw in Example 1-1

In Example 1-2, the keywords are all in lowercase. PL/SQL is not case-sensitive, so you can use uppercase or lowercase. The two-space indentation provides a nice, compact, and readable style, though you are free to use any number of spaces you like. The use of spaces is encouraged to improve readability for downstream maintainers of the PL/SQL code. So, it might be preferable to use this:

n
number
(
10
):
=
1
;
— Added an extra space

Similarly, I would always write the fourth line like this:

while
n
<=
10
— Added extra spaces

The following use of spaces is also more readable:

n
:
=
n
+
1
;
— Added extra spaces

Any thoughts on what this PL/SQL code in Example 1-2 might be doing? Any idea why there is no COMMIT statement here?

To answer the first question, Example 1-2 is a simple while loop. Again, this is very similar to Java, C++, etc. The reason we have no COMMIT (or commit in lowercase) simply reflects the fact that there is no data to write to the database. In other words, the code in Example 1-2 is ephemeral; it has no persistent content.

This section again illustrates the importance of the ability and willingness to read PL/SQL code and to then try to understand it. In the next section, we’ll get a little bit more ambitious and introduce a really powerful feature of PL/SQL: cursors.

Note

Some of the examples in this book are drawn from sample PL/SQL programs provided by Oracle. There’s lots of code at this site to assist you in your learning journey.

Leave a Reply

Your email address will not be published. Required fields are marked *