Structure of an Embedded SQL Program
In general, SQL statements can be embedded anywhere in a program that host language statements are allowed.
The following example shows a simple embedded SQL program that retrieves an employee name and salary from the database and prints them on a standard output device. The statements that begin with the words EXEC SQL are embedded SQL statements. The sequence of statements in this example illustrates a pattern common to most embedded SQL programs.
BEGIN program
EXEC SQL INCLUDE SQLCA;
EXEC SQL BEGIN DECLARE SECTION;
name character_string(15);
salary FLOAT;
EXEC SQL END DECLARE SECTION;
EXEC SQL WHENEVER SQLERROR stop;
EXEC SQL CONNECT personnel;
EXEC SQL SELECT ename, sal
INTO :name, :salary
FROM employee
WHERE eno = 23;
print name, salary;
EXEC SQL DISCONNECT;
END program
Each program statement is described here:
EXEC SQL INCLUDE SQLCA;
The INCLUDE statement incorporates the SQL error and status handling mechanism—the SQL Communications Area (SQLCA)—into the program. The SQLCA is used by the WHENEVER statement, which appears later in the program.
EXEC SQL BEGIN DECLARE SECTION;
Next is an SQL declaration section. Host language variables must be declared to SQL prior to their use in any embedded SQL statements. Host language variables are described in detail in the next section.
EXEC SQL WHENEVER SQLERROR stop;
The WHENEVER statement that follows uses information from the SQLCA to control program execution under error or exception conditions. In general, an error handling mechanism must precede all executable embedded SQL statements in a program. For details about error handling, see Error Handling in the chapter “Working with Transactions and Handling Errors.”
EXEC SQL CONNECT personnel;
Next is a series of SQL and host language statements. The first statement initiates access to the personnel database. A CONNECT statement must precede any references to a database.
EXEC SQL SELECT ename, sal
INTO :name, :salary
FROM employee
WHERE eno = 23;
Next is the familiar SELECT statement, containing a clause that begins with the keyword INTO. The INTO clause associates values retrieved by the SELECT statement with host language variables in the program. Following the INTO keyword are the two host language variables previously declared to SQL: name and salary.
print name, salary;
This host language statement prints the values contained in the variables.
EXEC SQL DISCONNECT;
The last SQL statement in the program severs the connection of the program to the database.
Last modified date: 04/03/2024