IBM Embedded SQL programming Database User manual
Annonce
Annonce
IBM i
Version 7.2
Database
Embedded SQL programming
IBM
IBM i
Version 7.2
Database
Embedded SQL programming
IBM
Note
This document may contain references to Licensed Internal Code. Licensed Internal Code is Machine Code and is licensed to you under the terms of the IBM License Agreement for Machine Code.
© Copyright IBM Corporation 1998, 2013.
US Government Users Restricted Rights – Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
Contents
||
Embedded SQL programming . . . . . 1
PDF file for Embedded SQL programming .
Common concepts and rules for using embedded
Writing applications that use SQL .
Using host variables in SQL statements .
Assignment rules for host variables in SQL statements .
Indicator variables in applications that use SQL 4
Indicator variables used with host structures 5
Indicator variables used to assign special values .
Handling SQL error return codes using the
Using the SQL diagnostics area .
Updating applications to use the SQL diagnostics area .
Additional notes on using the SQL diagnostics area .
Example: SQL routine exception .
Example: Logging items from the SQL diagnostics area .
Handling exception conditions with the
Coding SQL statements in C and C++ applications 11
Defining the SQL communication area in C and
C++ applications that use SQL .
Defining SQL descriptor areas in C and C++ applications that use SQL.
Embedding SQL statements in C and C++ applications that use SQL.
Comments in C and C++ applications that use
Continuation for SQL statements in C and
C++ applications that use SQL .
Including code in C and C++ applications that use SQL .
Margins in C and C++ applications that use
Names in C and C++ applications that use
NULLs and NULs in C and C++ applications that use SQL .
Statement labels in C and C++ applications that use SQL .
Preprocessor sequence for C and C++ applications that use SQL.
Trigraphs in C and C++ applications that use
WHENEVER statement in C and C++ applications that use SQL.
Using host variables in C and C++ applications that use SQL .
© Copyright IBM Corp. 1998, 2013
Declaring host variables in C and C++ applications that use SQL.
Numeric host variables in C and C++ applications that use SQL.
Character host variables in C and C++ applications that use SQL.
Graphic host variables in C and C++ applications that use SQL.
Binary host variables in C and C++ applications that use SQL.
LOB host variables in C and C++ applications that use SQL.
XML host variables in C and C++ applications that use SQL.
ROWID host variables in C and C++ applications that use SQL.
Result set locator host variables in C and
C++ applications that use SQL .
Using host structures in C and C++ applications that use SQL .
Host structure declarations in C and C++ applications that use SQL.
Host structure indicator array in C and C++ applications that use SQL.
Using arrays of host structures in C and C++ applications that use SQL.
Host structure array in C and C++ applications that use SQL.
Host structure array indicator structure in C and C++ applications that use SQL .
Using pointer data types in C and C++ applications that use SQL.
Using typedef in C and C++ applications that use SQL .
Using ILE C compiler external file descriptions in
C and C++ applications that use SQL.
Determining equivalent SQL and C or C++ data types .
Notes on C and C++ variable declaration and usage .
Using indicator variables in C and C++ applications that use SQL.
Coding SQL statements in COBOL applications .
Defining the SQL communication area in COBOL applications that use SQL.
Defining SQL descriptor areas in COBOL applications that use SQL.
Embedding SQL statements in COBOL applications that use SQL.
Comments in COBOL applications that use
Continuation for SQL statements in COBOL applications that use SQL.
Including code in COBOL applications that use SQL .
Margins in COBOL applications that use SQL 48
iii
Sequence numbers in COBOL applications that use SQL .
Names in COBOL applications that use SQL 48
COBOL compile-time options in COBOL applications that use SQL.
Statement labels in COBOL applications that use SQL .
WHENEVER statement in COBOL applications that use SQL.
Multiple source COBOL programs and the
Using host variables in COBOL applications that use SQL .
Declaring host variables in COBOL applications that use SQL.
Numeric host variables in COBOL applications that use SQL.
Floating-point host variables in COBOL applications that use SQL.
Character host variables in COBOL applications that use SQL.
Graphic host variables in COBOL applications that use SQL.
Binary host variables in COBOL applications that use SQL.
LOB host variables in COBOL applications that use SQL .
XML host variables in COBOL applications that use SQL .
Datetime host variables in COBOL applications that use SQL.
ROWID host variables in COBOL applications that use SQL.
Result set locator host variables in COBOL applications that use SQL.
Using host structures in COBOL applications that use SQL .
Host structure in COBOL applications that use
Host structure indicator array in COBOL applications that use SQL.
Using host structure arrays in COBOL applications that use SQL.
Host structure array in COBOL applications that use SQL .
Host array indicator structure in COBOL applications that use SQL.
Using external file descriptions in COBOL applications that use SQL.
Using external file descriptions for host structure arrays in COBOL applications that use SQL .
Determining equivalent SQL and COBOL data types .
Notes on COBOL variable declaration and usage .
Using indicator variables in COBOL applications that use SQL .
Coding SQL statements in PL/I applications .
Defining the SQL communication area in PL/I applications that use SQL.
iv
IBM i: Embedded SQL programming
Defining SQL descriptor areas in PL/I applications that use SQL.
Embedding SQL statements in PL/I applications that use SQL .
Example: Embedding SQL statements in PL/I applications that use SQL.
Comments in PL/I applications that use SQL 76
Continuation for SQL statements in PL/I applications that use SQL.
Including code in PL/I applications that use
Margins in PL/I applications that use SQL .
Names in PL/I applications that use SQL .
Statement labels in PL/I applications that use
WHENEVER statement in PL/I applications that use SQL .
Using host variables in PL/I applications that use
Declaring host variables in PL/I applications that use SQL .
Numeric-host variables in PL/I applications that use SQL.
Character-host variables in PL/I applications that use SQL.
Binary host variables in PL/I applications that use SQL .
LOB host variables in PL/I applications that use SQL .
ROWID host variables in PL/I applications that use SQL .
Using host structures in PL/I applications that use SQL .
Host structures in PL/I applications that use
Host structure indicator arrays in PL/I applications that use SQL.
Using host structure arrays in PL/I applications that use SQL .
Host structure array in PL/I applications that use SQL .
Host structure array indicator in PL/I applications that use SQL.
Using external file descriptions in PL/I applications that use SQL.
Determining equivalent SQL and PL/I data types 85
Using indicator variables in PL/I applications that use SQL .
Differences in PL/I because of structure parameter passing techniques .
Coding SQL statements in RPG/400 applications .
Defining the SQL communication area in
RPG/400 applications that use SQL .
Defining SQL descriptor areas in RPG/400 applications that use SQL.
Embedding SQL statements in RPG/400 applications that use SQL.
Example: Embedding SQL statements in
RPG/400 applications that use SQL .
Comments in RPG/400 applications that use
Continuation for SQL statements in RPG/400 applications that use SQL.
Including code in RPG/400 applications that use SQL .
Sequence numbers in RPG/400 applications that use SQL .
Names in RPG/400 applications that use SQL 91
Statement labels in RPG/400 applications that use SQL .
WHENEVER statement in RPG/400 applications that use SQL.
Using host variables in RPG/400 applications that use SQL .
Declaring host variables in RPG/400 applications that use SQL.
Using host structures in RPG/400 applications that use SQL .
Using host structure arrays in RPG/400 applications that use SQL.
Using external file descriptions in RPG/400 applications that use SQL.
Determining equivalent SQL and RPG/400 data types .
Assignment rules in RPG/400 applications that use SQL .
Using indicator variables in RPG/400 applications that use SQL.
Example: Using indicator variables in
RPG/400 applications that use SQL .
Differences in RPG/400 because of structure parameter passing techniques .
Correctly ending a called RPG/400 program that uses SQL .
Coding SQL statements in ILE RPG applications .
Defining the SQL communication area in ILE
RPG applications that use SQL .
Defining SQL descriptor areas in ILE RPG applications that use SQL .
Embedding SQL statements in ILE RPG applications that use SQL .
Comments in ILE RPG applications that use
Continuation for SQL statements in ILE RPG applications that use SQL .
Including code in ILE RPG applications that use SQL .
Using directives in ILE RPG applications that use SQL .
Sequence numbers in ILE RPG applications that use SQL .
Names in ILE RPG applications that use SQL 103
Statement labels in ILE RPG applications that use SQL .
WHENEVER statement in ILE RPG applications that use SQL .
Using host variables in ILE RPG applications that use SQL .
Declaring host variables in ILE RPG applications that use SQL .
Declaring binary host variables in ILE
RPG applications that use SQL .
Declaring LOB host variables in ILE RPG applications that use SQL .
Declaring XML host variables in ILE RPG applications that use SQL .
Declaring ROWID variables in ILE RPG applications that use SQL .
Declaring result set locator variables in
ILE RPG applications that use SQL .
Using host structures in ILE RPG applications that use SQL .
Using host structure arrays in ILE RPG applications that use SQL .
Using external file descriptions in ILE RPG applications that use SQL .
Determining equivalent SQL and ILE RPG data types .
Notes on ILE RPG variable declaration and usage .
Using indicator variables in ILE RPG applications that use SQL .
Example: Using indicator variables in ILE
RPG applications that use SQL .
Example: SQLDA for a multiple row-area fetch in ILE RPG applications that use SQL .
Example: Dynamic SQL in an ILE RPG application that uses SQL .
Coding SQL statements in REXX applications .
Using the SQL communication area in REXX applications .
Using SQL descriptor areas in REXX applications .
Embedding SQL statements in REXX applications .
Comments in REXX applications that use
Continuation of SQL statements in REXX applications that use SQL .
Including code in REXX applications that use
Margins in REXX applications that use SQL 133
Names in REXX applications that use SQL 133
Nulls in REXX applications that use SQL .
Statement labels in REXX applications that use SQL .
Handling errors and warnings in REXX applications that use SQL .
Using host variables in REXX applications that use SQL .
Determining data types of input host variables in REXX applications that use SQL . 134
The format of output host variables in REXX applications that use SQL .
Avoiding REXX conversion in REXX applications that use SQL .
Contents
v
Using indicator variables in REXX applications that use SQL .
Preparing and running a program with SQL statements .
Basic processes of the SQL precompiler.
Input to the SQL precompiler .
Source file CCSIDs in the SQL precompiler 138
Output from the SQL precompiler .
Temporary source file members created by the SQL precompiler .
Sample SQL precompiler output .
Non-ILE SQL precompiler commands .
Compiling a non-ILE application program that uses SQL .
ILE SQL precompiler commands .
Compiling an ILE application program that uses SQL .
Setting compiler options using the precompiler commands .
Interpreting compile errors in applications that use SQL .
Binding an application that uses SQL .
Program references in applications that use
Displaying SQL precompiler options .
Running a program with embedded SQL .
Running a program with embedded SQL:
Running a program with embedded SQL:
Running a program with embedded SQL:
Example programs: Using DB2 for i statements .
Example: SQL statements in ILE C and C++ programs .
Example: SQL statements in COBOL and ILE
Example: SQL statements in PL/I programs .
Example: SQL statements in RPG/400 programs 171
Example: SQL statements in ILE RPG programs 177
Example: SQL statements in REXX programs
Report produced by example programs that use
CL command descriptions for host language precompilers .
Create SQL COBOL Program command .
Create SQL ILE COBOL Object command .
Create SQL ILE C Object command .
Create SQL ILE C++ Object command .
Create SQL PL/I Program command .
Create SQL RPG Program command .
Create SQL ILE RPG Object command .
Related information for Embedded SQL programming .
Notices . . . . . . . . . . . . . . 191
Programming interface information .
vi
IBM i: Embedded SQL programming
Embedded SQL programming
This topic collection explains how to create database applications in host languages that use DB2
®
SQL statements and functions.
for i
Note:
|
|
|
|
|
|
|
What's new for IBM i 7.2
Read about new or significantly changed information for the Embedded SQL programming topic collection.
v The ILE RPG precompiler supports RPG free form H, F, D, and P specs.
– “Determining equivalent SQL and ILE RPG data types” on page 117
v The ILE COBOL and ILE RPG precompilers support a timestamp data type that allows fractional seconds values from 0 to 12.
|
|
|
|
What's new as of March 2017
v The precompiler COMPILEOPT parameter recognizes EVENTF as an option. For more information, see
“Setting compiler options using the precompiler commands” on page 146.
v The ILE RPG precompiler generates more free-form declarations and code.
|
How to see what's new or changed
|
|
|
To help you see where technical changes have been made, this information uses: v The image to mark where new or changed information begins.
v The image to mark where new or changed information ends.
| In PDF files, you might see revision bars (|) in the left margin of new and changed information.
| To find other information about what's new or changed this release, see the Memo to users.
PDF file for Embedded SQL programming
You can view and print a PDF file of this information.
To view or download the PDF version of this document, select Embedded SQL programming.
Saving PDF files
To save a PDF on your workstation for viewing or printing:
1.
Right-click the PDF link in your browser.
2.
Click the option that saves the PDF locally.
3.
Navigate to the directory in which you want to save the PDF.
4.
Click Save.
© Copyright IBM Corp. 1998, 2013
1
Downloading Adobe Reader
You need Adobe Reader installed on your system to view or print these PDFs. You can download a free copy from the Adobe Web site (http://get.adobe.com/reader/) .
Related reference
:
“Related information for Embedded SQL programming” on page 189
Product manuals and other information center topic collections contain information that relates to the
Embedded SQL programming topic collection. You can view or print any of the PDF files.
Common concepts and rules for using embedded SQL
Here are some common concepts and rules for using SQL statements in a host language.
Writing applications that use SQL
You can create database applications in host languages that use DB2 for i SQL statements and functions.
To use embedded SQL, you must have the licensed program IBM
®
DB2 Query Manager and SQL
Development Kit for i installed. Additionally, you must have the compilers for the host languages you want to use installed.
Related concepts
:
“Coding SQL statements in C and C++ applications” on page 11
To embed SQL statements in an ILE C or C++ program, you need to be aware of some unique application and coding requirements. This topic also defines the requirements for host structures and host variables.
“Coding SQL statements in COBOL applications” on page 44
There are unique application and coding requirements for embedding SQL statements in a COBOL program. In this topic, requirements for host structures and host variables are defined.
“Coding SQL statements in PL/I applications” on page 73
There are some unique application and coding requirements for embedding SQL statements in a PL/I program. In this topic, requirements for host structures and host variables are defined.
“Coding SQL statements in RPG/400 applications” on page 88
The RPG/400
® licensed program supports both RPG II and RPG III programs.
“Coding SQL statements in ILE RPG applications” on page 98
You need to be aware of the unique application and coding requirements for embedding SQL statements in an ILE RPG program. In this topic, the coding requirements for host variables are defined.
“Coding SQL statements in REXX applications” on page 128
REXX procedures do not have to be preprocessed. At run time, the REXX interpreter passes statements that it does not understand to the current active command environment for processing.
“Preparing and running a program with SQL statements” on page 136
This topic describes some of the tasks for preparing and running an application program.
IBM Developer Kit for Java
Using host variables in SQL statements
When your program retrieves data, the values are put into data items that are defined by your program and that are specified with the INTO clause of a SELECT INTO or FETCH statement. The data items are called host variables.
A host variable is a field in your program that is specified in an SQL statement, usually as the source or target for the value of a column. The host variable and column must have compatible data types. Host variables cannot be used to identify SQL objects, such as tables or views, except in the DESCRIBE TABLE statement.
2
IBM i: Embedded SQL programming
A host structure is a group of host variables used as the source or target for a set of selected values (for example, the set of values for the columns of a row). A host structure array is an array of host structures that is used in the multiple-row FETCH and blocked INSERT statements.
Note:
By using a host variable instead of a literal value in an SQL statement, you give the application program the flexibility to process different rows in a table or view.
For example, instead of coding an actual department number in a WHERE clause, you can use a host variable set to the department number you are currently interested in.
Host variables are commonly used in SQL statements in these ways: v In a WHERE clause: You can use a host variable to specify a value in the predicate of a search condition, or to replace a literal value in an expression. For example, if you have defined a field called
EMPID that contains an employee number, you can retrieve the name of the employee whose number is 000110 with:
MOVE ’000110’ TO EMPID.
EXEC SQL
SELECT LASTNAME
INTO :PGM-LASTNAME
FROM CORPDATA.EMPLOYEE
WHERE EMPNO = :EMPID
END-EXEC.
v As a receiving area for column values (named in an INTO clause): You can use a host variable to specify a program data area that is to contain the column values of a retrieved row. The INTO clause names one or more host variables that you want to contain column values returned by SQL. For example, suppose you are retrieving the EMPNO, LASTNAME, and WORKDEPT column values from rows in the CORPDATA.EMPLOYEE table. You could define a host variable in your program to hold each column, then name the host variables with an INTO clause. For example:
EXEC SQL
SELECT EMPNO, LASTNAME, WORKDEPT
INTO :CBLEMPNO, :CBLNAME, :CBLDEPT
FROM CORPDATA.EMPLOYEE
WHERE EMPNO = :EMPID
END-EXEC.
In this example, the host variable CBLEMPNO receives the value from EMPNO, CBLNAME receives the value from LASTNAME, and CBLDEPT receives the value from WORKDEPT.
v As a value in a SELECT clause: When specifying a list of items in the SELECT clause, you are not restricted to the column names of tables and views. Your program can return a set of column values intermixed with host variable values and literal constants. For example:
MOVE ’000220’ TO PERSON.
EXEC SQL
SELECT "A", LASTNAME, SALARY, :RAISE,
SALARY + :RAISE
INTO :PROCESS, :PERSON-NAME, :EMP-SAL,
:EMP-RAISE, :EMP-TTL
FROM CORPDATA.EMPLOYEE
WHERE EMPNO = :PERSON
END-EXEC.
The results are:
PROCESS
A
PERSON-NAME
LUTZ
EMP-SAL
29840
EMP-RAISE
4476
EMP-TTL
34316 v As a value in other clauses of an SQL statement:
– The SET clause in an UPDATE statement
– The VALUES clause in an INSERT statement
Embedded SQL programming
3
– The CALL statement
Related concepts
:
DB2 for i5/OS SQL reference
Assignment rules for host variables in SQL statements
SQL values are assigned to host variables during the running of FETCH, SELECT INTO, SET, and
VALUES INTO statements. SQL values are assigned from host variables during the running of INSERT,
UPDATE, and CALL statements.
All assignment operations observe the following rules: v Numbers and strings are compatible:
– Numbers can be assigned to character or graphic string columns or host variables.
– Character and graphic strings can be assigned to numeric columns or numeric host variables.
v All character and DBCS graphic strings are compatible with UCS-2 and UTF-16 graphic columns if conversion is supported between the CCSIDs. All graphic strings are compatible if the CCSIDs are compatible. All numeric values are compatible. Conversions are performed by SQL whenever necessary. All character and DBCS graphic strings are compatible with UCS-2 and UTF-16 graphic columns for assignment operations, if conversion is supported between the CCSIDs. For the CALL statement, character and DBCS graphic parameters are compatible with UCS-2 and UTF-16 parameters if conversion is supported.
v Binary strings are only compatible with binary strings.
v A null value cannot be assigned to a host variable that does not have an associated indicator variable.
v Different types of date/time values are not compatible. Dates are only compatible with dates or string representations of dates; times are only compatible with times or string representations of times; and timestamps are only compatible with timestamps or string representations of timestamps.
Related concepts
: i5/OS globalization
Related reference
:
DECLARE VARIABLE
Numeric assignments
String assignments
Datetime assignments
Indicator variables in applications that use SQL
An indicator variable is a halfword integer variable used to communicate additional information about its associated host variable.
v If the value for the result column is null, SQL puts a -1 in the indicator variable.
v If you do not use an indicator variable and the result column is a null value, a negative SQLCODE is returned.
v If the value for the result column causes a data mapping error, SQL sets the indicator variable to -2.
You can also use an indicator variable to verify that a retrieved string value has not been truncated. If truncation occurs, the indicator variable contains a positive integer that specifies the original length of the string. If the string represents a large object (LOB), and the original length of the string is greater than
32 767, the value that is stored in the indicator variable is 32 767, because no larger value can be stored in a halfword integer.
Always test the indicator variable first. If the value of the indicator variable is less than zero, you know the value of the result column should not be used. When the database manager returns a null value, the host variable might or might not be set to the default value for the result column's data type (0 for numeric, blanks for fixed length character, etc).
4
IBM i: Embedded SQL programming
You specify an indicator variable (preceded by a colon) immediately after the host variable. For example:
EXEC SQL
SELECT COUNT(*), AVG(SALARY)
INTO :PLICNT, :PLISAL:INDNULL
FROM CORPDATA.EMPLOYEE
WHERE EDLEVEL < 18
END-EXEC.
You can then test INDNULL in your program to see if it contains a negative value. If it does, you know
SQL returned a null value (if its value is -1) or a data mapping error (if its value is -2). If the indicator value is not negative, the value returned in PLISAL can be used.
Related reference
:
Predicates
Indicator variables used with host structures:
You can specify an indicator array (defined as an array of halfword integer variables) to support a host structure.
If the results column values returned to a host structure can be null, you can add an indicator array name after the host structure name. This allows SQL to notify your program about each null value returned to a host variable in the host structure.
For example, in COBOL:
01 SAL-REC.
10 MIN-SAL
10 AVG-SAL
10 MAX-SAL
01 SALTABLE.
02 SALIND
01 EDUC-LEVEL
...
PIC S9(6)V99 USAGE COMP-3.
PIC S9(6)V99 USAGE COMP-3.
PIC S9(6)V99 USAGE COMP-3.
PIC S9999 USAGE COMP-4 OCCURS 3 TIMES.
PIC S9999 COMP-4.
MOVE 20 TO EDUC-LEVEL.
...
EXEC SQL
SELECT MIN(SALARY), AVG(SALARY), MAX(SALARY)
INTO :SAL-REC:SALIND
FROM CORPDATA.EMPLOYEE
WHERE EDLEVEL>:EDUC-LEVEL
END-EXEC.
In this example, SALIND is an array that contains three values, each of which can be tested for a negative value. SQL selects the values for the result row and puts them into the host structure. If
MIN-SAL is to return a null value, the corresponding indicator variable, SALIND(1), is set to -1. Your program must check the corresponding indicator variables first to determine which, if any, selected result variables contain the null value.
Indicator variables used to assign special values:
You can use an indicator variable to set a null value for a column in an INSERT or UPDATE statement.
There are two forms of indicators for INSERT and UPDATE statements: normal indicators and extended indicators. When you use normal indicators, an indicator set to any negative value is interpreted as the null value. When you use extended indicators, the negative values have several different meanings. Both forms of indicators can be used for inserts and updates that are part of a MERGE statement as well.
When processing update and insert using normal indicators, SQL checks the indicator variable (if it exists). If it contains a negative value, the column value is set to null. If it contains a value greater than
-1, the column is set from the associated host variable value.
Embedded SQL programming
5
For example, you can specify that a value be updated in a column, but you know that an actual value is not always known. To provide the capability to set a column to a null value, you can write the following statement:
EXEC SQL
UPDATE CORPDATA.EMPLOYEE
SET PHONENO = :NEWPHONE:PHONEIND
WHERE EMPNO = :EMPID
END-EXEC.
When NEWPHONE contains a non-null value, set PHONEIND to zero; otherwise, to tell SQL that
NEWPHONE contains a null value, set PHONEIND to a negative value.
Using extended indicators provides your application with more flexibility when writing INSERT and
UPDATE statements. In addition to providing the null value, you can set an indicator to indicate that the default value for a column is used or that the corresponding column is not updated at all.
For extended indicators, the indicator values are interpreted as follows: v An indicator value of 0 means the value for the host variable is assigned to the column.
v An indicator value of -1, -2, -3, -4, or -6 means the null value is assigned to the column.
v An indicator value of -5 means the default value for the column is assigned.
v An indicator value of -7 means that the column is not assigned. This value causes the column to be treated as though it were not listed in the insert or update column list. For an INSERT statement it means the default value is used.
To write an UPDATE statement that can conditionally update several different fields, write it as follows:
EXEC SQL
UPDATE CORPDATA.EMPLOYEE
SET PHONENO = :NEWPHONE:PHONEIND,
LASTNAME = :LASTNAME:LASTNAMEIND,
WORKDEPT = :WORKDEPT:WORKDEPTIND,
EDLEVEL = :EDLEVEL:EDLEVELIND
WHERE EMPNO = :EMPID
END-EXEC.
With this one UPDATE statement, you can update any or all of the columns listed in the SET clause. For example, if you only want to update the EDLEVEL column, set the EDLEVEL variable to the new value and the EDLEVELIND indicator to 0. Set the other three indicators (PHONEIND, LASTNAMEIND, and
WORKDEPTIND) to -7. This causes the statement to be processed as though you had written it this way.
EXEC SQL
UPDATE CORPDATA.EMPLOYEE
SET EDLEVEL = :EDLEVEL:EDLEVELIND
WHERE EMPNO = :EMPID
END-EXEC.
You can use extended indicators only if they are explicitly enabled for your program. To specify that your program supports extended indicators, use *EXTIND on the OPTION parameter of the precompiler command or EXTIND(*YES) on the SET OPTION statement.
Handling SQL error return codes using the SQLCA
When an SQL statement is processed in your program, SQL places a return code in the SQLCODE and
SQLSTATE fields. The return codes indicate the success or failure of the running of your statement.
If SQL encounters an error while processing the statement, the SQLCODE is a negative number and
SUBSTR(SQLSTATE,1,2) is not '00', '01', or '02'. If SQL encounters an exception but valid condition while
6
IBM i: Embedded SQL programming
processing your statement, the SQLCODE is a positive number and SUBSTR(SQLSTATE,1,2) is '01' or '02'.
If your SQL statement is processed without encountering an error or warning condition, the SQLCODE is zero and the SQLSTATE is '00000'.
Note:
There are situations when a zero SQLCODE is returned to your program and the result might not be satisfactory. For example, if a value was truncated as a result of running your program, the SQLCODE returned to your program is zero. However, one of the SQL warning flags (SQLWARN1) indicates truncation. In this case, the SQLSTATE is not '00000'.
Attention:
If you do not test for negative SQLCODEs or specify a WHENEVER SQLERROR statement, your program will continue to the next statement. Continuing to run after an error can produce unpredictable results.
The main purpose for SQLSTATE is to provide common return codes for common return conditions among the different IBM relational database systems. SQLSTATEs are particularly useful when handling problems with distributed database operations.
Because the SQLCA is a valuable problem-diagnosis tool, it is a good idea to include in your application programs the instructions necessary to display some of the information contained in the SQLCA.
Especially important are the following SQLCA fields:
SQLCODE
Return code.
SQLSTATE
Return code.
SQLERRD(3)
The number of rows updated, inserted, or deleted by SQL.
SQLWARN0
If set to W, at least one of the SQL warning flags (SQLWARN1 through SQLWARNA) is set.
Related concepts
:
DB2 for i5/OS SQL reference
SQL messages and codes
Using the SQL diagnostics area
The SQL diagnostics area is used to keep the returned information for an SQL statement that has been run in a program. It contains all the information that is available to you as an application programmer through the SQLCA.
There are additional values available to provide more detailed information about your SQL statement including connection information. More than one condition can be returned from a single SQL statement.
The information in the SQL diagnostics area is available for the previous SQL statement until the next
SQL statement is run.
To access the information from the diagnostics area, use the GET DIAGNOSTICS statement. In this statement, you can request multiple pieces of information at one time about the previously run SQL statement. Each item is returned in a host variable. You can also request to get a string that contains all the diagnostic information that is available. Running the GET DIAGNOSTICS statement does not clear the diagnostics area.
Related reference
:
GET DIAGNOSTICS
Embedded SQL programming
7
Updating applications to use the SQL diagnostics area
You might consider changing your applications to use the SQL diagnostics area instead of the SQL communication area (SQLCA), because the SQL diagnostics area provides some significant advantages over the SQLCA.
One of the best reasons is that the SQLERRM field in the SQLCA is only 70 bytes in length. This is often insufficient for returning meaningful error information to the calling application. Additional reasons for considering the SQL diagnostics area are multiple row operations, and long column and object names.
Reporting even simple warnings is sometimes difficult within the restrictions of the 136 byte SQLCA.
Quite often, the returned tokens are truncated to fit the restrictions of the SQLCA.
Current applications include the SQLCA definition by using the following:
EXEC SQL INCLUDE SQLCA; /* Existing SQLCA */
With the conversion to using the SQL diagnostics area, the application would first declare a stand-alone
SQLSTATE variable: char SQLSTATE[6]; /* Stand-alone sqlstate */
And possibly a stand-alone SQLCODE variable: long int SQLCODE; /* Stand-alone sqlcode */
The completion status of the SQL statement is verified by checking the stand-alone SQLSTATE variable. If upon the completion of the current SQL statement, the application chooses to retrieve diagnostics, the application would run the SQL GET DIAGNOSTICS statement: char hv1[256]; long int hv2;
EXEC SQL GET DIAGNOSTICS :hv1 = COMMAND_FUNCTION,
:hv2 = COMMAND_FUNCTION_CODE;
IBM i programming model
In the IBM i Integrated Language Environment
®
(ILE), the SQL diagnostics area is scoped to a thread and an activation group. This means that for each activation group in which a thread runs SQL statements, a separate diagnostics area exists for the activation.
Additional notes on using the SQL diagnostics area
In an application program, the SQLCA is replaced with an implicit or a stand-alone SQLSTATE variable, which must be declared in the program.
With multiple condition areas existing in the SQL diagnostics area, the most severe error or warning is returned in the first diagnostics area. There is no specific ordering of the multiple conditions, except that the first diagnostics area will contain the information for the SQLSTATE that is also returned in the
SQLSTATE variable.
With the SQLCA, the application program provides the storage for the SQLCA that is used to communicate the results of the run of an SQL statement. With the SQL diagnostics area, the database manager manages the storage for the diagnostics, and the GET DIAGNOSTICS statement is provided to retrieve the contents of the diagnostics area.
Note that the SQLCA will continue to be supported for application programs. Also, the GET
DIAGNOSTICS statement can be used in an application program that uses the SQLCA.
Example: SQL routine exception
In this application example, a stored procedure signals an error when an input value is out of range.
8
IBM i: Embedded SQL programming
EXEC SQL CREATE PROCEDURE check_input (IN p1 INT)
LANGUAGE SQL READS SQL DATA
test: BEGIN
IF p1< 0 THEN
SIGNAL SQLSTATE VALUE ’99999’
SET MESSAGE_TEXT = ’Bad input value’;
END IF;
END test;
The calling application checks for a failure and retrieves the information about the failure from the SQL diagnostics area: char SQLSTATE[6]; /* Stand-alone sqlstate */ long int SQLCODE; /* Stand-alone sqlcode */ long int hv1; char hv2[6]; char hv3[256]; hv1 = -1;
EXEC SQL CALL check_input(:hv1); if (strncmp(SQLSTATE, "99999", 5) == 0)
{
EXEC SQL GET DIAGNOSTICS CONDITION 1
:hv2 = RETURNED_SQLSTATE,
:hv3 = MESSAGE_TEXT;
{
}
} else
Example: Logging items from the SQL diagnostics area
In this example, an application needs to log all errors for security reasons. The log can be used to monitor the health of a system or to monitor for inappropriate use of a database.
For each SQL error that occurs, an entry is placed in the log. The entry includes when the error occurred, what user was using the application, what type of SQL statement was run, the returned SQLSTATE value, and the message number and corresponding complete message text.
char stmt_command[256]; long int error_count; long int condition_number; char auth_id[256]; char error_state[6]; char msgid[128]; char msgtext[1024];
EXEC SQL WHENEVER SQLERROR GOTO error;
(application code) error:
EXEC SQL GET DIAGNOSTICS :stmt_command = COMMAND_FUNCTION,
:error_count = NUMBER; for (condition_number=1;condition_number<=error_count;++condition_number)
{
EXEC SQL GET DIAGNOSTICS CONDITION :condition_number
:auth_id = DB2_AUTHORIZATION_ID,
:error_state = RETURNED_SQLSTATE,
:msgid = DB2_MESSAGE_ID,
:msgtext = DB2_MESSAGE_TEXT;
EXEC SQL INSERT INTO error_log VALUES(CURRENT_TIMESTAMP,
Embedded SQL programming
9
:stmt_command,
:condition_number,
:auth_id,
:error_state,
:msgid,
:msgtext);
}
Related reference
:
GET DIAGNOSTICS
Handling exception conditions with the WHENEVER statement
The WHENEVER statement causes SQL to check the SQLSTATE and SQLCODE and continue processing your program, or branch to another area in your program if an error, exception, or warning exists as a result of running an SQL statement.
An exception condition handling subroutine (part of your program) can then examine the SQLCODE or
SQLSTATE field to take an action specific to the error or exception situation.
Note:
The WHENEVER statement is not allowed in REXX procedures.
The WHENEVER statement allows you to specify what you want to do whenever a general condition is true. You can specify more than one WHENEVER statement for the same condition. When you do this, the first WHENEVER statement applies to all subsequent SQL statements in the source program until another WHENEVER statement is specified.
The WHENEVER statement looks like this:
EXEC SQL
WHENEVER condition action
END-EXEC.
There are three conditions you can specify:
SQLWARNING
Specify SQLWARNING to indicate what you want done when SQLWARN0 = W or SQLCODE contains a positive value other than 100 (SUBSTR(SQLSTATE,1,2) ='01').
Note:
SQLWARN0 could be set for several different reasons. For example, if the value of a column was truncated when it was moved into a host variable, your program might not regard this as an error.
SQLERROR
Specify SQLERROR to indicate what you want done when an error code is returned as the result of an SQL statement (SQLCODE < 0) (SUBSTR(SQLSTATE,1,2) > '02').
NOT FOUND
Specify NOT FOUND to indicate what you want done when an SQLCODE of +100 and a
SQLSTATE of '02000' is returned because: v After a single-row SELECT is issued or after the first FETCH is issued for a cursor, the data the program specifies does not exist.
v After a subsequent FETCH, no more rows satisfying the cursor select-statement are left to retrieve.
v After an UPDATE, a DELETE, or an INSERT, no row meets the search condition.
You can also specify the action you want taken:
CONTINUE
This causes your program to continue to the next statement.
10
IBM i: Embedded SQL programming
GO TO label
This causes your program to branch to an area in the program. The label for that area may be preceded with a colon. The WHENEVER ... GO TO statement: v Must be a section name or an unqualified paragraph name in COBOL v Is a label in PL/I and C v Is the label of a TAG in RPG
For example, if you are retrieving rows using a cursor, you expect that SQL will eventually be unable to find another row when the FETCH statement is issued. To prepare for this situation, specify a
WHENEVER NOT FOUND GO TO ... statement to cause SQL to branch to a place in the program where you issue a CLOSE statement in order to close the cursor properly.
Note:
A WHENEVER statement affects all subsequent source SQL statements until another WHENEVER is encountered.
In other words, all SQL statements coded between two WHENEVER statements (or following the first, if there is only one) are governed by the first WHENEVER statement, regardless of the path the program takes.
Because of this, the WHENEVER statement must precede the first SQL statement it is to affect. If the
WHENEVER follows the SQL statement, the branch is not taken on the basis of the value of the
SQLCODE and SQLSTATE set by that SQL statement. However, if your program checks the SQLCODE or
SQLSTATE directly, the check must be done after the SQL statement is run.
The WHENEVER statement does not provide a CALL to a subroutine option. For this reason, you might want to examine the SQLCODE or SQLSTATE value after each SQL statement is run and call a subroutine, rather than use a WHENEVER statement.
Coding SQL statements in C and C++ applications
To embed SQL statements in an ILE C or C++ program, you need to be aware of some unique application and coding requirements. This topic also defines the requirements for host structures and host variables.
Note:
Related concepts
:
“Writing applications that use SQL” on page 2
You can create database applications in host languages that use DB2 for i SQL statements and functions.
Related reference
:
“Example programs: Using DB2 for i statements” on page 149
Here is a sample application that shows how to code SQL statements in each of the languages that DB2 for i supports.
“Example: SQL statements in ILE C and C++ programs” on page 151
This example program is written in the C programming language.
Defining the SQL communication area in C and C++ applications that use SQL
A C or C++ program can be written to use the SQLCA to check return status for embedded SQL statements, or the program can use the SQL diagnostics area to check return status.
When using the SQLCA, a C or C++ program that contains SQL statements must include one or both of the following: v An SQLCODE variable declared as long SQLCODE
Embedded SQL programming
11
v An SQLSTATE variable declared as char SQLSTATE[6]
Or, v An SQLCA (which contains an SQLCODE and SQLSTATE variable).
The SQLCODE and SQLSTATE values are set by the database manager after each SQL statement is run.
An application can check the SQLCODE or SQLSTATE value to determine whether the last SQL statement was successful.
You can code the SQLCA in a C or C++ program directly or by using the SQL INCLUDE statement.
When coding it directly, initialize the SQLCA using the following statement: struct sqlca sqlca = {0x0000000000000000};
Using the SQL INCLUDE statement requests the inclusion of a standard declaration:
EXEC SQL INCLUDE SQLCA ;
A standard declaration includes a structure definition and a data area that are named sqlca.
The SQLCODE, SQLSTATE, and SQLCA variables must appear before any executable statements. The scope of the declaration must include the scope of all SQL statements in the program.
The included C and C++ source statements for the SQLCA are: struct sqlca { unsigned char sqlcaid[8]; long sqlcabc; long short sqlcode; sqlerrml; unsigned char sqlerrmc[70]; unsigned char sqlerrp[8]; long sqlerrd[6]; unsigned char sqlwarn[11]; unsigned char sqlstate[5];
};
#define SQLCODE sqlca.sqlcode
#define SQLWARN0 sqlca.sqlwarn[0]
#define SQLWARN1 sqlca.sqlwarn[1]
#define SQLWARN2 sqlca.sqlwarn[2]
#define SQLWARN3 sqlca.sqlwarn[3]
#define SQLWARN4 sqlca.sqlwarn[4]
#define SQLWARN5 sqlca.sqlwarn[5]
#define SQLWARN6 sqlca.sqlwarn[6]
#define SQLWARN7 sqlca.sqlwarn[7]
#define SQLWARN8 sqlca.sqlwarn[8]
#define SQLWARN9 sqlca.sqlwarn[9]
#define SQLWARNA sqlca.sqlwarn[10]
#define SQLSTATE sqlca.sqlstate
struct sqlca sqlca = {0x0000000000000000};
When a declare for SQLCODE is found in the program and the precompiler provides the SQLCA,
SQLCADE replaces SQLCODE. When a declare for SQLSTATE is found in the program and the precompiler provides the SQLCA, SQLSTOTE replaces SQLSTATE.
Note:
Many SQL error messages contain message data that is of varying length. The lengths of these data fields are embedded in the value of the SQLCA sqlerrmc field. Because of these lengths, printing the value of sqlerrmc from a C or C++ program might give unpredictable results.
Related concepts
:
“Using the SQL diagnostics area” on page 7
The SQL diagnostics area is used to keep the returned information for an SQL statement that has been run in a program. It contains all the information that is available to you as an application programmer
12
IBM i: Embedded SQL programming
through the SQLCA.
Related reference
:
SQL communication area
GET DIAGNOSTICS
Defining SQL descriptor areas in C and C++ applications that use SQL
There are two types of SQL descriptor areas. One is defined with the ALLOCATE DESCRIPTOR statement. The other is defined using the SQL descriptor area (SQLDA) structure. In this topic, only the
SQLDA form is discussed.
The following statements can use an SQLDA: v EXECUTE...USING DESCRIPTOR descriptor-name v FETCH...USING DESCRIPTOR descriptor-name v
OPEN...USING DESCRIPTOR descriptor-name v DESCRIBE statement-name INTO descriptor-name v DESCRIBE CURSOR cursor-name INTO descriptor-name v DESCRIBE INPUT statement-name INTO descriptor-name v DESCRIBE PROCEDURE procedure-name INTO descriptor-name v DESCRIBE TABLE host-variable INTO descriptor-name v PREPARE statement-name INTO descriptor-name v CALL...USING DESCRIPTOR descriptor-name
Unlike the SQLCA, more than one SQLDA can be in the program, and an SQLDA can have any valid name. The following list includes the statements that require a SQLDA. You can code an SQLDA in a C or C++ program either directly or by using the SQL INCLUDE statement. Using the SQL INCLUDE statement requests the inclusion of a standard SQLDA declaration:
EXEC SQL INCLUDE SQLDA;
A standard declaration includes only a structure definition with the name 'sqlda'.
C and C++ declarations that are included for the SQLDA are: struct sqlda { unsigned char sqldaid[8]; long sqldabc; short sqln; short sqld; struct sqlvar { short sqltype; short sqllen; union { unsigned char *sqldata; long long sqld_result_set_locator; }; union { short *sqlind; long sqld_row_change; long sqld_result_set_rows; ]; struct sqlname { short length; unsigned char data[30];
} sqlname;
} sqlvar[1];
};
One benefit from using the INCLUDE SQLDA SQL statement is that you also get the following macro definition:
Embedded SQL programming
13
#define SQLDASIZE(n) (sizeof(struct sqlda) + (n-1)* sizeof(struc sqlvar))
This macro makes it easy to allocate storage for an SQLDA with a specified number of SQLVAR elements.
In the following example, the SQLDASIZE macro is used to allocate storage for an SQLDA with 20
SQLVAR elements.
#include <stdlib.h>
EXEC SQL INCLUDE SQLDA; struct sqlda *mydaptr; short numvars = 20;
.
.
mydaptr = (struct sqlda *) malloc(SQLDASIZE(numvars)); mydaptr->sqln = 20;
Here are other macro definitions that are included with the INCLUDE SQLDA statement:
GETSQLDOUBLED(daptr)
Returns 1 if the SQLDA pointed to by daptr has been doubled, or 0 if it has not been doubled.
The SQLDA is doubled if the seventh byte in the SQLDAID field is set to '2'.
SETSQLDOUBLED(daptr, newvalue)
Sets the seventh byte of SQLDAID to a new value.
GETSQLDALONGLEN(daptr,n)
Returns the length attribute of the nth entry in the SQLDA to which daptr points. Use this only if the SQLDA was doubled and the nth SQLVAR entry has a LOB data type.
SETSQLDALONGLEN(daptr,n,len)
Sets the SQLLONGLEN field of the SQLDA to which daptr points to len for the nth entry. Use this only if the SQLDA was doubled and the nth SQLVAR entry has a LOB datatype.
GETSQLDALENPTR(daptr,n)
Returns a pointer to the actual length of the data for the nth entry in the SQLDA to which daptr points. The SQLDATALEN pointer field returns a pointer to a long (4 byte) integer. If the
SQLDATALEN pointer is zero, a NULL pointer is returned. Use this only if the SQLDA has been doubled.
SETSQLDALENPTR(daptr,n,ptr)
Sets a pointer to the actual length of the data for the nth entry in the SQLDA to which daptr points. Use this only if the SQLDA has been doubled.
When you have declared an SQLDA as a pointer, you must reference it exactly as declared when you use it in an SQL statement, just as you would for a host variable that was declared as a pointer. To avoid compiler errors, the type of the value that is assigned to the sqldata field of the SQLDA must be a pointer of unsigned character. This helps avoid compiler errors. The type casting is only necessary for the
EXECUTE, OPEN, CALL, and FETCH statements where the application program is passing the address of the host variables in the program. For example, if you declared a pointer to an SQLDA called mydaptr, you would use it in a PREPARE statement as:
EXEC SQL PREPARE mysname INTO :*mydaptr FROM :mysqlstring;
SQLDA declarations can appear wherever a structure definition is allowed. Normal C scope rules apply.
Dynamic SQL is an advanced programming technique. With dynamic SQL, your program can develop and then run SQL statements while the program is running. A SELECT statement with a variable SELECT list (that is a list of the data to be returned as part of the query) that runs dynamically requires an SQL descriptor area (SQLDA). This is because you will not know in advance how many or what type of variables to allocate in order to receive the results of the SELECT.
Related concepts
:
Dynamic SQL applications
14
IBM i: Embedded SQL programming
Related reference
:
SQL descriptor area
Embedding SQL statements in C and C++ applications that use SQL
SQL statements can be coded in a C or C++ program wherever executable statements can appear.
Each SQL statement must begin with EXEC SQL and end with a semicolon (;). The EXEC SQL keywords must be on one line. The remaining part of the SQL statement can be on more than one line.
Example: An UPDATE statement coded in a C or C++ program might be coded in the following way:
EXEC SQL
UPDATE DEPARTMENT
SET MGRNO = :MGR_NUM
WHERE DEPTNO = :INT_DEPT ;
Do not use #pragma convert to modify the CCSID of any literals that could be used by SQL. All literals used by SQL are assumed to be in the CCSID of the source file.
Comments in C and C++ applications that use SQL
In addition to using SQL comments (--), you can include C comments (/*...*/) and single-line comments
(comments that start with //) within embedded SQL statements whenever a blank is allowed, except between the keywords EXEC and SQL.
Comments can span any number of lines. You cannot nest comments.
Continuation for SQL statements in C and C++ applications that use SQL
SQL statements can be contained in one or more lines.
You can split an SQL statement wherever a blank can appear. The backslash (\) can be used to continue a string constant or delimited identifier. Identifiers that are not delimited cannot be continued.
Constants containing DBCS data may be continued across multiple lines in two ways: v If the character at the right margin of the continued line is a shift-in and the character at the left margin of the continuation line is a shift-out, then the shift characters located at the left and right margin are removed.
This SQL statement has a valid graphic constant of G'<AABBCCDDEEFFGGHHIIJJKK>'. The redundant shifts at the margin are removed.
*...+....1....+....2....+....3....+....4....+....5....+....6....+....7....*....8
EXEC SQL SELECT * FROM GRAPHTAB WHERE GRAPHCOL = G’<AABBCCDDEEFFGGHH>
<IIJJKK>’; v It is possible to place the shift characters outside of the margins. For this example, assume the margins are 5 and 75. This SQL statement has a valid graphic constant of G'<AABBCCDDEEFFGGHHIIJJKK>'.
*...(....1....+....2....+....3....+....4....+....5....+....6....+....7....)....8
EXEC SQL SELECT * FROM GRAPHTAB WHERE GRAPHCOL = G’<AABBCCDD>
<EEFFGGHHIIJJKK>’;
Including code in C and C++ applications that use SQL
You can include SQL statements, C, or C++ statements by embedding the following SQL statement in the source code.
EXEC SQL INCLUDE member-name;
You cannot use C and C++ #include statements to include SQL statements or declarations of C or C++ host variables that are referred to in SQL statements.
Embedded SQL programming
15
Margins in C and C++ applications that use SQL
When you precompile using a source member, you must code SQL statements within the margins that are specified by the MARGINS parameter on the CRTSQLCI or CRTSQLCPPI command.
If the MARGINS parameter is specified as *SRCFILE, the record length of the source file will be used. If a value is specified for the right margin and that value is larger than the source record length, the entire record will be read. The value will also apply to any included members. For example, if a right margin of
200 is specified and the source file has a record length of 80, only 80 columns of data will be read from the source file. If an included source member in the same precompile has a record length of 200, the entire 200 from the include will be read.
When you precompile using a source stream file, the MARGINS parameter is ignored; the entire file is read. Any source stream file included using the SQL INCLUDE statement is read up to the length of the longest line in the primary source stream file, which is specified on the SRCSTMF parameter.
If EXEC SQL does not start within the margins, the SQL precompiler does not recognize the SQL statement.
Related concepts
:
“CL command descriptions for host language precompilers” on page 188
The IBM DB2 Query Manager and SQL Development Kit for i licensed program provides commands for precompiling programs coded in these programming languages.
Names in C and C++ applications that use SQL
You can use any valid C or C++ variable name for a host variable. It is subject to these restrictions.
Do not use host variable names or external entry names that begin with SQL, RDI, or DSN in any combination of uppercase or lowercase letters. These names are reserved for the database manager. The length of host variable names is limited to 128.
If the name SQL in any combination of uppercase or lowercase letters is used, unpredictable results might occur.
NULLs and NULs in C and C++ applications that use SQL
C, C++, and SQL use the word null, but for different meanings.
The C and C++ languages have a null character (NUL), a null pointer (NULL), and a null statement (just a semicolon (;)). The C NUL is a single character that compares equal to 0. The C NULL is a special reserved pointer value that does not point to any valid data object. The SQL null value is a special value that is distinct from all non-null values and denotes the absence of a (non-null) value.
Statement labels in C and C++ applications that use SQL
Executable SQL statements can be preceded with a label.
Preprocessor sequence for C and C++ applications that use SQL
You must run the SQL preprocessor before the C or C++ preprocessor. You cannot use C or C++ preprocessor directives within SQL statements.
Trigraphs in C and C++ applications that use SQL
Some characters from the C and C++ character set are not available on all keyboards. You can enter these characters into a C or C++ source program by using a sequence of three characters that is called a
trigraph.
The following trigraph sequences are supported within host variable declarations: v ??( left bracket v ??) right bracket
16
IBM i: Embedded SQL programming
v ??< left brace v
??> right brace v ??= pound v ??/ backslash
WHENEVER statement in C and C++ applications that use SQL
The target for the GOTO clause in an SQL WHENEVER statement must be within the scope of any SQL statements affected by the WHENEVER statement.
Using host variables in C and C++ applications that use SQL
All host variables used in SQL statements must be explicitly declared prior to their first use.
In C, the C statements that are used to define the host variables should be preceded by a BEGIN
DECLARE SECTION statement and followed by an END DECLARE SECTION statement. If a BEGIN
DECLARE SECTION and END DECLARE SECTION are specified, all host variable declarations used in
SQL statements must be between the BEGIN DECLARE SECTION and the END DECLARE SECTION statements. Host variables declared using a typedef identifier also require a BEGIN DECLARE SECTION and END DECLARE SECTION; however, the typedef declarations do not need to be between these two sections.
In C++, the C++ statements that are used to define the host variables must be preceded by a BEGIN
DECLARE SECTION statement and followed by an END DECLARE SECTION statement. You cannot use any variable that is not between the BEGIN DECLARE SECTION statement and the END DECLARE
SECTION statement as a host variable.
All host variables within an SQL statement must be preceded by a colon (:).
The names of host variables must be unique within the program, even if the host variables are in different blocks or procedures.
An SQL statement that uses a host variable must be within the scope of the statement in which the variable was declared.
Host variables cannot be union elements.
Host variables cannot contain continuation characters within the name.
Declaring host variables in C and C++ applications that use SQL
The C and C++ precompilers recognize only a subset of valid C and C++ declarations as valid host variable declarations.
Numeric host variables in C and C++ applications that use SQL:
This figure shows the syntax for valid numeric host variable declarations.
Numeric
Embedded SQL programming
17
►► auto extern static const volatile float double decimal (
precision
_Decimal32
_Decimal64
_Decimal128 signed sqlint32 sqlint64
, long long long short
scale
int
)
►
,
► ▼
variable-name
=
expression
; ►◄
Notes:
1.
Precision and scale must be integer constants. Precision may be in the range from 1 to 63. Scale may be in the range from 0 to the precision.
2.
If using the decimal data type, the header file decimal.h must be included.
3.
If using sqlint32 or sqlint64, the header file sqlsystm.h must be included.
4.
_Decimal32, _Decimal64, and _Decimal128 are only supported for C.
Character host variables in C and C++ applications that use SQL:
There are three valid forms for character host variables.
These forms are: v Single-character form v NUL-terminated character form v VARCHAR structured form
In addition, an SQL VARCHAR declare can be used to define a varchar host variable.
All character types are treated as unsigned.
Single-character form
►► char auto extern static const volatile unsigned signed
►
18
IBM i: Embedded SQL programming
,
► ▼
variable-name
[
1
] =
expression
NUL-terminated character form
►► auto extern static const volatile unsigned signed char
; ►◄
►
,
► ▼
variable-name
[
length
]
=
expression
; ►◄
Notes:
1.
The length must be an integer constant that is greater than 1 and not greater than 32 741.
2.
If the *CNULRQD option is specified on the CRTSQLCI or CRTSQLCPPI command, the input host variables must contain the NUL-terminator. Output host variables are padded with blanks, and the last character is the NUL-terminator. If the output host variable is too small to contain both the data and the NUL-terminator, the following actions are taken: v
The data is truncated v The last character is the NUL-terminator v SQLWARN1 is set to 'W'
3.
If the *NOCNULRQD option is specified on the CRTSQLCI or CRTSQLCPPI command, the input variables do not need to contain the NUL-terminator.
The following applies to output host variables.
v If the host variable is large enough to contain the data and the NUL-terminator, then the following actions are taken:
– The data is returned, but the data is not padded with blanks
– The NUL-terminator immediately follows the data v If the host variable is large enough to contain the data but not the NUL-terminator, then the following actions are taken:
– The data is returned
– A NUL-terminator is not returned
– SQLWARN1 is set to 'N' v If the host variable is not large enough to contain the data, the following actions are taken:
– The data is truncated
– A NUL-terminator is not returned
– SQLWARN1 is set to 'W'
VARCHAR structured form
Embedded SQL programming
19
►► auto extern static const volatile
_Packed struct
tag
{ ►
► signed short int
var-1
; unsigned signed char
var-2
[
length
] ; }
,
► ▼
variable-name
= {
expression , expression
}
;
►
►◄
Notes:
1.
length must be an integer constant that is greater than 0 and not greater than 32 740.
2.
var-1 and var-2 must be simple variable references and cannot be used individually as integer and character host variables.
3.
The struct tag can be used to define other data areas, but these cannot be used as host variables.
4.
The VARCHAR structured form should be used for bit data that may contain the NULL character. The
VARCHAR structured form will not be ended using the nul-terminator.
5.
_Packed must not be used in C++. Instead, specify #pragma pack(1) prior to the declaration and
#pragma pack() after the declaration.
Note:
You can use #pragma pack (reset) instead of #pragma pack() because they are the same.
#pragma pack(1) struct VARCHAR { short len; char s[10];
} vstring;
#pragma pack()
Example:
EXEC SQL BEGIN DECLARE SECTION;
/* valid declaration of host variable vstring */ struct VARCHAR { short len; char s[10];
} vstring;
/* invalid declaration of host variable wstring */ struct VARCHAR wstring;
SQL VARCHAR form
,
►► VARCHAR
▼
variable-name
[
length
] ; ►◄
=
"init-data"
20
IBM i: Embedded SQL programming
Notes:
1.
VARCHAR can be in mixed case.
2.
length must be an integer constant that is greater than 0 and not greater than 32 740.
3.
The SQL VARCHAR form should be used for bit data that may contain the NULL character. The SQL
VARCHAR form will not be ended using the nul-terminator.
Example
The following declaration:
VARCHAR vstring[528]="mydata";
Results in the generation of the following structure:
_Packed struct { short len; char data[528];} vstring={6, "mydata"};
The following declaration:
VARCHAR vstring1[111], vstring2[222]="mydata", vstring3[333]="more data";
Results in the generation of the following structures:
_Packed struct { short len; char data[111];} vstring1;
_Packed struct { short len; char data[222];} vstring2={6,"mydata"};
_Packed struct { short len; char data[333};} vstring3={9,"more data"};
Graphic host variables in C and C++ applications that use SQL:
There are three valid forms for graphic host variables.
v Single-graphic form v NUL-terminated graphic form v VARGRAPHIC structured form
Single-graphic form
►►
, wchar_t
▼
variable-name
auto extern static const volatile
=
expression
; ►◄
NUL-terminated graphic form
Embedded SQL programming
21
►► auto extern static const volatile
, wchar_t
▼
variable-name
[
length
]
=
expression
; ►◄
Notes:
1.
length must be an integer constant that is greater than 1 and not greater than 16371.
2.
If the *CNULRQD option is specified on the CRTSQLCI or CRTSQLCPPI command, then input host variables must contain the graphic NUL-terminator (/0/0). Output host variables are padded with
DBCS blanks, and the last character is the graphic NUL-terminator. If the output host variable is too small to contain both the data and the NUL-terminator, the following actions are taken: v
The data is truncated v The last character is the graphic NUL-terminator v SQLWARN1 is set to 'W'
If the *NOCNULRQD option is specified on the CRTSQLCI or CRTSQLCPPI command, the input host variables do not need to contain the graphic NUL-terminator. The following is true for output host variables.
v If the host variable is large enough to contain the data and the graphic NUL-terminator, the following actions are taken:
– The data is returned, but is not padded with DBCS blanks
– The graphic NUL-terminator immediately follows the data v
If the host variable is large enough to contain the data but not the graphic NUL-terminator, the following actions are taken:
– The data is returned
– A graphic NUL-terminator is not returned
– SQLWARN1 is set to 'N' v If the host variable is not large enough to contain the data, the following actions are taken:
– The data is truncated
– A graphic NUL-terminator is not returned
– SQLWARN1 is set to 'W'
VARGRAPHIC structured form
►► struct { auto extern static const volatile
_Packed
tag
►
► signed short int
var-1
; wchar_t
var-2
[
length
] ; } ►
22
IBM i: Embedded SQL programming
,
► ▼
variable-name
= {
expression , expression
}
; ►◄
Notes:
1.
length must be an integer constant that is greater than 0 and not greater than 16370.
2.
var-1 and var-2 must be simple variable references and cannot be used as host variables.
3.
The struct tag can be used to define other data areas, but these cannot be used as host variables.
4.
_Packed must not be used in C++. Instead, specify #pragma pack(1) prior to the declaration and
#pragma pack() after the declaration.
#pragma pack(1) struct VARGRAPH { short len; wchar_t s[10];
} vstring;
#pragma pack()
Example
EXEC SQL BEGIN DECLARE SECTION;
/* valid declaration of host variable graphic string */ struct VARGRAPH { short len; wchar_t s[10];
} vstring;
/* invalid declaration of host variable wstring */ struct VARGRAPH wstring;
Binary host variables in C and C++ applications that use SQL:
C and C++ do not have variables that correspond to the SQL binary data types. To create host variables that can be used with these data types, use the SQL TYPE IS clause. The SQL precompiler replaces this declaration with a C language structure in the output source member.
BINARY
►►
,
SQL TYPE IS BINARY
(length)
▼
variable-name
auto extern static const volatile
=
init-data
►
► ; ►◄
VARBINARY
Embedded SQL programming
23
►► auto extern static const volatile
SQL TYPE IS VARBINARY
BINARY VARYING
(length)
►
,
► ▼
variable-name
= {
init-len,"init-data"
}
=
SQL_VARBINARY_INIT("init-data")
; ►◄
Notes:
1.
For BINARY host variables, the length must be in the range 1 to 32 766.
2.
For VARBINARY and BINARY VARYING host variables, the length must in the range 1 to 32 740.
3.
SQL TYPE IS, BINARY, VARBINARY, and BINARY VARYING can be in mixed case.
BINARY example
The following declaration:
SQL TYPE IS BINARY(4) myBinField;
Results in the generation of the following code: char myBinField[4];
VARBINARY example
The following declaration:
SQL TYPE IS VARBINARY(12) myVarBinField;
Results in the generation of the following structure:
_Packed struct myVarBinField_t { short length; char data[12]; } myVarBinField;
LOB host variables in C and C++ applications that use SQL:
C and C++ do not have variables that correspond to the SQL data types for LOBs (large objects). To create host variables that can be used with these data types, use the SQL TYPE IS clause. The SQL precompiler replaces this declaration with a C language structure in the output source member.
LOB host variable
►► auto extern static const volatile
SQL TYPE IS CLOB
DBCLOB
BLOB
(
length
K
M
G
) ►
24
IBM i: Embedded SQL programming
,
► ▼
variable-name
= {
init-len,"init-data"
}
=
SQL_CLOB_INIT("init-data")
=
SQL_DBCLOB_INIT("init-data")
=
SQL_BLOB_INIT("init-data")
; ►◄
Notes:
1.
K multiplies length by 1024. M multiplies length by 1 048 576. G multiplies length by 1 073 741 824.
2.
For BLOB and CLOB, 1 ≤ length ≤ 2 147 483 647
3.
For DBCLOB, 1 ≤ length ≤ 1 073 741 823
4.
SQL TYPE IS, BLOB, CLOB, DBCLOB, K, M, G can be in mixed case.
5.
The maximum length allowed for the initialization string is 32 766 bytes.
6.
The initialization length, init-len, must be a numeric constant (that is, it cannot include K, M, or G).
7.
If the LOB is not initialized within the declaration, then no initialization will be done within the precompiler generated code.
8.
The precompiler generates a structure tag which can be used to cast to the host variable's type.
9.
Pointers to LOB host variables can be declared, with the same rules and restrictions as for pointers to other host variable types.
10.
CCSID processing for LOB host variables will be the same as the processing for other character and graphic host variable types.
11.
If a DBCLOB is initialized, it is the user's responsibility to prefix the string with an 'L' (indicating a wide-character string).
CLOB example
The following declaration:
SQL TYPE IS CLOB(128K) var1, var2 = {10, "data2data2"};
The precompiler will generate for C:
_Packed struct var1_t { unsigned long length; char data[131072];
} var1,var2={10,"data2data2"};
DBCLOB example
The following declaration:
SQL TYPE IS DBCLOB(128K) my_dbclob;
The precompiler will then generate:
_Packed struct my_dbclob_t { unsigned long length; wchar_t data[131072]; } my_dbclob;
BLOB example
The following declaration: static SQL TYPE IS BLOB(128K) my_blob=SQL_BLOB_INIT("mydata");
Results in the generation of the following structure:
Embedded SQL programming
25
static struct my_blob_t { unsigned long length; char data[131072];
} my_blob=SQL_BLOB_INIT("my_data");
LOB locator
►► auto extern static const volatile
SQL TYPE IS CLOB_LOCATOR
DBCLOB_LOCATOR
BLOB_LOCATOR
►
,
► ▼
variable-name
=
init-value
; ►◄
Notes:
1.
SQL TYPE IS, BLOB_LOCATOR, CLOB_LOCATOR, DBCLOB_LOCATOR can be in mixed case.
2.
init-value permits the initialization of pointer locator variables. Other types of initialization will have no meaning.
3.
Pointers to LOB locators can be declared with the same rules and restrictions as for pointers to other host variable types.
CLOB locator example
The following declaration: static SQL TYPE IS CLOB_LOCATOR my_locator;
Results in the following generation: static long int unsigned my_locator;
BLOB and DBCLOB locators have similar syntax.
LOB file reference variable
►► auto extern static const volatile
SQL TYPE IS CLOB_FILE
DBCLOB_FILE
BLOB_FILE
►
,
► ▼
variable-name
=
init-value
;
Notes:
1.
SQL TYPE IS, BLOB_FILE, CLOB_FILE, DBCLOB_FILE can be in mixed case.
2.
Pointers to LOB File Reference Variables can be declared, with the same rules and restrictions as for pointers to other host variable types.
26
IBM i: Embedded SQL programming
►◄
CLOB file reference example
The following declaration: static SQL TYPE IS CLOB_FILE my_file;
Results in the generation of the following structure: static _Packed struct { unsigned long name_length; unsigned long unsigned long char
} my_file; data_length; file_options; name[255];
BLOB and DBCLOB file reference variables have similar syntax.
The precompiler generates declarations for the following file option constants. You can use these constants to set the file_options variable when you use file reference host variables.
v SQL_FILE_READ (2) v SQL_FILE_CREATE (8) v SQL_FILE_OVERWRITE (16) v SQL_FILE_APPEND (32)
Related reference
:
LOB file reference variables
XML host variables in C and C++ applications that use SQL:
C and C++ do not have variables that correspond to the SQL data type for XML. To create host variables that can be used with this data type, use the SQL TYPE IS clause. The SQL precompiler replaces this declaration with a C language structure in the output source member.
XML host variable
►► auto extern static const volatile
SQL TYPE IS XML AS CLOB
DBCLOB
BLOB
(
length
K
M
G
) ►
,
► ▼
variable-name
= {
init-len,"init-data"
}
=
SQL_CLOB_INIT("init-data")
=
SQL_DBCLOB_INIT("init-data")
=
SQL_BLOB_INIT("init-data")
; ►◄
Notes:
1.
K multiplies length by 1024. M multiplies length by 1 048 576. G multiplies length by 1 073 741 824.
2.
For BLOB and CLOB, 1 ≤ length ≤ 2 147 483 647
3.
For DBCLOB, 1 ≤ length ≤ 1 073 741 823
4.
SQL TYPE IS, XML AS, BLOB, CLOB, DBCLOB, K, M, G can be in mixed case.
5.
The maximum length allowed for the initialization string is 32 766 bytes.
6.
The initialization length, init-len, must be a numeric constant (that is, it cannot include K, M, or G).
Embedded SQL programming
27
7.
If the XML variable is not initialized within the declaration, then no initialization will be done within the precompiler generated code.
8.
The precompiler generates a structure tag which can be used to cast to the host variable's type.
9.
Pointers to XML host variables can be declared, with the same rules and restrictions as for pointers to other host variable types.
10.
The CCSID value for an XML host variable can be explicitly set by the DECLARE VARIABLE statement. Otherwise, the value specified by the SQL_XML_DATA_CCSID QAQQINI option will be used. The default for this QAQQINI option is CCSID 1208.
11.
If XML AS DBCLOB is initialized, it is the user's responsibility to prefix the string with an 'L'
(indicating a wide-character string).
XML example
The following declaration:
SQL TYPE IS XML AS CLOB(5000) var1;
The precompiler will generate for C:
_Packed struct var1_t { unsigned long length; char data[5000];
} var1;
XML locator
►► auto extern static const volatile
SQL TYPE IS XML AS LOCATOR ►
,
► ▼
variable-name
=
init-value
;
Notes:
1.
SQL TYPE IS, XML AS LOCATOR can be in mixed case.
2.
init-value permits the initialization of pointer locator variables. Other types of initialization will have no meaning.
3.
Pointers to XML locators can be declared with the same rules and restrictions as for pointers to other host variable types.
XML locator example
The following declaration: static SQL TYPE IS XML AS LOCATOR my_locator;
Results in the following generation: static long int unsigned my_locator;
►◄
28
IBM i: Embedded SQL programming
XML file reference variable
►► auto extern static const volatile
SQL TYPE IS XML AS CLOB_FILE
DBCLOB_FILE
BLOB_FILE
►
,
► ▼
variable-name
=
init-value
; ►◄
Notes:
1.
SQL TYPE IS, XML AS, BLOB_FILE, CLOB_FILE, DBCLOB_FILE can be in mixed case.
2.
Pointers to XML File Reference Variables can be declared, with the same rules and restrictions as for pointers to other host variable types.
XML file reference example
The following declaration: static SQL TYPE IS XML AS CLOB_FILE my_file;
Results in the generation of the following structure: static _Packed struct { unsigned long name_length; unsigned long unsigned long char data_length; file_options; name[255];
} my_file;
The precompiler generates declarations for the following file option constants. You can use these constants to set the file_options variable when you use file reference host variables.
v SQL_FILE_READ (2) v SQL_FILE_CREATE (8) v SQL_FILE_OVERWRITE (16) v SQL_FILE_APPEND (32)
ROWID host variables in C and C++ applications that use SQL:
C and C++ do not have a variable that corresponds to the SQL data type ROWID. To create host variables that can be used with this data type, use the SQL TYPE IS clause. The SQL precompiler replaces this declaration with a C language structure in the output source member.
ROWID
,
►► SQL TYPE IS ROWID
▼
variable-name
; ►◄
Note:
SQL TYPE IS ROWID can be in mixed case.
Embedded SQL programming
29
ROWID example
The following declaration:
SQL TYPE IS ROWID myrowid, myrowid2;
Results in the generation of the following structure:
_Packed struct { short len; char data[40];} myrowid1, myrowid2;
Result set locator host variables in C and C++ applications that use SQL:
C and C++ do not have a variable that corresponds to the SQL result set locator data type. To create host variables that can be used for this data type, use the SQL TYPE IS clause. The SQL precompiler replaces this declaration with a C language structure in the output source member.
Result set locator
,
►► SQL TYPE IS RESULT_SET_LOCATOR
▼
variable-name
; ►◄
Note:
SQL TYPE IS RESULT_SET_LOCATOR can be in mixed case.
Result set locator example
The following declaration:
SQL TYPE IS RESULT_SET_LOCATOR resloc1;
Results in the generation of the following structure: long long unsigned resloc1;
Using host structures in C and C++ applications that use SQL
In C and C++ programs, you can define a host structure, which is a named set of elementary C or C++ variables.
Host structures have a maximum of two levels, even though the host structure might itself occur within a multilevel structure. An exception is the declaration of a varying-length string, which requires another structure.
A host structure name can be a group name whose subordinate levels name elementary C or C++ variables. For example: struct { struct { char c1; char c2;
} b_st;
} a_st;
In this example, b_st is the name of a host structure consisting of the elementary items c1 and c2.
You can use the structure name as a shorthand notation for a list of scalars, but only for a two-level structure. You can qualify a host variable with a structure name (for example, structure.field). Host structures are limited to two levels. (For example, in the above host structure example, the a_st cannot be referred to in SQL.) A structure cannot contain an intermediate level structure. In the previous example,
30
IBM i: Embedded SQL programming
a_st could not be used as a host variable or referred to in an SQL statement. A host structure for SQL data has two levels and can be thought of as a named set of host variables. After the host structure is defined, you can refer to it in an SQL statement instead of listing the several host variables (that is, the names of the host variables that make up the host structure).
For example, you can retrieve all column values from selected rows of the table CORPDATA.EMPLOYEE
with: struct { char empno[7]; struct { short int firstname_len; char firstname_text[12];
} firstname; char midint, struct char workdept[4];
} lastname;
} pemp1;
{ short int lastname_len; char lastname_text[15];
.....
strcpy(pemp1.empno, "000220");
.....
exec sql
SELECT *
INTO :pemp1
FROM corpdata.employee
WHERE empno=:pemp1.empno;
Notice that in the declaration of pemp1, two varying-length string elements are included in the structure: firstname and lastname.
Host structure declarations in C and C++ applications that use SQL
These figures show the valid syntax for host structure declarations.
Host structures
►► struct { ► auto extern static const volatile
_Packed
tag
Embedded SQL programming
31
► ▼ float double decimal (
precision
)
,
scale
_Decimal32
_Decimal64
_Decimal128 int signed long long long short sqlint32 sqlint64
varchar-structure vargraphic-structure binary lob xml
SQL-varchar rowid result-set-locator
, char
▼
var-2
signed unsigned
, wchar_t
▼
var-5
[
[
length
]
length
;
]
,
▼
var-1
;
,
► ▼
variable-name
;
=
expression
; }
varchar-structure:
struct
tag
{ signed short int
var-3
; signed unsigned
► char
var-4
[
length
] ; }
Host structures (continued)
vargraphic-structure:
struct
tag
{ signed short int
var-6
; wchar_t
var-7
[
length
] ; }
32
IBM i: Embedded SQL programming
►
►◄
►
binary:
SQL TYPE IS BINARY
VARBINARY
BINARY VARYING
(
length
)
lob:
SQL TYPE IS CLOB
DBCLOB
BLOB
(
length
CLOB_LOCATOR
DBCLOB_LOCATOR
BLOB_LOCATOR
CLOB_FILE
DBCLOB_FILE
BLOB_FILE
K
M
G
)
xml:
SQL TYPE IS XML AS CLOB
DBCLOB
BLOB
(
LOCATOR
CLOB_FILE
DBCLOB_FILE
BLOB_FILE
length
K
M
G
)
SQL-varchar:
VARCHAR
variable-name
[
length
]
rowid:
SQL TYPE IS ROWID
result-set-locator:
SQL TYPE IS RESULT_SET_LOCATOR
Notes:
1.
For details on declaring numeric, character, graphic, binary, LOB, XML, ROWID, and result set locator host variables, see the notes under numeric, character, graphic, binary, LOB, XML, ROWID, and result set locator host variables.
2.
A structure of a short int followed by either a char or wchar_t array is always interpreted by the SQL
C and C++ precompilers as either a VARCHAR or VARGRAPHIC structure.
3.
_Packed must not be used in C++. Instead, specify #pragma pack(1) prior to the declaration and
#pragma pack() after the declaration.
Embedded SQL programming
33
#pragma pack(1) struct { short myshort; long mylong; char mychar[5];
} a_st;
#pragma pack()
4.
If using sqlint32 or sqlint64, the header file sqlsystm.h must be included.
5.
_Decimal32, _Decimal64, and _Decimal128 are only supported for C.
Host structure indicator array in C and C++ applications that use SQL
This figure shows the valid syntax for host structure indicator array declarations.
Host structure indicator array
int
►► short auto extern static const volatile signed
,
► ▼
variable-name
[
dimension
]
=
expression
;
Note:
Dimension must be an integer constant between 1 and 32 767.
Using arrays of host structures in C and C++ applications that use
SQL
In C and C++ programs, you can define a host structure array that has the dimension attribute. Host structure arrays have a maximum of two levels, even though the array might occur within a multiple-level structure. Another structure is not needed if a varying-length character string or a varying-length graphic string is not used.
In this C example, struct {
_Packed struct{ char c1_var[20]; short c2_var;
} b_array[10];
} a_struct; and in this C++ example,
#pragma pack(1) struct { struct{ char c1_var[20]; short c2_var;
} b_array[10];
} a_struct;
#pragma pack() the following are true: v All of the members in b_array must be valid variable declarations.
v The _Packed attribute must be specified for the struct tag.
34
IBM i: Embedded SQL programming
►◄
►
v b_array is the name of an array of host structures containing the members c1_var and c2_var.
v b_array may only be used on the blocked forms of FETCH statements and INSERT statements.
v c1_var and c2_var are not valid host variables in any SQL statement.
v A structure cannot contain an intermediate level structure.
For example, in C you can retrieve 10 rows from the cursor with:
_Packed struct {char first_initial; char middle_initial;
_Packed struct {short lastname_len; char lastname_data[15];
} lastname; double total_salary;
} employee_rec[10]; struct { short inds[4];
} employee_inds[10];
...
EXEC SQL DECLARE C1 CURSOR FOR
SELECT SUBSTR(FIRSTNME,1,1), MIDINIT, LASTNAME,
SALARY+BONUS+COMM
FROM CORPDATA.EMPLOYEE;
EXEC SQL OPEN C1;
EXEC SQL FETCH C1 FOR 10 ROWS INTO :employee_rec:employee_inds;
...
Host structure array in C and C++ applications that use SQL
The figure shows the valid syntax for host structure array declarations.
►► _Packed struct { auto extern static const volatile
tag
►
Embedded SQL programming
35
► ▼ float double decimal (
precision
)
,
scale
_Decimal32
_Decimal64
_Decimal128 int signed long long long short sqlint32 sqlint64
varchar-structure vargraphic-structure binary lob xml
SQL-varchar rowid result-set-locator
, char
▼
var-2
signed unsigned
, wchar_t
▼
var-5
[
[
length
]
length
;
]
,
▼
var-1
;
,
► ▼
variable-name
[
dimension
]
=
expression
;
; }
varchar-structure:
_Packed struct
tag
{ signed short int
var-3
; signed unsigned
► char
var-4
[
length
] ; }
vargraphic-structure:
_Packed struct
tag
{ signed short int
var-6
;
36
IBM i: Embedded SQL programming
►
►◄
►
►
► wchar_t
var-7
[
length
] ; }
binary:
SQL TYPE IS BINARY
VARBINARY
BINARY VARYING
(
length
)
lob:
SQL TYPE IS CLOB
DBCLOB
BLOB
(
length
CLOB_LOCATOR
DBCLOB_LOCATOR
BLOB_LOCATOR
CLOB_FILE
DBCLOB_FILE
BLOB_FILE
K
M
G
)
xml:
SQL TYPE IS XML AS CLOB
DBCLOB
BLOB
(
LOCATOR
CLOB_FILE
DBCLOB_FILE
BLOB_FILE
length
K
M
G
)
SQL-varchar:
VARCHAR
variable-name
[
length
]
rowid:
SQL TYPE IS ROWID
result-set-locator:
SQL TYPE IS RESULT_SET_LOCATOR
Notes:
1.
For details on declaring numeric, character, graphic, binary, LOB, XML, ROWID, and result set locator host variables, see the notes under numeric-host variables, character-host variables, graphic-host variables, binary host variables, LOB host variables, XML host variables, ROWID host variables, and result set locator host variables.
2.
The struct tag can be used to define other data areas, but these cannot be used as host variables.
Embedded SQL programming
37
3.
Dimension must be an integer constant between 1 and 32 767.
4.
_Packed must not be used in C++. Instead, specify #pragma pack(1) prior to the declaration and
#pragma pack() after the declaration.
5.
If using sqlint32 or sqlint64, the header file sqlsystm.h must be included.
6.
_Decimal32, _Decimal64, and _Decimal128 are only supported for C.
Host structure array indicator structure in C and C++ applications that use SQL
The figure shows the valid syntax for host structure array indicator structure declarations.
Host Structure Array Indicator Structure
►► struct { auto extern static const volatile
_Packed
tag
►
► signed short int
var-1
[
dimension-1
] ; }
,
► ▼
variable-name
[
dimension-2
]
=
expression
;
Notes:
1.
The struct tag can be used to define other data areas, but they cannot be used as host variables.
2.
dimension-1 and dimension-2 must both be integer constants between 1 and 32 767.
3.
_Packed must not be used in C++. Instead, specify #pragma pack(1) prior to the declaration and
#pragma pack() after the declaration.
Using pointer data types in C and C++ applications that use SQL
You can also declare host variables that are pointers to the supported C and C++ data types, with the following restrictions.
v
If a host variable is declared as a pointer, then that host variable must be declared with asterisks followed by a host variable. The following examples are all valid: short *mynum; long **mynumptr; char *mychar; char(*mychara)[20]; struct { short mylen; char mydata[30];
} *myvarchar;
/* Ptr to an integer
/* Ptr to a ptr to a long integer
/* Ptr to a single character
/* Ptr to a char array of 20 bytes
/* Ptr to a variable char array of 30
/* bytes.
*/
*/
*/
*/
*/
*/
Note:
Parentheses are only allowed when declaring a pointer to a NUL-terminated character array, in which case they are required. If the parentheses were not used, you would be declaring an array of pointers rather than the desired pointer to an array. For example: char (*a)[10]; char *a[10];
/* pointer to a null-terminated char array */
/* pointer to an array of pointers */ v If a host variable is declared as a pointer, then no other host variable can be declared with that same name within the same source file. For example, the second declaration below would be invalid:
38
IBM i: Embedded SQL programming
►◄
►
char *mychar; char mychar;
/* This declaration is valid
/* But this one is invalid
*/
*/ v
When a host variable is referenced within an SQL statement, that host variable must be referenced exactly as declared, with the exception of pointers to NUL-terminated character arrays. For example, the following declaration required parentheses: char (*mychara)[20]; /* ptr to char array of 20 bytes */
However, the parentheses are not allowed when the host variable is referenced in an SQL statement, such as a SELECT:
EXEC SQL SELECT name INTO :*mychara FROM mytable; v Only the asterisk can be used as an operator over a host variable name.
v The maximum length of a host variable name is affected by the number of asterisks specified, as these asterisks are considered part of the name.
v Pointers to structures are not usable as host variables except for variable character structures. Also, pointer fields in structures are not usable as host variables.
v SQL requires that all specified storage for based host variables be allocated. If the storage is not allocated, unpredictable results can occur.
Using typedef in C and C++ applications that use SQL
You can also use the typedef declarations to define your own identifiers that will be used in place of C type specifiers such as short, float, and double.
The typedef identifiers used to declare host variables must be unique within the program, even if the typedef declarations are in different blocks or procedures. If the program contains BEGIN DECLARE
SECTION and END DECLARE SECTION statements, the typedef declarations do not need to be contained with the BEGIN DECLARE SECTION and END DECLARE SECTION. The typedef identifier will be recognized by the SQL precompiler within the BEGIN DECLARE SECTION. The C and C++ precompilers recognize only a subset of typedef declarations, the same as with host variable declarations.
Examples of valid typedef statements: v Declaring a long typedef and then declaring host variables which reference the typedef.
typedef long int LONG_T;
LONG_T I1, *I2; v The character array length may be specified in either the typedef or on the host variable declaration but not in both.
typedef char NAME_T[30]; typedef char CHAR_T;
CHAR_T name1[30]; /* Valid */
NAME_T name2; /* Valid */
NAME_T name3[10]; /* Not valid for SQL use */ v The SQL TYPE IS statement may be used in a typedef.
typedef SQL TYPE IS CLOB(5K) CLOB_T;
CLOB_T clob_var1; v Storage class (auto, extern, static), volatile, or const qualifiers may be specified on the host variable declaration.
typdef short INT_T; typdef short INT2_T; static INT_T i1; volatile INT2_T i2; v typedefs of structures are supported.
typedef _Packed struct {char dept[3]; char deptname[30]; long Num_employees;} DEPT_T;
DEPT_T dept_rec;
DEPT_T dept_array[20]; /* use for blocked insert or fetch */
Embedded SQL programming
39
Using ILE C compiler external file descriptions in C and C++ applications that use SQL
You can use the C or C++ #pragma mapinc directive with the #include directive to include external file descriptions in your program.
When used with SQL, only a particular format of the #pragma mapinc directive is recognized by the SQL precompiler. If all of the required elements are not specified, the precompiler ignores the directive and does not generate host variable structures. The required elements are: v Include name v Externally described file name v Format name or a list of format names v Options v Conversion options
The library name, union name, conversion options, and prefix name are optional. Although typedef statements coded by the user are not recognized by the precompiler, those created by the #pragma mapinc and #include directives are recognized. SQL supports input, output, both, and key values for the options parameter. For the conversion options, the supported values are D, p, z, _P, and 1BYTE_CHAR.
These options may be specified in any order except that both D and p cannot be specified. Unions declared using the typedef union created by the #pragma mapinc and #include directive cannot be used as host variables in SQL statements; the members of the unions can be used. Structures that contain the typedef structure cannot be used in SQL statements; the structure declared using the typedef can be used.
To retrieve the definition of the sample table DEPARTMENT described in DB2 for i sample tables in the
SQL programming topic collection, you can code the following:
#pragma mapinc ("dept","CORPDATA/DEPARTMENT(*ALL)","both")
#include "dept"
CORPDATA_DEPARTMENT_DEPARTMENT_both_t Dept_Structure;
A host structure named Dept_Structure is defined with the following elements: DEPTNO, DEPTNAME,
MGRNO, and ADMRDEPT. These field names can be used as host variables in SQL statements.
Note:
DATE, TIME, and TIMESTAMP columns generate character host variable definitions. They are treated by SQL with the same comparison and assignment rules as a DATE, TIME, and TIMESTAMP column. For example, a date host variable can be compared only against a DATE column or a character string that is a valid representation of a date.
If the GRAPHIC or VARGRAPHIC column has a UCS-2 CCSID, the generated host variable will have the
UCS-2 CCSID assigned to it. If the GRAPHIC or VARGRAPHIC column has a UTF-16 CCSID, the generated host variable will have the UTF-16 CCSID assigned to it.
Although zoned, binary (with nonzero scale fields), and, optionally, decimal are mapped to character fields in ILE C, SQL will treat these fields as numeric. By using the extended program model (EPM) routines, you can manipulate these fields to convert zoned and packed decimal data. For more information, see the ILE C/C++ Language Reference topic.
|
|
CLOB, BLOB, and DBCLOB columns in the external file are ignored. No host variable definition will be generated in the host structure for these types.
Determining equivalent SQL and C or C++ data types
The precompiler determines the base SQLTYPE and SQLLEN of host variables based on the table. If a host variable appears with an indicator variable, the SQLTYPE is the base SQLTYPE plus one.
40
IBM i: Embedded SQL programming
Table 1. C or C++ declarations mapped to typical SQL data types
C or C++ data type
short int long int long long int decimal(p,s)
_Decimal32
_Decimal64
_Decimal128 float double single-character form
NUL-terminated character form
VARCHAR structured form 448 single-graphic form 468
400 NUL-terminated single-graphic form
VARGRAPHIC structured form
464
996
996
480
480
SQLTYPE of host variable SQLLEN of host variable SQL data type
500 2 SMALLINT
496
492
4
8
INTEGER
BIGINT
484
996 p in byte 1, s in byte 2
4
DECIMAL (p,s)
Treated as DECFLOAT(7) although SQL does not directly support this data type.
DECFLOAT(16)
452
460
4
8
8
16
1 length
DECFLOAT(34)
FLOAT (single precision)
FLOAT (double precision)
CHAR(1)
VARCHAR (length - 1) length
1 length length
VARCHAR (length)
GRAPHIC(1)
VARGRAPHIC (length - 1)
VARGRAPHIC (length)
You can use the following table to determine the C or C++ data type that is equivalent to a given SQL data type.
Table 2. SQL data types mapped to typical C or C++ declarations
SQL data type C or C++ data type
SMALLINT
INTEGER
BIGINT
DECIMAL(p,s) short int long int long long int decimal(p,s)
Notes
No exact equivalent p is a positive integer from 1 to 63, and s is a positive integer from 0 to
63.
Use DECIMAL (p,s).
NUMERIC(p,s) or nonzero scale binary
DECFLOAT(16)
DECFLOAT(34)
FLOAT (single precision)
FLOAT (double precision)
CHAR(1)
CHAR(n)
_Decimal64
_Decimal128 float double single-character form
No exact equivalent
Only supported in C.
Only supported in C.
If n>1, use NUL-terminated character form.
Embedded SQL programming
41
Table 2. SQL data types mapped to typical C or C++ declarations (continued)
SQL data type
VARCHAR(n)
C or C++ data type
NUL-terminated character form
Notes
Allow at least n+1 to accommodate the NUL-terminator. If data can contain character NULs (/0), use
VARCHAR structured form or SQL
VARCHAR.
CLOB
VARCHAR structured form
None
n is a positive integer. The maximum value of n is 32740.
The maximum value of n is 32740.
The SQL VARCHAR form may also be used.
Use SQL TYPE IS to declare a CLOB in C or C++.
GRAPHIC (1)
GRAPHIC (n)
VARGRAPHIC(n) single-graphic form
No exact equivalent
NUL-terminated graphic form
DBCLOB
BINARY
VARBINARY
BLOB
DATE
TIME
VARGRAPHIC structured form
None
None
None
None
NUL-terminated character form
VARCHAR structured form
NUL-terminated character form
VARCHAR structured form
If n > 1, use NUL-terminated graphic form.
If data can contain graphic NUL values (/0/0), use VARGRAPHIC structured form. Allow at least n + 1 to accommodate the NUL-terminator.
n is a positive integer. The maximum value of n is 16370.
Use SQL TYPE IS to declare a
DBCLOB in C or C++.
Use SQL TYPE IS to declare a
BINARY in C or C++.
Use SQL TYPE IS to declare a
VARBINARY in C or C++.
Use SQL TYPE IS to declare a BLOB in C or C++.
If the format is *USA, *ISO, *JIS, or
*EUR, allow at least 11 characters to accommodate the NUL-terminator. If the format is *MDY, *YMD, or *DMY, allow at least 9 characters to accommodate the NUL-terminator. If the format is *JUL, allow at least 7 characters to accommodate the
NUL-terminator.
If the format is *USA, *ISO, *JIS, or
*EUR, allow at least 10 characters. If the format is *MDY, *YMD, or *DMY, allow at least 8 characters. If the format is *JUL, allow at least 6 characters.
Allow at least 7 characters (9 to include seconds) to accommodate the
NUL-terminator.
Allow at least 6 characters; 8 to include seconds.
42
IBM i: Embedded SQL programming
|
|
|
|
|
|
|
|
|
|
Table 2. SQL data types mapped to typical C or C++ declarations (continued)
SQL data type
TIMESTAMP
C or C++ data type
NUL-terminated character form
XML
VARCHAR structured form
None
Notes
Allow at least 20 characters (33 to include all fractional seconds) to accommodate the NUL-terminator. If n is less than 33, truncation occurs on the fractional seconds part.
Allow at least 19 characters. To include all fractional seconds, allow
32 characters. If the number of characters is less than 32, truncation occurs on the fractional seconds part.
Use SQL TYPE IS to declare XML in
C or C++.
DATALINK
ROWID
Not supported
None
Result set locator None
Use SQL TYPE IS to declare a
ROWID in C or C++.
Use SQL TYPE IS to declare a result set locator in C or C++.
Notes on C and C++ variable declaration and usage
Single quotation marks (') and quotation marks (") have different meanings in C, C++, and SQL.
C and C++ use quotation marks to delimit string constants and single quotation marks to delimit character constants. In contrast, SQL uses quotation marks for delimited identifiers and uses single quotation marks to delimit character string constants. Character data in SQL is distinct from integer data.
Using indicator variables in C and C++ applications that use SQL
An indicator variable is a two-byte integer (short int).
You can also specify an indicator structure (defined as an array of halfword integer variables) to support a host structure.
Indicator variables are declared in the same way as host variables. The declarations of the two can be mixed in any way that seems appropriate to you.
Example
Given the statement:
EXEC SQL FETCH CLS_CURSOR INTO :ClsCd,
:Day :DayInd,
:Bgn :BgnInd,
:End :EndInd;
Variables can be declared as follows:
EXEC SQL BEGIN DECLARE SECTION; char ClsCd[8]; char Bgn[9]; char End[9]; short Day, DayInd, BgnInd, EndInd;
EXEC SQL END DECLARE SECTION;
Related reference
:
References to variables
Embedded SQL programming
43
“Indicator variables in applications that use SQL” on page 4
An indicator variable is a halfword integer variable used to communicate additional information about its associated host variable.
Coding SQL statements in COBOL applications
There are unique application and coding requirements for embedding SQL statements in a COBOL program. In this topic, requirements for host structures and host variables are defined.
The IBM i products support more than one COBOL compiler. The IBM DB2 Query Manager and SQL
Development Kit for i licensed program only supports the OPM COBOL and ILE COBOL programming languages.
Note:
Related concepts
:
“Writing applications that use SQL” on page 2
You can create database applications in host languages that use DB2 for i SQL statements and functions.
Related reference
:
“Example programs: Using DB2 for i statements” on page 149
Here is a sample application that shows how to code SQL statements in each of the languages that DB2 for i supports.
“Example: SQL statements in COBOL and ILE COBOL programs” on page 157
This example program is written in the COBOL programming language.
Defining the SQL communication area in COBOL applications that use
SQL
A COBOL program can be written to use the SQL communication area (SQLCA) to check return status for embedded SQL statements, or the program can use the SQL diagnostics area to check return status.
To use the SQL diagnostics area instead of the SQLCA, use the SET OPTION SQL statement with the option SQLCA = *NO.
When using the SQLCA, a COBOL program that contains SQL statements must include one or both of the following: v An SQLCODE variable declared as PICTURE S9(9) BINARY, PICTURE S9(9) COMP-4, or PICTURE
S9(9) COMP.
v
An SQLSTATE variable declared as PICTURE X(5).
Or, v An SQLCA (which contains an SQLCODE and SQLSTATE variable).
The SQLCODE and SQLSTATE values are set by the database manager after each SQL statement is run.
An application can check the SQLCODE or SQLSTATE value to determine whether the last SQL statement was successful.
The SQLCA can be coded in a COBOL program either directly or by using the SQL INCLUDE statement.
When coding it directly, make sure it is initialized. Using the SQL INCLUDE statement requests the inclusion of a standard declaration:
EXEC SQL INCLUDE SQLCA END-EXEC.
44
IBM i: Embedded SQL programming
The SQLCODE, SQLSTATE, and SQLCA variable declarations must appear in the WORKING-STORAGE
SECTION or LINKAGE SECTION of your program and can be placed wherever a record description entry can be specified in those sections.
When you use the INCLUDE statement, the SQL COBOL precompiler includes COBOL source statements for the SQLCA:
01 SQLCA.
05 SQLCAID
05 SQLCABC
05 SQLCODE
05 SQLERRM.
49 SQLERRML
49 SQLERRMC
05 SQLERRP
05 SQLERRD
PIC X(8). VALUE X"0000000000000000".
PIC S9(9) BINARY.
PIC S9(9) BINARY.
PIC S9(4) BINARY.
PIC X(70).
PIC X(8).
OCCURS 6 TIMES
PIC S9(9) BINARY.
05 SQLWARN.
10 SQLWARN0
10 SQLWARN1
10 SQLWARN2
10 SQLWARN3
10 SQLWARN4
10 SQLWARN5
10 SQLWARN6
10 SQLWARN7
10 SQLWARN8
10 SQLWARN9
10 SQLWARNA
05 SQLSTATE
PIC X.
PIC X.
PIC X.
PIC X.
PIC X.
PIC X.
PIC X.
PIC X.
PIC X.
PIC X.
PIC X.
PIC X(5).
For ILE COBOL, the SQLCA is declared using the GLOBAL clause. SQLCODE is replaced with
SQLCADE when a declaration for SQLCODE is found in the program and the SQLCA is provided by the precompiler. SQLSTATE is replaced with SQLSTOTE when a declaration for SQLSTATE is found in the program and the SQLCA is provided by the precompiler.
Related concepts
:
“Using the SQL diagnostics area” on page 7
The SQL diagnostics area is used to keep the returned information for an SQL statement that has been run in a program. It contains all the information that is available to you as an application programmer through the SQLCA.
Related reference
:
SQL communication area
Defining SQL descriptor areas in COBOL applications that use SQL
There are two types of SQL descriptor areas (SQLDAs). One is defined with the ALLOCATE
DESCRIPTOR statement. The other is defined using the SQLDA structure. In this topic, only the SQLDA form is discussed.
The following statements can use an SQLDA: v EXECUTE...USING DESCRIPTOR descriptor-name v FETCH...USING DESCRIPTOR descriptor-name v OPEN...USING DESCRIPTOR descriptor-name v CALL...USING DESCRIPTOR descriptor-name v
DESCRIBE statement-name INTO descriptor-name v DESCRIBE CURSOR cursor-name INTO descriptor-name v DESCRIBE INPUT statement-name INTO descriptor-name v DESCRIBE PROCEDURE procedure-name INTO descriptor-name
Embedded SQL programming
45
v DESCRIBE TABLE host-variable INTO descriptor-name v
PREPARE statement-name INTO descriptor-name
Unlike the SQLCA, there can be more than one SQLDA in a program. The SQLDA can have any valid name. An SQLDA can be coded in a COBOL program directly or added with the INCLUDE statement.
Using the SQL INCLUDE statement requests the inclusion of a standard SQLDA declaration:
EXEC SQL INCLUDE SQLDA END-EXEC.
The COBOL declarations included for the SQLDA are:
1 SQLDA.
05 SQLDAID
05 SQLDABC
05 SQLN
05 SQLD
PIC X(8).
PIC S9(9) BINARY.
PIC S9(4) BINARY.
PIC S9(4) BINARY.
05 SQLVAR OCCURS 0 TO 409 TIMES DEPENDING ON SQLD.
10 SQLVAR1.
15 SQLTYPE PIC S9(4) BINARY.
15 SQLLEN PIC S9(4) BINARY.
15 FILLER REDEFINES SQLLEN.
20 SQLPRECISION PIC X.
20 SQLSCALE PIC X.
15 SQLRES PIC X(12).
15 SQLDATA POINTER.
15 SQL-RESULT-SET-LOCATOR-R REDEFINES SQLDATA.
20 SQL-RESULT-SET-LOCATOR PIC S9(18) BINARY.
15 SQLIND POINTER.
15 SQL-ROW-CHANGE-SQL-R REDEFINES SQLIND.
20 SQLD-ROW-CHANGE FIC S9(9) BINARY.
15 SQL-RESULT-SET-ROWS-R PIC REDEFINES SQLIND.
20 SQLD-RESULT-SET-ROWS PIC S9(9) BINARY.
15 SQLNAME.
49 SQLNAMEL PIC S9(4) BINARY.
49 SQLNAMEC PIC X(30).
10 SQLVAR2 REDEFINES SQLVAR1.
15 SQLVAR2-RESERVED-1 PIC S9(9) BINARY.
15 SQLLONGLEN REDEFINEDS SQLVAR2-RESERVED-1
PIC S9(9) BINARY.
15 SQLVAR2-RESERVED-2 PIC X(28).
15 SQLDATALEN POINTER.
15 SQLDATATYPE-NAME.
49 SQLDATATYPE_NAMEL PIC S9(4) BINARY.
49 SQLDATATYPE_NAMEC PIC X(30).
Figure 1. INCLUDE SQLDA declarations for COBOL
SQLDA declarations must appear in the WORKING-STORAGE SECTION or LINKAGE SECTION of your program and can be placed wherever a record description entry can be specified in those sections. For
ILE COBOL, the SQLDA is declared using the GLOBAL clause.
Dynamic SQL is an advanced programming technique. With dynamic SQL, your program can develop and then run SQL statements while the program is running. A SELECT statement with a variable SELECT list (that is, a list of the data to be returned as part of the query) that runs dynamically requires an SQL descriptor area (SQLDA). This is because you cannot know in advance how many or what type of variables to allocate in order to receive the results of the SELECT.
Related concepts
:
Dynamic SQL applications
Related reference
:
SQL descriptor area
46
IBM i: Embedded SQL programming
Embedding SQL statements in COBOL applications that use SQL
SQL statements can be coded in COBOL program sections as in this table.
SQL statement Program section
WORKING-STORAGE SECTION or LINKAGE SECTION
BEGIN DECLARE SECTION
END DECLARE SECTION
DECLARE VARIABLE
DECLARE STATEMENT
WORKING-STORAGE SECTION or LINKAGE SECTION
INCLUDE SQLCA
INCLUDE SQLDA
INCLUDE member-name
Other
DATA DIVISION or PROCEDURE DIVISION
PROCEDURE DIVISION
Each SQL statement in a COBOL program must begin with EXEC SQL and end with END-EXEC. If the
SQL statement appears between two COBOL statements, the period is optional and might not be appropriate. The EXEC SQL keywords must appear all on one line, but the remainder of the statement can appear on the next and subsequent lines.
Example
An UPDATE statement coded in a COBOL program might be coded as follows:
EXEC SQL
UPDATE DEPARTMENT
SET MGRNO = :MGR-NUM
WHERE DEPTNO = :INT-DEPT
END-EXEC.
Comments in COBOL applications that use SQL
In addition to SQL comments (--), you can include COBOL comment lines (* or / in column 7) within embedded SQL statements except between the keywords EXEC and SQL. COBOL debugging lines (D in column 7) are treated as comment lines by the precompiler.
Continuation for SQL statements in COBOL applications that use SQL
The line continuation rules for SQL statements are the same as those for other COBOL statements, except that EXEC SQL must be specified within one line.
If you continue a string constant from one line to the next, the first nonblank character in the next line must be either an apostrophe or a quotation mark. If you continue a delimited identifier from one line to the next, the first nonblank character in the next line must be either an apostrophe or a quotation mark.
Constants containing DBCS data can be continued across multiple lines by placing the shift-in character in column 72 of the continued line and the shift-out after the first string delimiter of the continuation line.
This SQL statement has a valid graphic constant of G'<AABBCCDDEEFFGGHHIIJJKK>'. The redundant shifts are removed.
Embedded SQL programming
47
*...+....1....+....2....+....3....+....4....+....5....+....6....+....7....+....8
EXEC SQL
SELECT * FROM GRAPHTAB
’<CCDDEEFFGGHHIIJJKK>’
WHERE GRAPHCOL = G’<AABB>
END-EXEC.
Including code in COBOL applications that use SQL
SQL statements or COBOL host variable declaration statements can be included by embedding the following SQL statement in the source code where the statements are to be embedded.
EXEC SQL INCLUDE member-name END-EXEC.
COBOL COPY statements cannot be used to include SQL statements or declarations of COBOL host variables that are referenced in SQL statements.
Margins in COBOL applications that use SQL
You must code SQL statements in columns 12 through 72. If EXEC SQL starts before the specified margin
(that is, before column 12), the SQL precompiler does not recognize the statement.
Sequence numbers in COBOL applications that use SQL
The source statements generated by the SQL precompiler are generated with the same sequence number as the SQL statement.
Names in COBOL applications that use SQL
Any valid COBOL variable name can be used for a host variable and is subject to the following restrictions:
Do not use host variable names or external entry names that begin with 'SQL', 'RDI', or 'DSN'. These names are reserved for the database manager.
Using structures that contain FILLER may not work as expected in an SQL statement. It is recommended that all fields within a COBOL structure be named to avoid unexpected results.
COBOL compile-time options in COBOL applications that use SQL
The COBOL PROCESS statement can be used to specify the compile-time options for the COBOL compiler.
Although the PROCESS statement will be recognized by the COBOL compiler when it is called by the precompiler to create the program; the SQL precompiler itself does not recognize the PROCESS statement.
Therefore, options that affect the syntax of the COBOL source such as APOST and QUOTE should not be specified in the PROCESS statement. Instead *APOST and *QUOTE should be specified in the OPTION parameter of the CRTSQLCBL and CRTSQLCBLI commands.
Statement labels in COBOL applications that use SQL
Executable SQL statements in the PROCEDURE DIVISION can be preceded by a paragraph name.
WHENEVER statement in COBOL applications that use SQL
The target for the GOTO clause in an SQL WHENEVER statement must be a section name or unqualified paragraph name in the PROCEDURE DIVISION.
Multiple source COBOL programs and the SQL COBOL precompiler
The SQL COBOL precompiler does not support precompiling multiple source programs separated with the PROCESS statement.
Using host variables in COBOL applications that use SQL
All host variables used in SQL statements must be explicitly declared prior to their first use.
48
IBM i: Embedded SQL programming
The COBOL statements that are used to define the host variables should be preceded by a BEGIN
DECLARE SECTION statement and followed by an END DECLARE SECTION statement. If a BEGIN
DECLARE SECTION and END DECLARE SECTION are specified, all host variable declarations used in
SQL statements must be between the BEGIN DECLARE SECTION and the END DECLARE SECTION statements.
All host variables within an SQL statement must be preceded by a colon (:).
Host variables cannot be records or elements.
To accommodate using dashes within a COBOL host variable name, blanks must precede and follow a minus sign.
Declaring host variables in COBOL applications that use SQL
The COBOL precompiler only recognizes a subset of valid COBOL declarations as valid host variable declarations.
Numeric host variables in COBOL applications that use SQL:
This figure shows the syntax for valid integer host variable declarations.
BIGINT and INTEGER and SMALLINT
IS
IS USAGE
►► 01
77
level-1 variable-name
► BINARY
COMPUTATIONAL-4
COMP-4
COMPUTATIONAL-5
COMP-5
VALUE
PICTURE
PIC
IS
picture-string numeric-constant
.
►
►◄
Notes:
1.
BINARY, COMPUTATIONAL-4, COMP-4 , COMPUTATIONAL-5, and COMP-5 are equivalent. A portable application should code BINARY, because COMPUTATIONAL-4, COMP-4
COMPUTATIONAL-5, and COMP-5 are IBM extensions that are not supported in International
Organization for Standardization (ISO)/ANSI COBOL. The picture-string associated with these types must have the form S9(i)V9(d) (or S9...9V9...9, with i and d instances of 9). i + d must be less than or equal to 18.
2.
level-1 indicates a COBOL level between 2 and 48.
3.
COMPUTATIONAL-5, and COMP-5 are only supported for ILE COBOL.
The following figure shows the syntax for valid decimal host variable declarations.
DECIMAL
IS
IS USAGE
►► 01
77
level-1 variable-name
PICTURE
PIC
picture-string
►
Embedded SQL programming
49
► PACKED-DECIMAL
COMPUTATIONAL-3
COMP-3
COMPUTATIONAL
COMP
VALUE
IS
numeric-constant
.
►◄
Notes:
1.
PACKED-DECIMAL, COMPUTATIONAL-3, and COMP-3 are equivalent. A portable application should code PACKED-DECIMAL, because COMPUTATIONAL-3 and COMP-3 are IBM extensions that are not supported in ISO/ANS COBOL. The picture-string associated with these types must have the form S9(i)V9(d) (or S9...9V9...9, with i and d instances of 9). i + d must be less than or equal to 63.
2.
COMPUTATIONAL and COMP are equivalent. The picture strings associated with these and the data types they represent are product-specific. Therefore, COMP and COMPUTATIONAL should not be used in a portable application. In an OPM COBOL program, the picture-string associated with these types must have the form S9(i)V9(d) (or S9...9V9...9, with i and d instances of 9). i + d must be less than or equal to 63.
3.
level-1 indicates a COBOL level between 2 and 48.
The following figure shows the syntax for valid numeric host variable declarations.
Numeric
IS
►► 01
77
level-1 variable-name
PICTURE
PIC
picture-string
►
► .
►◄
IS IS
USAGE VALUE
numeric-constant
DISPLAY
display clause
display clause:
DISPLAY
SIGN
IS
LEADING SEPARATE
CHARACTER
Notes:
1.
The picture-string associated with SIGN LEADING SEPARATE and DISPLAY must have the form
S9(i)V9(d) (or S9...9V9...9, with i and d instances of 9). i + d must be less than or equal to 18.
2.
level-1 indicates a COBOL level between 2 and 48.
Floating-point host variables in COBOL applications that use SQL:
This figure shows the syntax for valid floating-point host variable declarations. Floating-point host variables are only supported for ILE COBOL.
50
IBM i: Embedded SQL programming
Floating-point
►► 01
77
level-1 variable-name
USAGE
IS
►
VALUE
IS
numeric-constant
.
COMPUTATIONAL-1
COMP-1
COMPUTATIONAL-2
COMP-2
Notes:
1.
COMPUTATIONAL-1 and COMP-1 are equivalent. COMPUTATIONAL-2 and COMP-2 are equivalent.
2.
level-1 indicates a COBOL level between 2 and 48.
Character host variables in COBOL applications that use SQL:
There are two valid forms of character host variables: fixed-length strings and varying-length strings.
Fixed-length character strings
IS
►► 01
77
level-1 variable-name
PICTURE
PIC
picture-string
USAGE
IS
►
DISPLAY
► .
►◄
IS
VALUE
string-constant
Notes:
1.
The picture-string associated with these forms must be X(m) (or XXX...X, with m instances of X) with 1
≤
m ≤ 32 766.
2.
level-1 indicates a COBOL level between 2 and 48.
Varying-length character strings
IS
►► 01
level-1 variable-name
.
49
var-1
PICTURE
PIC
picture-string-1
►
►
►◄
Embedded SQL programming
51
►
USAGE
► 49
var-2
IS
PICTURE
PIC
BINARY
COMPUTATIONAL-4
COMP-4
COMPUTATIONAL-5
COMP-5
IS
VALUE
picture-string-2
IS
numeric-constant
USAGE
IS
DISPLAY
.
►
VALUE
IS
string-constant
.
►
►
►◄
Notes:
1.
The picture-string-1 associated with these forms must be S9(m) or S9...9 with m instances of 9. m must be from 1 to 4.
Note that the database manager uses the full size of the S9(m) variable even though OPM COBOL only recognizes values up to the specified precision. This can cause data truncation errors when
COBOL statements are being run, and might effectively limit the maximum length of variable-length character strings to the specified precision.
2.
The picture-string-2 associated with these forms must be either X(m), or XX...X, with m instances of X, and with 1 ≤ m ≤ 32 740.
3.
var-1 and var-2 cannot be used as host variables.
4.
level-1 indicates a COBOL level between 2 and 48.
5.
COMPUTATIONAL-5 and COMP-5 are only supported for ILE COBOL.
Graphic host variables in COBOL applications that use SQL:
Graphic host variables are only supported in ILE COBOL.
There are two valid forms of graphic host variables: v Fixed-length graphic strings v Varying-length graphic strings
Fixed-length graphic strings
IS
►► 01
77
level-1 variable-name
PICTURE
PIC
picture-string
►
52
IBM i: Embedded SQL programming
►
USAGE
IS
DISPLAY-1
NATIONAL
VALUE
IS
string-constant
.
►◄
Notes:
1.
The picture-string associated with the DISPLAY-1 form must be G(m) (or GGG...G, with m instances of
G) or N(m) (or NNN...N, with m instances of N) with 1 ≤ m ≤ 16 383.
2.
The picture-string associated with the NATIONAL form must be N(m) (or NNN...N, with m instances of N) with 1 ≤ m ≤ 16 383. NATIONAL is only supported for ILE COBOL. The CCSID is always 1200.
You cannot specify a variable that is declared as NATIONAL on the DECLARE VARIABLE statement.
3.
level-1 indicates a COBOL level between 2 and 48.
Varying-length graphic strings
IS
►► 01
level-1 variable-name
.
49
var-1
PICTURE
PIC
picture-string-1
►
►
USAGE
IS
BINARY
COMPUTATIONAL-4
COMP-4
COMPUTATIONAL-5
COMP-5
VALUE
IS
numeric-constant
IS
► 49
var-2
PICTURE
PIC
►
IS
VALUE
string-constant picture-string-2
.
USAGE
IS
.
DISPLAY-1
NATIONAL
►
►
►◄
Notes:
1.
The picture-string-1 associated with these forms must be S9(m) or S9...9 with m instances of 9. m must be from 1 to 4.
Note that the database manager uses the full size of the S9(m) variable even though OPM COBOL only recognizes values up to the specified precision. This can cause data truncation errors when
COBOL statements are being run, and might effectively limit the maximum length of variable-length graphic strings to the specified precision.
2.
The picture-string-2 associated with the DISPLAY-1 form must be G(m), GG...G with m instances of G,
N(m), or NN...N with m instances of N, and with 1 ≤ m ≤ 16 370.
3.
The picture-string-2 associated with the NATIONAL form must be N(m) (or NNN...N, with m instances of N) with 1 ≤ m ≤ 16 383. NATIONAL is only supported for ILE COBOL. The CCSID is always 1200.
You cannot specify a variable that is declared as NATIONAL on the DECLARE VARIABLE statement.
4.
The variables var-1 and var-2 cannot be used as host variables.
5.
level-1 indicates a COBOL level between 2 and 48.
Embedded SQL programming
53
6.
COMPUTATIONAL-5 and COMP-5 are only supported for ILE COBOL.
Binary host variables in COBOL applications that use SQL:
COBOL does not have variables that correspond to the SQL binary data types. To create host variables that can be used with these data types, use the SQL TYPE IS clause. The SQL precompiler replaces this declaration with a COBOL language structure in the output source member.
BINARY and VARBINARY
IS
USAGE
►► 01
variable-name
SQL TYPE IS BINARY
VARBINARY
BINARY VARYING
(
length
) .
►◄
Notes:
1.
For BINARY host variables, the length must be in the range 1 to 32766.
2.
For VARBINARY or BINARY VARYING host variables, the length must be in the range 1 to 32740.
3.
SQL TYPE IS, BINARY, VARBINARY, and BINARY VARYING can be in mixed case.
BINARY Example
The following declaration:
01 MY-BINARY SQL TYPE IS BINARY(200).
Results in the generation of the following code:
01 MY-BINARY PIC X(200).
VARBINARY Example
The following declaration:
01 MY-VARBINARY SQL TYPE IS VARBINARY(250).
Results in the generation of the following structure:
01 MY-VARBINARY.
49 MY-VARBINARY-LENGTH PIC 9(5) BINARY.
49 MY-VARBINARY-DATA PIC X(250).
LOB host variables in COBOL applications that use SQL:
COBOL does not have variables that correspond to the SQL data types for LOBs (large objects). To create host variables that can be used with these data types, use the SQL TYPE IS clause. The SQL precompiler replaces this declaration with a COBOL language structure in the output source member.
LOB host variables are only supported in ILE COBOL.
LOB host variables
IS
USAGE
►► 01
variable-name
SQL TYPE IS CLOB
DBCLOB
BLOB
(
lob-length
K
M
) .
►◄
54
IBM i: Embedded SQL programming
Notes:
1.
For BLOB and CLOB, 1 ≤ lob-length ≤ 15,728,640
2.
For DBCLOB, 1 ≤ lob-length ≤ 7,864,320
3.
SQL TYPE IS, BLOB, CLOB, DBCLOB can be in mixed case.
CLOB example
The following declaration:
01 MY-CLOB SQL TYPE IS CLOB(16384).
Results in the generation of the following structure:
01 MY-CLOB.
49 MY-CLOB-LENGTH PIC 9(9) BINARY.
49 MY-CLOB-DATA PIC X(16384).
DBCLOB example
The following declaration:
01 MY-DBCLOB SQL TYPE IS DBCLOB(8192).
Results in the generation of the following structure:
01 MY-DBCLOB.
49 MY-DBCLOB-LENGTH PIC 9(9) BINARY.
49 MY-DBCLOB-DATA PIC G(8192) DISPLAY-1.
BLOB example
The following declaration:
01 MY-BLOB SQL TYPE IS BLOB(16384).
Results in the generation of the following structure:
01 MY-BLOB.
49 MY-BLOB-LENGTH PIC 9(9) BINARY.
49 MY-BLOB-DATA PIC X(16384).
LOB locator
IS
USAGE
►► 01
variable-name
SQL TYPE IS CLOB-LOCATOR
DBCLOB-LOCATOR
BLOB-LOCATOR
.
►◄
Notes:
1.
SQL TYPE IS, BLOB-LOCATOR, CLOB-LOCATOR, DBCLOB-LOCATOR can be in mixed case.
2.
LOB locators cannot be initialized in the SQL TYPE IS statement.
CLOB and DBCLOB locators have similar syntax.
BLOB locator example
The following declaration:
01 MY-LOCATOR SQL TYPE IS BLOB_LOCATOR.
Embedded SQL programming
55
Results in the following generation:
01 MY-LOCATOR PIC 9(9) BINARY.
LOB file reference variable
IS
USAGE
►► 01
variable-name
SQL TYPE IS CLOB-FILE
DBCLOB-FILE
BLOB-FILE
.
►◄
Note:
SQL TYPE IS, BLOB-FILE, CLOB-FILE, DBCLOB-FILE can be in mixed case.
BLOB file reference example
The following declaration:
01 MY-FILE SQL TYPE IS BLOB-FILE.
Results in the generation of the following structure:
01 MY-FILE.
49 MY-FILE-NAME-LENGTH PIC S9(9) COMP-5.
49 MY-FILE-DATA-LENGTH PIC S9(9) COMP-5.
49 MY-FILE-FILE-OPTIONS PIC S9(9) COMP-5.
49 MY-FILE-NAME PIC X(255).
CLOB and DBCLOB file reference variables have similar syntax.
The precompiler generates declarations for the following file option constants. You can use these constants to set the xxx-FILE-OPTIONS variable when you use file reference host variables.
v SQL_FILE_READ (2) v SQL_FILE_CREATE (8) v SQL_FILE_OVERWRITE (16) v SQL_FILE_APPEND (32)
Related reference
:
LOB file reference variables
XML host variables in COBOL applications that use SQL:
COBOL does not have variables that correspond to the SQL data type for XML. To create host variables that can be used with this data type, use the SQL TYPE IS clause. The SQL precompiler replaces this declaration with a COBOL language structure in the output source member.
XML host variables are only supported in ILE COBOL.
XML host variables
IS
USAGE
►► 01
variable-name
SQL TYPE IS XML AS CLOB
DBCLOB
BLOB
(
lob-length
K
M
) ►
56
IBM i: Embedded SQL programming
► .
►◄
Notes:
1.
For BLOB and CLOB, 1 ≤ lob-length ≤ 15,728,640
2.
For DBCLOB, 1 ≤ lob-length ≤ 7,864,320
3.
SQL TYPE IS, XML AS, BLOB, CLOB, DBCLOB can be in mixed case.
4.
The CCSID value for an XML host variable can be explicitly set by the DECLARE VARIABLE statement. Otherwise, the value specified by the SQL_XML_DATA_CCSID QAQQINI option will be used. The default for this QAQQINI option is CCSID 1208.
XML example
The following declaration:
01 MY-XML SQL TYPE IS CLOB(5000).
Results in the generation of the following structure:
01 MY-XML.
49 MY-XML-LENGTH PIC 9(9) BINARY.
49 MY-XML-DATA PIC X(5000).
XML locator
IS
USAGE
►► 01
variable-name
SQL TYPE IS XML-LOCATOR .
►◄
Notes:
1.
SQL TYPE IS, XML AS, XML-LOCATOR can be in mixed case.
2.
LOB locators cannot be initialized in the SQL TYPE IS statement.
XML locator example
The following declaration:
01 MY-LOCATOR SQL TYPE IS XML-LOCATOR.
Results in the following generation:
01 MY-LOCATOR PIC 9(9) BINARY.
XML file reference variable
IS
USAGE
►► 01
variable-name
SQL TYPE IS XML AS CLOB-FILE
DBCLOB-FILE
BLOB-FILE
.
Note:
SQL TYPE IS, XML AS, BLOB-FILE, CLOB-FILE, DBCLOB-FILE can be in mixed case.
►◄
Embedded SQL programming
57
XML file reference example
The following declaration:
01 MY-FILE SQL TYPE IS XML AS CLOB-FILE.
Results in the generation of the following structure:
01 MY-FILE.
49 MY-FILE-NAME-LENGTH PIC S9(9) COMP-5.
49 MY-FILE-DATA-LENGTH PIC S9(9) COMP-5.
49 MY-FILE-FILE-OPTIONS PIC S9(9) COMP-5.
49 MY-FILE-NAME PIC X(255).
The precompiler generates declarations for the following file option constants. You can use these constants to set the xxx-FILE-OPTIONS variable when you use file reference host variables.
v SQL_FILE_READ (2) v
SQL_FILE_CREATE (8) v SQL_FILE_OVERWRITE (16) v SQL_FILE_APPEND (32)
Datetime host variables in COBOL applications that use SQL:
This figure shows the syntax for valid date, time, and timestamp host variable declarations. Datetime host variables are supported only for ILE COBOL.
Datetime host variable
|||||||||
►► 01
77
level-1 variable-name
FORMAT
OF
DATE
TIME
TIMESTAMP
IS
format-options
►◄
IS IS
SIZE
integer
Notes:
1.
level-1 indicates a COBOL level between 2 and 48.
2.
format-options indicates valid datetime options that are supported by the COBOL compiler. See the ILE
|
COBOL Language Reference manual for details.
3.
The value for the TIMESTAMP SIZE integer must be 19 to 32.
ROWID host variables in COBOL applications that use SQL:
COBOL does not have a variable that corresponds to the SQL data type ROWID. To create host variables that can be used with this data type, use the SQL TYPE IS clause. The SQL precompiler replaces this declaration with a COBOL language structure in the output source member.
ROWID
►► 01
variable-name
SQL TYPE IS ROWID .
►◄
Note:
SQL TYPE IS ROWID can be in mixed case.
58
IBM i: Embedded SQL programming
ROWID example
The following declaration:
01 MY-ROWID SQL TYPE IS ROWID.
Results in the generation of the following structure:
01 MY-ROWID.
49 MY-ROWID-LENGTH PIC 9(2) BINARY.
49 MY-ROWID-DATA PIC X(40).
Result set locator host variables in COBOL applications that use SQL:
COBOL does not have a variable that corresponds to the SQL result set locator data type. To create host variables that can be used with this data type, use the SQL TYPE IS clause. The SQL precompiler replaces this declaration with a COBOL language structure in the output source member.
Result set locator
IS
USAGE
►► 01
variable-name
SQL TYPE IS RESULT_SET_LOCATOR .
►◄
Note:
SQL TYPE IS RESULT_SET_LOCATOR can be in mixed case.
Result set locator example
The following declaration:
01 RSLOC1 SQL TYPE IS RESULT_SET_LOCATOR.
Results in the generation of the following structure:
01 RSLOC1 PIC 9(18) BINARY.
Using host structures in COBOL applications that use SQL
A host structure is a named set of host variables that is defined in your program's DATA DIVISION.
Host structures have a maximum of two levels, even though the host structure might itself occur within a multilevel structure. An exception is the declaration of a varying-length character string, which requires another level that must be level 49.
A host structure name can be a group name whose subordinate levels name basic data items. For example:
01 A
02 B
03 C1 PICTURE ...
03 C2 PICTURE ...
In this example, B is the name of a host structure consisting of the basic items C1 and C2.
When writing an SQL statement using a qualified host variable name (for example, to identify a field within a structure), use the name of the structure followed by a period and the name of the field. For example, specify B.C1 rather than C1 OF B or C1 IN B. However, this guideline applies only to qualified names within SQL statements; you cannot use this technique for writing qualified names in COBOL statements.
A host structure is considered complete if any of the following items are found:
Embedded SQL programming
59
v A COBOL item that must begin in area A v
Any SQL statement (except SQL INCLUDE)
After the host structure is defined, you can refer to it in an SQL statement instead of listing the several host variables (that is, the names of the data items that comprise the host structure).
For example, you can retrieve all column values from selected rows of the table CORPDATA.EMPLOYEE
with:
01 PEMPL.
10 EMPNO
10 MIDINIT
10 LASTNAME.
PIC X(6).
10 FIRSTNME.
49 FIRSTNME-LEN PIC S9(4) USAGE BINARY.
49 FIRSTNME-TEXT PIC X(12).
PIC X(1).
49 LASTNAME-LEN PIC S9(4) USAGE BINARY.
49 LASTNAME-TEXT PIC X(15).
10 WORKDEPT PIC X(3).
...
MOVE "000220" TO EMPNO.
...
EXEC SQL
SELECT *
INTO :PEMPL
FROM CORPDATA.EMPLOYEE
WHERE EMPNO = :EMPNO
END-EXEC.
Notice that in the declaration of PEMPL, two varying-length string elements are included in the structure:
FIRSTNME and LASTNAME.
Host structure in COBOL applications that use SQL
This figure shows the syntax for the valid host structure.
►►
level-1 variable-name
.
►
► ▼
level-2 var-1
IS
PICTURE
PIC
picture-string floating-point
.
.
varchar-string
.
.
vargraphic-string
.
usage-clause
.
binary
.
lob
.
xml
.
datetime
.
rowid
.
result-set-locator
.
usage-clause:
►◄
60
IBM i: Embedded SQL programming
USAGE
IS
VALUE
IS
constant
display-clause:
DISPLAY
SIGN
IS
LEADING SEPARATE
CHARACTER
floating-point:
BINARY
COMPUTATIONAL-4
COMP-4
COMPUTATIONAL-5
COMP-5
PACKED-DECIMAL
COMPUTATIONAL-3
COMP-3
COMPUTATIONAL
COMP
DISPLAY
display-clause
DISPLAY-1
NATIONAL
USAGE
IS
VALUE
IS
constant
COMPUTATIONAL-1
COMP-1
COMPUTATIONAL-2
COMP-2
varchar-string:
49
var-2
PICTURE
PIC
IS
picture-string-1
►
USAGE
► 49
var-3
IS
PICTURE
PIC
BINARY
COMPUTATIONAL-4
COMP-4
COMPUTATIONAL-5
COMP-5
IS
VALUE
picture-string-2
IS
numeric-constant
.
Embedded SQL programming
61
►
►
►
►
USAGE
IS
DISPLAY
VALUE
IS
constant
vargraphic-string:
49
var-2
PICTURE
PIC
IS
picture-string-1
USAGE
IS
BINARY
COMPUTATIONAL-4
COMP-4
COMPUTATIONAL-5
COMP-5
►
VALUE
IS
numeric-constant
.
► 49
var-3
PICTURE
PIC
►
IS
VALUE
constant
IS
picture-string-2
USAGE
IS
DISPLAY-1
NATIONAL
binary:
USAGE
IS
SQL TYPE IS BINARY
VARBINARY
BINARY VARYING
(
length
)
lob:
USAGE
IS
SQL TYPE IS CLOB
DBCLOB
(
BLOB
CLOB-LOCATOR
lob-length
DBCLOB-LOCATOR
BLOB-LOCATOR
CLOB-FILE
DBCLOB-FILE
BLOB-FILE
K
M
)
62
IBM i: Embedded SQL programming
►
►
►
xml:
USAGE
IS
SQL TYPE IS XML AS
XML AS
CLOB
DBCLOB
BLOB
XML-LOCATOR
CLOB-FILE
(
DBCLOB-FILE
lob-length
BLOB-FILE
K
M
)
|||||||||
datetime:
variable-name
FORMAT
OF
DATE
TIME
TIMESTAMP
IS
IS
format-options
IS
SIZE
integer
rowid:
SQL TYPE IS ROWID
result-set-locator:
SQL TYPE IS RESULT_SET_LOCATOR
Notes:
1.
level-1 indicates a COBOL level between 1 and 47.
2.
level-2 indicates a COBOL level between 2 and 48 where level-2 > level-1.
3.
Graphic host variables, LOB host variables, XML host variables, floating-point host variables, and
COMP-5 host variables are only supported for ILE COBOL.
4.
For details on declaring numeric, character, graphic, binary, LOB, XML, ROWID, and result set locator host variables, see the notes under numeric-host variables, character-host variables, graphic-host variables, binary host variables, LOB host variables, XML host variables, ROWID, and result set locator host variables.
5.
The variable format-options indicates valid datetime options that are supported by the COBOL
| compiler. See the ILE COBOL Language Reference manual for details.
6.
The value for the TIMESTAMP SIZE integer must be 19 to 32.
Host structure indicator array in COBOL applications that use SQL
This figure shows the syntax for valid host structure indicator array declarations.
Host structure indicator array
IS
IS USAGE
►►
level-1
variable-name PICTURE
PIC
picture-string
►
Embedded SQL programming
63
► BINARY
COMPUTATIONAL-4
COMP-4
COMPUTATIONAL-5
COMP-5
OCCURS
dimension
TIMES
VALUE
IS
constant
.
►◄
Notes:
1.
Dimension must be an integer between 1 and 32 767.
2.
level-1 must be an integer between 2 and 48.
3.
BINARY, COMPUTATIONAL-4, COMP-4, COMPUTATIONAL-5, and COMP-5 are equivalent. A portable application should code BINARY because COMPUTATIONAL-4, COMP-4,
COMPUTATIONAL-5, and COMP-5 are IBM extensions that are not supported in ISO/ANSI COBOL.
The picture-string associated with these types must have the form S9(i) (or S9...9, with i instances of 9).
i must be less than or equal to 4.
Using host structure arrays in COBOL applications that use SQL
A host structure array is a named set of host variables that is defined in the program's Data Division and has an OCCURS clause.
Host structure arrays have a maximum of two levels, even though the host structure can occur within a multiple level structure. A varying-length string requires another level, level 49. A host structure array name can be a group name whose subordinate levels name basic data items.
In these examples, the following are true: v
All members in B-ARRAY must be valid.
v B-ARRAY cannot be qualified.
v B-ARRAY can only be used on the blocked form of the FETCH and INSERT statements.
v B-ARRAY is the name of an array of host structures containing items C1-VAR and C2-VAR.
v The SYNCHRONIZED attribute must not be specified.
v C1-VAR and C2-VAR are not valid host variables in any SQL statement. A structure cannot contain an intermediate level structure.
01 A-STRUCT.
02 B-ARRAY OCCURS 10 TIMES.
03 C1-VAR PIC X(20).
03 C2-VAR PIC S9(4).
To retrieve 10 rows from the CORPDATA.DEPARTMENT table, use the following example:
01 TABLE-1.
02 DEPT OCCURS 10 TIMES.
05 DEPTNO PIC X(3).
05 DEPTNAME.
49 DEPTNAME-LEN PIC S9(4) BINARY.
49 DEPTNAME-TEXT PIC X(29).
05 MGRNO PIC X(6).
05 ADMRDEPT PIC X(3).
01 TABLE-2.
02 IND-ARRAY OCCURS 10 TIMES.
05 INDS PIC S9(4) BINARY OCCURS 4 TIMES.
....
EXEC SQL
DECLARE C1 CURSOR FOR
SELECT *
FROM CORPDATA.DEPARTMENT
END-EXEC.
64
IBM i: Embedded SQL programming
....
EXEC SQL
FETCH C1 FOR 10 ROWS INTO :DEPT :IND-ARRAY
END-EXEC.
Host structure array in COBOL applications that use SQL
These figures show the syntax for valid host structure array declarations.
TIMES
►►
level-1 variable-name
OCCURS
dimension
.
► ▼
level-2
var-1
IS
PICTURE
PIC
picture-string-1 floating-point
.
.
varchar-string
.
.
vargraphic-string
.
usage-clause
.
binary
.
lob
.
xml
.
datetime
.
rowid
.
result-set-locator
.
usage-clause:
USAGE
IS
VALUE
IS
constant
display-clause:
DISPLAY
SIGN
IS
LEADING SEPARATE
CHARACTER
floating-point:
BINARY
COMPUTATIONAL-4
COMP-4
COMPUTATIONAL-5
COMP-5
PACKED-DECIMAL
COMPUTATIONAL-3
COMP-3
COMPUTATIONAL
COMP
DISPLAY
display-clause
DISPLAY-1
NATIONAL
Embedded SQL programming
65
►
►◄
USAGE
IS
VALUE
IS
constant
COMPUTATIONAL-1
COMP-1
COMPUTATIONAL-2
COMP-2
varchar-string:
49
var-2
PICTURE
PIC
IS
picture-string-2
USAGE
IS
BINARY
COMPUTATIONAL-4
COMP-4
COMPUTATIONAL-5
COMP-5
►
VALUE
IS
numeric-constant
.
► 49
var-3
PICTURE
PIC
IS
picture-string-3
USAGE
IS
DISPLAY
►
VALUE
IS
constant
vargraphic-string:
49
var-2
PICTURE
PIC
IS
picture-string-2
USAGE
IS
BINARY
COMPUTATIONAL-4
COMP-4
COMPUTATIONAL-5
COMP-5
►
VALUE
IS
numeric-constant
.
►
►
►
►
►
66
IBM i: Embedded SQL programming
► 49
var-3
PICTURE
PIC
►
IS
VALUE
constant
IS
picture-string-3
USAGE
IS
DISPLAY-1
NATIONAL
binary:
USAGE
IS
SQL TYPE IS BINARY
VARBINARY
BINARY VARYING
(
length
)
lob:
USAGE
IS
SQL TYPE IS CLOB
DBCLOB
BLOB
(
lob-length
CLOB-LOCATOR
DBCLOB-LOCATOR
BLOB-LOCATOR
CLOB-FILE
DBCLOB-FILE
BLOB-FILE
K
M
)
xml:
USAGE
IS
SQL TYPE IS XML AS CLOB
DBCLOB
BLOB
XML-LOCATOR
XML AS CLOB-FILE
(
DBCLOB-FILE
BLOB-FILE
lob-length
K
M
)
|||||||||
datetime:
variable-name
FORMAT
OF
DATE
TIME
TIMESTAMP
IS
IS
format-options
IS
SIZE
integer
►
Embedded SQL programming
67
rowid:
SQL TYPE IS ROWID
result set locator:
SQL TYPE IS RESULT_SET_LOCATOR
Notes:
1.
level-1 indicates a COBOL level between 2 and 47.
2.
level-2 indicates a COBOL level between 3 and 48 where level-2 > level-1.
3.
Graphic host variables, LOB host variables, XML host variables, and floating-point host variables are only supported for ILE COBOL.
4.
For details on declaring numeric, character, graphic, binary LOB, XML, ROWID, and result set locator host variables, see the notes under numeric-host variables, character-host variables, graphic-host variables, binary host variables, LOB, XML, ROWID, and result set locator host variables.
5.
Dimension must be an integer constant between 1 and 32 767.
6.
The variable format-options indicates valid datetime options that are supported by the COBOL
| compiler. See the ILE COBOL Language Reference manual for details.
7.
The value for the TIMESTAMP SIZE integer must be 19 to 32.
Host array indicator structure in COBOL applications that use SQL
This figure shows the valid syntax for host structure array indicators.
TIMES
►►
level-1 variable-name
OCCURS
dimension
.
►
►
level-2
var-1 PICTURE
PIC
IS
picture-string
USAGE
IS
BINARY
COMPUTATIONAL-4
COMP-4
COMPUTATIONAL-5
COMP-5
►
►
VALUE
IS
constant
.
►◄
Notes:
1.
level-1 indicates a COBOL level between 2 and 48.
2.
level-2 indicates a COBOL level between 3 and 48 where level-2 > level-1.
3.
Dimension must be an integer constant between 1 and 32 767.
4.
BINARY, COMPUTATIONAL-4, COMP-4, COMPUTATIONAL-5, and COMP-5 are equivalent. A portable application should code BINARY, because COMPUTATIONAL-4, COMP-4,
COMPUTATIONAL-5, and COMP-5 are IBM extensions that are not supported in ISO/ANSI COBOL.
The picture-string associated with these types must have the form S9(i) (or S9...9, with i instances of 9).
i must be less than or equal to 4.
68
IBM i: Embedded SQL programming
Using external file descriptions in COBOL applications that use SQL
SQL uses the COPY DD-format-name, COPY DD-ALL-FORMATS, COPY DDS-format-name, COPY
DDR-format-name, COPY DDR-ALL-FORMATS, COPY DDSR-format-name, COPY DDS-ALL-FORMATS, and COPY DDSR-ALL-FORMATS to retrieve host variables from the file definitions.
If the REPLACING option is specified, only complete name replacing is done. Var-1 is compared against the format name and the field name. If they are equal, var-2 is used as the new name.
Note:
You cannot retrieve host variables from file definitions that have field names which are COBOL reserved words. You must place the COPY DDx-format statement within a COBOL host structure.
To retrieve the definition of the sample table DEPARTMENT described in DB2 for i sample tables in the
SQL programming concepts topic collection, you can code the following:
01 DEPARTMENT-STRUCTURE.
COPY DDS-ALL-FORMATS OF DEPARTMENT.
A host structure named DEPARTMENT-STRUCTURE is defined with an 05 level field named
DEPARTMENT-RECORD that contains four 06 level fields named DEPTNO, DEPTNAME, MGRNO, and
ADMRDEPT. These field names can be used as host variables in SQL statements.
For more information about the COBOL COPY verb, see the ILE COBOL Language Reference and
COBOL/400 User's Guide at IBM Publications Center .
|
|
CLOB, BLOB, and DBCLOB columns in the external file are ignored. No host variable definition will be generated in the host structure for these types.
Using external file descriptions for host structure arrays in COBOL applications that use SQL
Because COBOL creates an extra level when including externally described data, the OCCURS clause must be placed on the preceding 04 level. The structure cannot contain any additional declares at the 05 level.
If the file contains fields that are generated as FILLER, the structure cannot be used as a host structure array.
For device files, if INDARA is not specified and the file contains indicators, the declaration cannot be used as a host structure array. The indicator area is included in the generated structure and causes the storage for records to not be contiguous.
For example, the following shows how to use COPY–DDS to generate a host structure array and fetch 10 rows into the host structure array:
01 DEPT.
04 DEPT-ARRAY OCCURS 10 TIMES.
COPY DDS-ALL-FORMATS OF DEPARTMENT.
...
EXEC SQL DECLARE C1 CURSOR FOR
SELECT * FROM CORPDATA.DEPARTMENT
END EXEC.
EXEC SQL OPEN C1
END-EXEC.
EXEC SQL FETCH C1 FOR 10 ROWS INTO :DEPARTMENT
END-EXEC.
Embedded SQL programming
69
Note:
DATE, TIME, and TIMESTAMP columns will generate character host variable definitions that are treated by SQL with the same comparison and assignment rules as the DATE, TIME, or TIMESTAMP column. For example, a date host variable can only be compared against a DATE column or a string which is a valid representation of a date.
Although GRAPHIC and VARGRAPHIC are mapped to character variables in OPM COBOL, SQL considers these GRAPHIC and VARGRAPHIC variables. If the GRAPHIC or VARGRAPHIC column has a
UCS-2 CCSID, the generated host variable has the UCS-2 CCSID assigned to it. If the GRAPHIC or
VARGRAPHIC column has a UTF-16 CCSID, the generated host variable has the UTF-16 CCSID assigned to it.
Determining equivalent SQL and COBOL data types
The precompiler determines the base SQLTYPE and SQLLEN of host variables based on this table. If a host variable appears with an indicator variable, the SQLTYPE is the base SQLTYPE plus one.
Table 3. COBOL declarations mapped to typical SQL data types
COBOL data type SQLTYPE of host variable
484 S9(i)V9(d) COMP-3 or S9(i)V9(d)
COMP or S9(i)V9(d)
PACKED-DECIMAL
S9(i)V9(d) DISPLAY SIGN LEADING
SEPARATE
504
S9(i)V9(d)DISPLAY 488
500
SQLLEN of host variable
i+d in byte 1, d in byte
2 i+d in byte 1, d in byte
2 i+d in byte 1, d in byte
2
2
SQL data type
DECIMAL(i+d,d)
No exact equivalent use
DECIMAL(i+d,d) or
NUMERIC (i+d,d)
NUMERIC(i+d,d)
SMALLINT S9(i) BINARY or S9(i) COMP-4 or S9(i)
COMP-5 where i is from 1 to 4
S9(i) BINARY or S9(i) COMP-4 or S9(i)
COMP-5 where i is from 5 to 9
S9(i) BINARY or S9(i) COMP-4 or S9(i)
COMP-5 where i is from 10 to 18.
496
492
4
8
INTEGER
BIGINT
Not supported by OPM COBOL.
S9(i)V9(d) BINARY or S9(i)V9(d)
COMP-4 or S9(i)V9(d) COMP-5 where i+d ≤ 4
S9(i)V9(d) BINARY or S9(i)V9(d)
COMP-4 or S9(i)V9(d) COMP-5 where
4 < i+d ≤ 9
COMP-1
Not supported by OPM COBOL.
COMP-2
500
496
480
480 i+d in byte 1, d in byte
2 i+d in byte 1, d in byte
2
4
No exact equivalent use
DECIMAL(i+d,d) or
NUMERIC (i+d,d)
No exact equivalent use
DECIMAL(i+d,d) or
NUMERIC (i+d,d)
FLOAT(single precision)
8 FLOAT(double precision)
Not supported by OPM COBOL.
Fixed-length character data
Varying-length character data
Fixed-length graphic data
452
448
468 m m m
CHAR(m)
VARCHAR(m)
GRAPHIC(m)
Not supported by OPM COBOL.
70
IBM i: Embedded SQL programming
Table 3. COBOL declarations mapped to typical SQL data types (continued)
COBOL data type
Varying-length graphic data
SQLTYPE of host variable
464
SQLLEN of host variable
m
Not supported by OPM COBOL.
DATE 384
Not supported by OPM COBOL.
TIME
|
|
|
|
||| |
Not supported by OPM COBOL.
TIMESTAMP SIZE n
Not supported by OPM COBOL.
388
392 n
SQL data type
VARGRAPHIC(m)
DATE
TIME
TIMESTAMP(0) when n = 19.
TIMESTAMP(n-20) when n > 20
The following table can be used to determine the COBOL data type that is equivalent to a given SQL data type.
Table 4. SQL data types mapped to typical COBOL declarations
SQL data type
SMALLINT
INTEGER
BIGINT
COBOL data type Notes
S9(m) COMP-4 or S9(m) COMP-5
S9(m) COMP-4 or S9(m) COMP-5 m is from 1 to 4 m is from 5 to 9
S9(m) COMP-4 or S9(m) COMP-5 for ILE
COBOL.
m is from 10 to 18
DECIMAL(p,s)
NUMERIC(p,s)
DECFLOAT
FLOAT(single precision)
Not supported by OPM COBOL.
If p<64: S9(p-s)V9(s)
PACKED-DECIMAL or S9(p-s)V9(s)
COMP or S9(p-s)V9(s) COMP-3. If p>63:
Not supported
If p<19: S9(p-s)V9(s) DISPLAY If p>18:
Not supported
p is precision; s is scale. 0<=s<=p<=63.
If s=0, use S9(p) or S9(p)V. If s=p, use
SV9(s).
p is precision; s is scale. 0<=s<=p<=18.
If s=0, use S9(p) or S9(p)V. If s=p, use
SV9(s).
Not supported
COMP-1 for ILE COBOL.
FLOAT(double precision)
CHAR(n)
VARCHAR(n)
CLOB
Not supported by OPM COBOL.
COMP-2 for ILE COBOL.
Not supported by OPM COBOL.
Fixed-length character string
Varying-length character string
None
32766≥n≥1
32740≥n≥1
Use SQL TYPE IS to declare a CLOB for ILE COBOL.
Not supported by OPM COBOL.
Embedded SQL programming
71
| |
| |
| ||
| |
Table 4. SQL data types mapped to typical COBOL declarations (continued)
SQL data type
GRAPHIC(n)
COBOL data type
Fixed-length graphic string for ILE
COBOL.
Notes
16383≥n≥1
VARGRAPHIC(n)
DBCLOB
Not supported by OPM COBOL.
Varying-length graphic string for ILE
COBOL.
Not supported by OPM COBOL.
None
16370≥n≥1
Use SQL TYPE IS to declare a DBCLOB for ILE COBOL.
BINARY
VARBINARY
BLOB
DATE
TIME
TIMESTAMP(n)
XML
DATALINK
ROWID
Result set locator
None
None
None
Not supported by OPM COBOL.
Use SQL TYPE IS to declare a BINARY.
Use SQL TYPE IS to declare a
VARBINARY.
Use SQL TYPE IS to declare a BLOB.
Fixed-length character string or DATE for ILE COBOL.
Not supported by OPM COBOL.
If the format is *USA, *JIS, *EUR, or
*ISO, allow at least 10 characters. If the format is *YMD, *DMY, or *MDY, allow at least 8 characters. If the format is
*JUL, allow at least 6 characters.
Fixed-length character string or TIME for
ILE COBOL.
Allow at least 6 characters; 8 to include seconds.
Fixed-length character string or
TIMESTAMP(19) when n = 0,
TIMESTAMP(20+n) when n > 0 for ILE
COBOL.
None
To include all fractional seconds, n must be 12. If n is less than 12, truncation occurs on the fractional seconds part.
Use SQL TYPE IS to declare an XML.
Not supported by OPM COBOL.
Not supported
None
None
Use SQL TYPE IS to declare a ROWID.
Use SQL TYPE IS to declare a result set locator.
Notes on COBOL variable declaration and usage
Any level 77 data description entry can be followed by one or more REDEFINES entries. However, the names in these entries cannot be used in SQL statements.
Unpredictable results may occur when a structure contains levels defined below a FILLER item.
The COBOL declarations for SMALLINT, INTEGER, and BIGINT data types are expressed as a number of decimal digits. The database manager uses the full size of the integers and can place larger values in the host variable than would be allowed in the specified number of digits in the COBOL declaration.
However, this can cause data truncation or size errors when COBOL statements are being run. Ensure that the size of numbers in your application is within the declared number of digits.
72
IBM i: Embedded SQL programming
Using indicator variables in COBOL applications that use SQL
An indicator variable is a two-byte integer (PIC S9(m) USAGE BINARY, where m is from 1 to 4).
You can also specify an indicator structure (defined as an array of halfword integer variables) to support a host structure.
Indicator variables are declared in the same way as host variables, and the declarations of the two can be mixed in any way that seems appropriate to the programmer.
Example
Given the statement:
EXEC SQL FETCH CLS_CURSOR INTO :CLS-CD,
:NUMDAY :NUMDAY-IND,
:BGN :BGN-IND,
:ENDCLS :ENDCLS-IND
END-EXEC.
The variables can be declared as follows:
EXEC SQL BEGIN DECLARE SECTION END-EXEC.
77 CLS-CD PIC X(7).
77 NUMDAY
77 BGN
PIC S9(4) BINARY.
PIC X(8).
77 ENDCLS PIC X(8).
77 NUMDAY-IND PIC S9(4) BINARY.
77 BGN-IND PIC S9(4) BINARY.
77 ENDCLS-IND PIC S9(4) BINARY.
EXEC SQL END DECLARE SECTION END-EXEC.
Related reference
:
References to variables
“Indicator variables in applications that use SQL” on page 4
An indicator variable is a halfword integer variable used to communicate additional information about its associated host variable.
Coding SQL statements in PL/I applications
There are some unique application and coding requirements for embedding SQL statements in a PL/I program. In this topic, requirements for host structures and host variables are defined.
Note:
Related concepts
:
“Writing applications that use SQL” on page 2
You can create database applications in host languages that use DB2 for i SQL statements and functions.
Related reference
:
“Example programs: Using DB2 for i statements” on page 149
Here is a sample application that shows how to code SQL statements in each of the languages that DB2 for i supports.
“Example: SQL statements in PL/I programs” on page 166
This example program is written in the PL/I programming language.
Embedded SQL programming
73
Defining the SQL communication area in PL/I applications that use
SQL
A PL/I program that contains SQL statements must include one or both of these fields.
v An SQLCODE variable declared as FIXED BINARY(31) v An SQLSTATE variable declared as CHAR(5)
Or, v An SQLCA (which contains an SQLCODE and SQLSTATE variable).
The SQLCODE and SQLSTATE values are set by the database manager after each SQL statement is run.
An application can check the SQLCODE or SQLSTATE value to determine whether the last SQL statement was successful.
The SQLCA can be coded in a PL/I program either directly or by using the SQL INCLUDE statement.
Using the SQL INCLUDE statement requests the inclusion of a standard SQLCA declaration:
EXEC SQL INCLUDE SQLCA ;
The scope of the SQLCODE, SQLSTATE, and SQLCA variables must include the scope of all SQL statements in the program.
The included PL/I source statements for the SQLCA are:
DCL 1 SQLCA,
2 SQLCAID
2 SQLCABC
2 SQLCODE
2 SQLERRM
2 SQLERRP
2 SQLERRD(6)
2 SQLWARN,
3 SQLWARN0
3 SQLWARN1
3 SQLWARN2
3 SQLWARN3
3 SQLWARN4
3 SQLWARN5
3 SQLWARN6
3 SQLWARN7
3 SQLWARN8
3 SQLWARN9
3 SQLWARNA
2 SQLSTATE
CHAR(8),
FIXED(31) BINARY,
FIXED(31) BINARY,
CHAR(70) VAR,
CHAR(8),
FIXED(31) BINARY,
CHAR(1),
CHAR(1),
CHAR(1),
CHAR(1),
CHAR(1),
CHAR(1),
CHAR(1),
CHAR(1),
CHAR(1),
CHAR(1),
CHAR(1),
CHAR(5);
SQLCODE is replaced with SQLCADE when a declare for SQLCODE is found in the program and the
SQLCA is provided by the precompiler. SQLSTATE is replaced with SQLSTOTE when a declare for
SQLSTATE is found in the program and the SQLCA is provided by the precompiler.
Related reference
:
SQL communication area
Defining SQL descriptor areas in PL/I applications that use SQL
There are two types of SQL descriptor areas. One is defined with the ALLOCATE DESCRIPTOR statement. The other is defined using the SQLDA structure. In this topic, only the SQLDA form is discussed.
The following statements can use an SQLDA: v EXECUTE...USING DESCRIPTOR descriptor-name v FETCH...USING DESCRIPTOR descriptor-name
74
IBM i: Embedded SQL programming
v OPEN...USING DESCRIPTOR descriptor-name v
CALL...USING DESCRIPTOR descriptor-name v DESCRIBE statement-name INTO descriptor-name v DESCRIBE CURSOR cursor-name INTO descriptor-name v DESCRIBE INPUT statement-name INTO descriptor-name v DESCRIBE PROCEDURE procedure-name INTO descriptor-name v DESCRIBE TABLE host-variable INTO descriptor-name v PREPARE statement-name INTO descriptor-name
Unlike the SQLCA, there can be more than one SQLDA in a program, and an SQLDA can have any valid name. An SQLDA can be coded in a PL/I program either program directly or by using the SQL
INCLUDE statement. Using the SQL INCLUDE statement requests the inclusion of a standard SQLDA declaration:
EXEC SQL INCLUDE SQLDA ;
The included PL/I source statements for the SQLDA are:
DCL 1 SQLDA BASED(SQLDAPTR),
2 SQLDAID CHAR(8),
2 SQLDABC
2 SQLN
2 SQLD
FIXED(31) BINARY,
FIXED(15) BINARY,
FIXED(15) BINARY,
2 SQLVAR(99),
3 SQLTYPE
3 SQLLEN
3 SQLRES
3 SQLDATA
3 SQLIND
3 SQLNAME
DCL SQLDAPTR PTR;
FIXED(15) BINARY,
FIXED(15) BINARY,
CHAR(12),
PTR,
PTR,
CHAR(30) VAR;
Dynamic SQL is an advanced programming technique. With dynamic SQL, your program can develop and then run SQL statements while the program is running. A SELECT statement with a variable SELECT list (that is, a list of the data to be returned as part of the query) that runs dynamically requires an SQL descriptor area (SQLDA). This is because you cannot know in advance how many or what type of variables to allocate in order to receive the results of the SELECT.
Related concepts
:
Dynamic SQL applications
Related reference
:
SQL descriptor area
Embedding SQL statements in PL/I applications that use SQL
The first statement of the PL/I program must be a PROCEDURE statement. SQL statements can be coded in a PL/I program wherever executable statements can appear.
Each SQL statement in a PL/I program must begin with EXEC SQL and end with a semicolon (;). The key words EXEC SQL must appear all on one line, but the remainder of the statement can appear on the next and subsequent lines.
Example: Embedding SQL statements in PL/I applications that use SQL
You can code an UPDATE statement in a PL/I program as in this example.
EXEC SQL UPDATE DEPARTMENT
SET MGRNO = :MGR_NUM
WHERE DEPTNO = :INT_DEPT ;
Embedded SQL programming
75
Comments in PL/I applications that use SQL
In addition to SQL comments (--), you can include PL/I comments (/*...*/) in embedded SQL statements wherever a blank is allowed, except between the keywords EXEC and SQL.
Continuation for SQL statements in PL/I applications that use SQL
The line continuation rules for SQL statements are the same as those for other PL/I statements, except that EXEC SQL must be specified within one line.
Constants containing DBCS data can be continued across multiple lines by placing the shift-in and shift-out characters outside of the margins. This example assumes margins of 2 and 72. This SQL statement has a valid graphic constant of G'<AABBCCDDEEFFGGHHIIJJKK>'.
*(..+....1....+....2....+....3....+....4....+....5....+....6....+....7.)..
EXEC SQL SELECT * FROM GRAPHTAB WHERE GRAPHCOL = G’<AABBCCDD>
<EEFFGGHHIIJJKK>’;
Including code in PL/I applications that use SQL
SQL statements or PL/I host variable declaration statements can be included by placing the following
SQL statement at the point in the source code where the statements are to be embedded.
EXEC SQL INCLUDE member-name ;
No PL/I preprocessor directives are permitted within SQL statements. PL/I %INCLUDE statements cannot be used to include SQL statements or declarations of PL/I host variables that are referenced in
SQL statements.
Margins in PL/I applications that use SQL
You must code SQL statements within the margins specified by the MARGINS parameter on the
CRTSQLPLI command. If EXEC SQL does not start within the specified margins, the SQL precompiler will not recognize the SQL statement.
Related concepts
:
“CL command descriptions for host language precompilers” on page 188
The IBM DB2 Query Manager and SQL Development Kit for i licensed program provides commands for precompiling programs coded in these programming languages.
Names in PL/I applications that use SQL
Any valid PL/I variable name can be used for a host variable and is subject to these restrictions.
Do not use host variable names or external entry names that begin with 'SQL', 'RDI', or 'DSN'. These names are reserved for the database manager.
Statement labels in PL/I applications that use SQL
All executable SQL statements, like PL/I statements, can have a label prefix.
WHENEVER statement in PL/I applications that use SQL
The target for the GOTO clause in an SQL WHENEVER statement must be a label in the PL/I source code and must be within the scope of any SQL statements affected by the WHENEVER statement.
Using host variables in PL/I applications that use SQL
All host variables used in SQL statements must be explicitly declared.
The PL/I statements that are used to define the host variables should be preceded by a BEGIN
DECLARE SECTION statement and followed by an END DECLARE SECTION statement. If a BEGIN
DECLARE SECTION and END DECLARE SECTION are specified, all host variable declarations used in
SQL statements must be between the BEGIN DECLARE SECTION and the END DECLARE SECTION statements.
76
IBM i: Embedded SQL programming
All host variables within an SQL statement must be preceded by a colon (:).
The names of host variables must be unique within the program, even if the host variables are in different blocks or procedures.
An SQL statement that uses a host variable must be within the scope of the statement in which the variable was declared.
Host variables must be scalar variables. They cannot be elements of an array.
Declaring host variables in PL/I applications that use SQL
The PL/I precompiler only recognizes a subset of valid PL/I declarations as valid host variable declarations.
Only the names and data attributes of the variables are used by the precompilers; the alignment, scope, and storage attributes are ignored. Even though alignment, scope, and storage are ignored, there are some restrictions on their use that, if ignored, may result in problems when compiling PL/I source code that is created by the precompiler. These restrictions are: v A declaration with the EXTERNAL scope attribute and the STATIC storage attribute must also have the
INITIAL storage attribute.
v If the BASED storage attribute is coded, it must be followed by a PL/I element-locator-expression.
Numeric-host variables in PL/I applications that use SQL:
This figure shows the syntax for valid scalar numeric-host variable declarations.
Numeric
►► DECLARE
DCL
variable-name
,
(
▼
variable-name
)
► BINARY
BIN
FIXED
(
precision
)
FLOAT
(
precision
)
DECIMAL
DEC
FIXED
(
precision
FLOAT
PICTURE
picture-string
(
precision
)
,scale
► ;
Alignment and/or Scope and/or Storage
)
►
►
►◄
Notes:
1.
(BINARY, BIN, DECIMAL, or DEC) and (FIXED or FLOAT) and (precision, scale) can be specified in any order.
2.
A picture-string in the form '9...9V9...R' indicates a numeric host variable. The R is required. The optional V indicates the implied decimal point.
3.
A picture-string in the form 'S9...9V9...9' indicates a sign leading separate host variable. The S is required. The optional V indicates the implied decimal point.
Embedded SQL programming
77
Character-host variables in PL/I applications that use SQL:
This figure shows the syntax for valid scalar character-host variables.
Character
►► DECLARE
DCL
variable-name
,
(
▼
variable-name
)
CHARACTER
CHAR (
length
)
► ;
Alignment and/or Scope and/or Storage
VARYING
VAR
►
►◄
Notes:
1.
The variable length must be an integer constant not greater than 32766 if VARYING or VAR is not specified.
2.
If VARYING or VAR is specified, length must be a constant no greater than 32740.
Binary host variables in PL/I applications that use SQL:
PL/I does not have variables that correspond to the SQL binary data types. To create host variables that can be used with these data types, use the SQL TYPE IS clause. The SQL precompiler replaces this declaration with a PL/I language structure in the output source member.
BINARY and VARBINARY
►► DECLARE
DCL
variable-name
,
▼
(
variable-name
)
SQL TYPE IS BINARY
VARBINARY
BINARY VARYING
(
length
) ; ►◄
Notes:
1.
For BINARY host variables, the length must be in the range 1 to 32766.
2.
For VARBINARY and BINARY VARYING host variables, the length must be in the range 1 to 32740.
3.
SQL TYPE IS, BINARY, VARBINARY, BINARY VARYING can be in mixed case.
BINARY example
The following declaration:
DCL MY_BINARY SQL TYPE IS BINARY(100);
Results in the generation of the following code:
DCL MY_BINARY CHARACTER(100);
VARBINARY example
The following declaration:
DCL MY_VARBINARY SQL TYPE IS VARBINARY(250);
Results in the generation of the following code:
DCL MY_VARBINARY CHARACTER(250) VARYING;
78
IBM i: Embedded SQL programming
LOB host variables in PL/I applications that use SQL:
PL/I does not have variables that correspond to the SQL data types for LOBs (large objects). To create host variables that can be used with these data types, use the SQL TYPE IS clause. The SQL precompiler replaces this declaration with a PL/I language structure in the output source member.
The following figure shows the syntax for valid LOB host variables.
LOB
►► DECLARE
DCL
variable-name
,
(
▼
variable-name
)
SQL TYPE IS CLOB
BLOB
(
lob-length
K
) ; ►◄
Notes:
1.
For BLOB and CLOB, 1 ≤ lob-length ≤ 32,766
2.
SQL TYPE IS, BLOB, CLOB can be in mixed case.
CLOB example
The following declaration:
DCL MY_CLOB SQL TYPE IS CLOB(16384);
Results in the generation of the following structure:
DCL 1 MY_CLOB,
3 MY_CLOB_LENGTH BINARY FIXED (31) UNALIGNED,
3 MY_CLOB_DATA CHARACTER (16384);
BLOB example
The following declaration:
DCL MY_BLOB SQL TYPE IS BLOB(16384);
Results in the generation of the following structure:
DCL 1 MY_BLOB,
3 MY_BLOB_LENGTH BINARY FIXED (31) UNALIGNED,
3 MY_BLOB_DATA CHARACTER (16384);
The following figure shows the syntax for valid LOB locators.
LOB locator
►► DECLARE
DCL
variable-name
,
(
▼
variable-name
)
SQL TYPE IS CLOB_LOCATOR
DBCLOB_LOCATOR
BLOB_LOCATOR
; ►◄
Note:
SQL TYPE IS, BLOB_LOCATOR, CLOB_LOCATOR, DBCLOB_LOCATOR can be in mixed case.
CLOB locator example
The following declaration:
DCL MY_LOCATOR SQL TYPE IS CLOB_LOCATOR;
Embedded SQL programming
79
Results in the following generation:
DCL MY_LOCATOR BINARY FIXED(31) UNALIGNED;
BLOB and DBCLOB locators have similar syntax.
The following figure shows the syntax for valid LOB file reference variables.
LOB file reference variable
►► DECLARE
DCL
variable-name
,
(
▼
variable-name
)
SQL TYPE IS CLOB_FILE
DBCLOB_FILE
BLOB_FILE
; ►◄
Note:
SQL TYPE IS, BLOB_FILE, CLOB_FILE, and DBCLOB_FILE can be in mixed case.
CLOB file reference example
The following declaration:
DCL MY_FILE SQL TYPE IS CLOB_FILE;
Results in the generation of the following structure:
DCL 1 MY_FILE,
3 MY_FILE_NAME_LENGTH BINARY FIXED(31) UNALIGNED,
3 MY_FILE_DATA_LENGTH BINARY FIXED(31) UNALIGNED,
3 MY_FILE_FILE_OPTIONS BINARY FIXED(31) UNALIGNED,
3 MY_FILE_NAME CHAR(255);
BLOB and DBCLOB file reference variables have similar syntax.
The pre-compiler will generate declarations for the following file option constants: v SQL_FILE_READ (2) v SQL_FILE_CREATE (8) v SQL_FILE_OVERWRITE (16) v SQL_FILE_APPEND (32)
Related reference
:
LOB file reference variables
ROWID host variables in PL/I applications that use SQL:
PL/I does not have a variable that corresponds to the SQL data type ROWID. To create host variables that can be used with this data type, use the SQL TYPE IS clause. The SQL precompiler replaces this declaration with a PL/I language structure in the output source member.
ROWID
►► DECLARE
DCL
variable-name
,
(
▼
variable-name
)
SQL TYPE IS ROWID ►◄
Note:
SQL TYPE IS ROWID can be in mixed case.
80
IBM i: Embedded SQL programming
ROWID example
The following declaration:
DCL MY_ROWID SQL TYPE IS ROWID;
Results in the following generation:
DCL MY_ROWID CHARACTER(40) VARYING;
Using host structures in PL/I applications that use SQL
In PL/I programs, you can define a host structure, which is a named set of elementary PL/I variables. A host structure name can be a group name whose subordinate levels name elementary PL/I variables.
For example:
DCL 1 A,
2 B,
3 C1 CHAR(...),
3 C2 CHAR(...);
In this example, B is the name of a host structure consisting of the elementary items C1 and C2.
You can use the structure name as shorthand notation for a list of scalars. You can qualify a host variable with a structure name (for example, STRUCTURE.FIELD). Host structures are limited to two levels. (For example, in the above host structure example, the A cannot be referred to in SQL.) A structure cannot contain an intermediate level structure. In the previous example, A could not be used as a host variable or referred to in an SQL statement. However, B is the first level structure. B can be referred to in an SQL statement. A host structure for SQL data is two levels deep and can be thought of as a named set of host variables. After the host structure is defined, you can refer to it in an SQL statement instead of listing the several host variables (that is, the names of the host variables that make up the host structure).
For example, you can retrieve all column values from selected rows of the table CORPDATA.EMPLOYEE
with:
DCL 1 PEMPL,
5 EMPNO CHAR(6),
5 FIRSTNME CHAR(12) VAR,
5 MIDINIT CHAR(1),
5 LASTNAME CHAR(15) VAR,
5 WORKDEPT CHAR(3);
...
EMPID = ’000220’;
...
EXEC SQL
SELECT *
INTO :PEMPL
FROM CORPDATA.EMPLOYEE
WHERE EMPNO = :EMPID;
Host structures in PL/I applications that use SQL
This figure shows the syntax for valid host structure declarations.
Host structures
►► DECLARE
DCL
1
variable-name level-1 variable-name
,
Scope and/or storage
, ►
Embedded SQL programming
81
,
► ▼
level-2 var-1
,
(
▼
var-2
)
data-types
;
data-types:
BINARY
BIN
DECIMAL
DEC
FIXED
FLOAT
FIXED
(
precision
(
precision
) UNALIGNED
)
,
scale
FLOAT
(
precision
)
PICTURE
picture-string
CHARACTER
CHAR (
length
) VARYING
VAR
SQL TYPE IS CLOB
BLOB
(
lob-length
CLOB_LOCATOR
DBCLOB_LOCATOR
K
UNALIGNED
)
ALIGNED
BLOB_LOCATOR
CLOB_FILE
DBCLOB_FILE
BLOB_FILE
SQL TYPE IS ROWID
SQL TYPE IS BINARY
VARBINARY
BINARY VARYING
(
length
)
►◄
Notes:
1.
level-1 indicates that there is an intermediate level structure.
2.
level-1 must be an integer constant between 1 and 254.
3.
level-2 must be an integer constant between 2 and 255.
4.
For details on declaring numeric, character, LOB, ROWID, and binary host variables, see the notes under numeric-host variables, character-host variables, LOB host variables, ROWID host variables, and binary host variables.
Host structure indicator arrays in PL/I applications that use SQL
This figure shows the syntax for valid host structure indicator array declarations.
Host structure indicator array
►► DECLARE
DCL
variable-name
(
dimension
)
,
(
▼
variable-name
(
dimension
) )
BINARY
BIN
FIXED
► ;
►
►◄
(
precision
)
Alignment and/or scope and/or storage
Note:
Dimension must be an integer constant between 1 and 32766.
82
IBM i: Embedded SQL programming
Using host structure arrays in PL/I applications that use SQL
In PL/I programs, you can define a host structure array.
In these examples, the following are true: v B_ARRAY is the name of a host structure array that contains the items C1_VAR and C2_VAR.
v B_ARRAY cannot be qualified.
v B_ARRAY can only be used with the blocked forms of the FETCH and INSERT statements.
v All items in B_ARRAY must be valid host variables.
v C1_VAR and C2_VAR are not valid host variables in any SQL statement. A structure cannot contain an intermediate level structure. A_STRUCT cannot contain the dimension attribute.
DCL 1 A_STRUCT,
2 B_ARRAY(10),
3 C1_VAR CHAR(20),
3 C2_FIXED BIN(15) UNALIGNED;
To retrieve 10 rows from the CORPDATA.DEPARTMENT table, do the following:
DCL 1 DEPT(10),
5 DEPTPNO CHAR(3),
5 DEPTNAME CHAR(29) VAR,
5 MGRNO CHAR(6),
5 ADMRDEPT CHAR (3);
DCL 1 IND_ARRAY(10),
5 INDS(4) FIXED BIN(15);
EXEC SQL
DECLARE C1 CURSOR FOR
SELECT *
FROM CORPDATA.DEPARTMENT;
EXEC SQL
FETCH C1 FOR 10 ROWS INTO :DEPT :IND_ARRAY;
Host structure array in PL/I applications that use SQL
This syntax diagram shows the syntax for valid host structure array declarations.
Host structure array
►► DECLARE
DCL
1
variable-name level-1 variable-name
,
(
dimension
)
Scope and/or storage
, ►
,
► ▼
level-2 var-1
,
(
▼
var-2
)
data-types
;
data-types:
►◄
Embedded SQL programming
83
BINARY
BIN
DECIMAL
DEC
FIXED
FLOAT
FIXED
(
precision
)
UNALIGNED
FLOAT
(
precision
,
scale
UNALIGNED
)
(
precision
)
PICTURE
picture-string
CHARACTER
CHAR (
length
)
SQL TYPE IS CLOB
BLOB
VARYING
VAR
(
lob-length
K
)
CLOB_LOCATOR
DBCLOB_LOCATOR
BLOB_LOCATOR
CLOB_FILE
DBCLOB_FILE
SQL TYPE IS ROWID
BLOB_FILE
SQL TYPE IS BINARY
VARBINARY
BINARY VARYING
(
length
)
Notes:
1.
level-1 indicates that there is an intermediate level structure.
2.
level-1 must be an integer constant between 1 and 254.
3.
level-2 must be an integer constant between 2 and 255.
4.
For details on declaring numeric, character, LOB, ROWID, and binary host variables, see the notes under numeric-host variables, character-host variables, LOB host variables, ROWID, and binary host variables.
5.
Dimension must be an integer constant between 1 and 32 767.
Host structure array indicator in PL/I applications that use SQL:
This figure shows the syntax diagram for the declaration of a valid host structure array indicator.
►► DECLARE
DCL
1
variable-name level-1 variable-name
,
(
dimension
)
► level-2
identifier
(
dimension-2
) BINARY
BIN
Scope and/or storage
FIXED
(
precision
)
,
;
►
►◄
Notes:
1.
level-1 indicates that there is an intermediate level structure.
2.
level-1 must be an integer constant between 1 and 254.
3.
level-2 must be an integer constant between 2 and 255.
4.
Dimension-1 and dimension-2 must be integer constants between 1 and 32 767.
Using external file descriptions in PL/I applications that use SQL
You can use the PL/I %INCLUDE directive to include the definitions of externally described files in a source program.
84
IBM i: Embedded SQL programming
When used with SQL, only a particular format of the %INCLUDE directive is recognized by the SQL precompiler. That directive format must have the following three elements or parameter values, otherwise the precompiler ignores the directive. The required elements are file name, format name, and element type.
There are two optional elements supported by the SQL precompiler: prefix name and COMMA.
The structure is ended normally by the last data element of the record or key structure. However, if in the %INCLUDE directive the COMMA element is specified, then the structure is not ended.
To include the definition of the sample table DEPARTMENT described in DB2 for i sample tables in the
SQL programming topic collection, you can code:
DCL 1 TDEPT_STRUCTURE,
%INCLUDE DEPARTMENT(DEPARTMENT,RECORD);
In the above example, a host structure named TDEPT_STRUCTURE would be defined having four fields.
The fields would be DEPTNO, DEPTNAME, MGRNO, and ADMRDEPT.
For device files, if INDARA is not specified and the file contains indicators, the declaration cannot be used as a host structure array. The indicator area is included in the generated structure and causes the storage to not be contiguous.
DCL 1 DEPT_REC(10),
%INCLUDE DEPARTMENT(DEPARTMENT,RECORD);
EXEC SQL DECLARE C1 CURSOR FOR
SELECT * FROM CORPDATA.DEPARTMENT;
EXEC SQL OPEN C1;
EXEC SQL FETCH C1 FOR 10 ROWS INTO :DEPT_REC;
Note:
DATE, TIME, and TIMESTAMP columns will generate host variable definitions that are treated by
SQL with the same comparison and assignment rules as a DATE, TIME, and TIMESTAMP column. For example, a date host variable can only be compared with a DATE column or a character string that is a valid representation of a date.
Although decimal and zoned fields with precision greater than 15 and binary with nonzero scale fields are mapped to character field variables in PL/I, SQL considers these fields to be numeric.
Although GRAPHIC and VARGRAPHIC are mapped to character variables in PL/I, SQL considers these to be GRAPHIC and VARGRAPHIC host variables. If the GRAPHIC or VARGRAPHIC column has a
UCS-2 CCSID, the generated host variable will have the UCS-2 CCSID assigned to it. If the GRAPHIC or
VARGRAPHIC column has a UTF-16 CCSID, the generated host variable will have the UTF-16 CCSID assigned to it.
|
| CLOB, BLOB, and DBCLOB columns in the external file are ignored. No host variable definition will be generated in the host structure for these types.
Determining equivalent SQL and PL/I data types
The precompiler determines the base SQLTYPE and SQLLEN of host variables based on this table.
If a host variable appears with an indicator variable, the SQLTYPE is the base SQLTYPE plus one.
Embedded SQL programming
85
Table 5. PL/I declarations mapped to typical SQL data types
PL/I data type SQLTYPE of host variable
BIN FIXED(p) where p is in the range 1 to 15 500
BIN FIXED(p) where p is in the range 16 to
31
496
DEC FIXED(p,s)
BIN FLOAT(p) p is in the range 1 to 24
484
480
BIN FLOAT(p) p is in the range 25 to 53
DEC FLOAT(m) m is in the range 1 to 7
DEC FLOAT(m) m is in the range 8 to 16
PICTURE picture string (numeric)
PICTURE picture string (sign leading separate)
CHAR(n)
CHAR(n) VARYING
480
480
480
488
504
452
448
2
4
SQLLEN of host variable
SQL data type
SMALLINT
INTEGER p in byte 1, s in byte 2 DECIMAL(p,s)
4 FLOAT (single precision)
8
4
FLOAT (double precision)
FLOAT (single precision)
8 n n
FLOAT (double precision) p in byte 1, s in byte 2 NUMERIC (p,s) p in byte 1, s in byte 2 No exact equivalent, use NUMERIC(p,s).
CHAR(n)
VARCHAR(n)
The following table can be used to determine the PL/I data type that is equivalent to a given SQL data type.
Table 6. SQL data types mapped to typical PL/I declarations
SQL data type
SMALLINT
INTEGER
BIGINT
DECIMAL(p,s) or NUMERIC(p,s)
PL/I equivalent
BIN FIXED(p)
BIN FIXED(p)
No exact equivalent
DEC FIXED(p) or DEC FIXED(p,s) or
PICTURE picture-string
DECFLOAT
FLOAT (single precision)
Not supported
BIN FLOAT(p) or DEC FLOAT(m)
Notes
p is a positive integer from 1 to 15.
p is a positive integer from 16 to 31.
Use DEC FIXED(18).
s (the scale factor) and p (the precision) are positive integers. p is a positive integer from 1 to 31. s is a positive integer from 0 to p.
Not supported.
p is a positive integer from 1 to 24.
FLOAT (double precision)
CHAR(n)
VARCHAR(n)
CLOB
GRAPHIC(n)
VARGRAPHIC(n)
DBCLOB
BINARY
BIN FLOAT(p) or DEC FLOAT(m)
CHAR(n)
CHAR(n) VARYING
None
Not supported
Not supported
Not supported
None
m is a positive integer from 1 to 7.
p is a positive integer from 25 to 53.
m is a positive integer from 8 to 16.
n is a positive integer from 1 to 32766.
n is a positive integer from 1 to 32740.
Use SQL TYPE IS to declare a CLOB.
Not supported.
Not supported.
Not supported.
Use SQL TYPE IS to declare a
BINARY.
86
IBM i: Embedded SQL programming
Table 6. SQL data types mapped to typical PL/I declarations (continued)
SQL data type
VARBINARY
PL/I equivalent
None
BLOB
DATE
None
CHAR(n)
TIME
TIMESTAMP
XML
DATALINK
ROWID
Result set locator
CHAR(n)
CHAR(n)
Not supported
Not supported
None
Not supported
Notes
Use SQL TYPE IS to declare a
VARBINARY.
Use SQL TYPE IS to declare a BLOB.
If the format is *USA, *JIS, *EUR, or
*ISO, n must be at least 10 characters.
If the format is *YMD, *DMY, or
*MDY, n must be at least 8 characters.
If the format is *JUL, n must be at least 6 characters.
n must be at least 6; to include seconds, n must be at least 8.
n must be at least 19. To include microseconds at full precision, n must be 26; if n is less than 26, truncation occurs on the microseconds part.
Not supported.
Not supported.
Use SQL TYPE IS to declare a
ROWID.
Not supported.
Using indicator variables in PL/I applications that use SQL
An indicator variable is a two-byte integer (BIN FIXED(p), where p is 1 to 15).
You can also specify an indicator structure (defined as an array of halfword integer variables) to support a host structure.
Indicator variables are declared in the same way as host variables and the declarations of the two can be mixed in any way that seems appropriate to the programmer.
Example
Given the statement:
EXEC SQL FETCH CLS_CURSOR INTO :CLS_CD,
:DAY :DAY_IND,
:BGN :BGN_IND,
:END :END_IND;
Variables can be declared as follows:
EXEC SQL BEGIN DECLARE SECTION;
DCL CLS_CD CHAR(7);
DCL DAY
DCL BGN
BIN FIXED(15);
CHAR(8);
DCL END CHAR(8);
DCL (DAY_IND, BGN_IND, END_IND) BIN FIXED(15);
EXEC SQL END DECLARE SECTION;
Related reference
:
References to variables
“Indicator variables in applications that use SQL” on page 4
An indicator variable is a halfword integer variable used to communicate additional information about its
Embedded SQL programming
87
associated host variable.
Differences in PL/I because of structure parameter passing techniques
The PL/I precompiler attempts to use the structure parameter passing technique, if possible. This structure parameter passing technique provides better performance for most PL/I programs using SQL.
The precompiler generates code where each host variable is a separate parameter when the following conditions are true: v A PL/I %INCLUDE compiler directive is found that copies external text into the source program.
v The data length of the host variables referred to in the statement is greater than 32 703. Because SQL uses 64 bytes of the structure, 32703 + 64 = 32767, the maximum length of a data structure.
v The PL/I precompiler estimates that it could possibly exceed the PL/I limit for user-defined names.
v
A sign leading separate host variable is found in the host variable list for the SQL statement.
Related concepts
:
Application design tips for database performance
Coding SQL statements in RPG/400 applications
The RPG/400 licensed program supports both RPG II and RPG III programs.
SQL statements can only be used in RPG III programs. RPG II and AutoReport are NOT supported. All referrals to RPG in this guide apply to RPG III or ILE RPG only.
This topic describes the unique application and coding requirements for embedding SQL statements in a
RPG/400 program. Requirements for host variables are defined.
Note:
For more information about programming using RPG, see the manuals RPG/400 User's Guide and
RPG/400 Reference at IBM Publications Center
Related concepts
:
.
“Writing applications that use SQL” on page 2
You can create database applications in host languages that use DB2 for i SQL statements and functions.
Related reference
:
“Example programs: Using DB2 for i statements” on page 149
Here is a sample application that shows how to code SQL statements in each of the languages that DB2 for i supports.
“Example: SQL statements in RPG/400 programs” on page 171
This example program is written in the RPG programming language.
Defining the SQL communication area in RPG/400 applications that use SQL
The SQL precompiler automatically places the SQLCA in the input specifications of the RPG/400 program prior to the first calculation specification.
INCLUDE SQLCA should not be coded in the source program. If the source program specifies INCLUDE
SQLCA, the statement will be accepted, but it is redundant. The SQLCA, as defined for RPG/400:
ISQLCA
I*
I I
I
DS
SQL COMMUNICATION AREA
X’0000000000000000’ 1 8 SQLAID
B 9 120SQLABC
SQL
SQL
SQL
SQL
88
IBM i: Embedded SQL programming
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I* END OF SQLCA
B 13 160SQLCOD
B 17 180SQLERL
19 88 SQLERM
89 96 SQLERP
97 120 SQLERR
B 97 1000SQLER1
B 101 1040SQLER2
B 105 1080SQLER3
B 109 1120SQLER4
B 113 1160SQLER5
B 117 1200SQLER6
121 131 SQLWRN
121 121 SQLWN0
122 122 SQLWN1
123 123 SQLWN2
124 124 SQLWN3
125 125 SQLWN4
126 126 SQLWN5
127 127 SQLWN6
128 128 SQLWN7
129 129 SQLWN8
130 130 SQLWN9
131 131 SQLWNA
132 136 SQLSTT
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
Note:
Variable names in RPG/400 are limited to 6 characters. The standard SQLCA names have been changed to a length of 6. RPG/400 does not have a way of defining arrays in a data structure without also defining them in the extension specification. SQLERR is defined as character with SQLER1 through 6 used as the names of the elements.
Related reference
:
SQL communication area
Defining SQL descriptor areas in RPG/400 applications that use SQL
There are two types of SQL descriptor areas. One is defined with the ALLOCATE DESCRIPTOR statement. The other is defined using the SQLDA structure. In this topic, only the SQLDA form is discussed.
The following statements can use an SQLDA: v EXECUTE...USING DESCRIPTOR descriptor-name v FETCH...USING DESCRIPTOR descriptor-name v
OPEN...USING DESCRIPTOR descriptor-name v CALL...USING DESCRIPTOR descriptor-name v DESCRIBE statement-name INTO descriptor-name v DESCRIBE CURSOR cursor-name INTO descriptor-name v DESCRIBE INPUT statement-name INTO descriptor-name v DESCRIBE PROCEDURE procedure-name INTO descriptor-name v DESCRIBE TABLE host-variable INTO descriptor-name v PREPARE statement-name INTO descriptor-name
Unlike the SQLCA, there can be more than one SQLDA in a program and an SQLDA can have any valid name.
Dynamic SQL is an advanced programming technique. With dynamic SQL, your program can develop and then run SQL statements while the program is running. A SELECT statement with a variable SELECT list (that is, a list of the data to be returned as part of the query) that runs dynamically requires an SQL
Embedded SQL programming
89
descriptor area (SQLDA). This is because you cannot know in advance how many or what type of variables to allocate in order to receive the results of the SELECT.
Because the SQLDA uses pointer variables that are not supported by RPG/400, an INCLUDE SQLDA statement cannot be specified in an RPG/400 program. An SQLDA must be set up by a C, C++, COBOL,
PL/I, or ILE RPG program and passed to the RPG program in order to use it.
Related concepts
:
Dynamic SQL applications
Related reference
:
SQL descriptor area
Embedding SQL statements in RPG/400 applications that use SQL
SQL statements coded in an RPG/400 program must be placed in the calculation section. This requires that a C be placed in position 6.
SQL statements can be placed in detail calculations, in total calculations, or in an RPG/400 subroutine.
The SQL statements are run based on the logic of the RPG/400 statements.
The keywords EXEC SQL indicate the beginning of an SQL statement. EXEC SQL must occupy positions
8 through 16 of the source statement, preceded by a / in position 7. The SQL statement may start in position 17 and continue through position 74.
The keyword END-EXEC ends the SQL statement. END-EXEC must occupy positions 8 through 16 of the source statement, preceded by a slash (/) in position 7. Positions 17 through 74 must be blank.
Both uppercase and lowercase letters are acceptable in SQL statements.
Example: Embedding SQL statements in RPG/400 applications that use SQL
An UPDATE statement coded in an RPG/400 program might be coded as this example shows.
*...1....+....2....+....3....+....4....+....5....+....6....+....7...*
C/EXEC SQL UPDATE DEPARTMENT
C+
C+
C/END-EXEC
SET MANAGER = :MGRNUM
WHERE DEPTNO = :INTDEP
Comments in RPG/400 applications that use SQL
In addition to SQL comments (--), RPG/400 comments can be included within SQL statements wherever a blank is allowed, except between the keywords EXEC and SQL.
To embed an RPG/400 comment within the SQL statement, place an asterisk (*) in position 7.
Continuation for SQL statements in RPG/400 applications that use SQL
When additional records are needed to contain the SQL statement, positions 9 through 74 can be used.
Position 7 must be a + (plus sign), and position 8 must be blank.
Constants containing DBCS data can be continued across multiple lines by placing the shift-in character in position 75 of the continued line and placing the shift-out character in position 8 of the continuation line. This SQL statement has a valid graphic constant of G'<AABBCCDDEEFFGGHHIIJJKK>'.
*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....8
C/EXEC SQL SELECT * FROM GRAPHTAB WHERE GRAPHCOL = G’<AABB>
C+<CCDDEEFFGGHHIIJJKK>’
C/END-EXEC
Including code in RPG/400 applications that use SQL
SQL statements and RPG/400 calculation specifications can be included by embedding the SQL statement.
90
IBM i: Embedded SQL programming
*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....8
C/EXEC SQL INCLUDE member-name
C/END-EXEC
The /COPY statement can be used to include SQL statements or RPG/400 specifications.
Sequence numbers in RPG/400 applications that use SQL
The sequence numbers of the source statements generated by the SQL precompiler are based on the
*NOSEQSRC/*SEQSRC keywords of the OPTION parameter on the CRTSQLRPG command.
When *NOSEQSRC is specified, the sequence number from the input source member is used. For
*SEQSRC, the sequence numbers start at 000001 and are incremented by 1.
Names in RPG/400 applications that use SQL
Any valid RPG variable name can be used for a host variable and is subject to these restrictions.
Do not use host variable names or external entry names that begin with 'SQ', 'SQL', 'RDI', or 'DSN'. These names are reserved for the database manager.
Statement labels in RPG/400 applications that use SQL
A TAG statement can precede any SQL statement. Code the TAG statement on the line preceding EXEC
SQL.
WHENEVER statement in RPG/400 applications that use SQL
The target for the GOTO clause must be the label of the TAG statement. The scope rules for the
GOTO/TAG must be observed.
Using host variables in RPG/400 applications that use SQL
All host variables used in SQL statements must be explicitly declared. LOB, XML, ROWID, result set locator, and binary host variables are not supported in RPG/400.
SQL embedded in RPG/400 does not use the SQL BEGIN DECLARE SECTION and END DECLARE
SECTION statements to identify host variables. Do not put these statements in the source program.
All host variables within an SQL statement must be preceded by a colon (:).
The names of host variables must be unique within the program.
Declaring host variables in RPG/400 applications that use SQL
The SQL RPG/400 precompiler only recognizes a subset of RPG/400 declarations as valid host variable declarations.
Most variables defined in RPG/400 can be used in SQL statements. A partial listing of variables that are not supported includes the following: v Indicator field names (*INxx) v Tables v UDATE v UDAY v UMONTH v UYEAR v
Look-ahead fields v Named constants
Embedded SQL programming
91
Fields used as host variables are passed to SQL, using the CALL/PARM functions of RPG/400. If a field cannot be used in the result field of the PARM, it cannot be used as a host variable.
Using host structures in RPG/400 applications that use SQL
The RPG/400 data structure name can be used as a host structure name if subfields exist in the data structure. The use of the data structure name in an SQL statement implies that it is the list of subfield names that make up the data structure.
When subfields are not present for the data structure, then the data structure name is a host variable of character type. This allows character variables larger than 256, because data structures can be up to 9999.
In the following example, BIGCHR is an RPG/400 data structure without subfields. SQL treats any referrals to BIGCHR as a character string with a length of 642.
*...1....+....2....+....3....+....4....+....5....+....6....+....7...*
IBIGCHR DS 642
In the next example, PEMPL is the name of the host structure consisting of the subfields EMPNO,
FIRSTN, MIDINT, LASTNAME, and DEPTNO. The referral to PEMPL uses the subfields. For example, the first column of EMPLOYEE is placed in EMPNO, the second column is placed in FIRSTN, and so on.
I
I
I
I
I
*...1....+....2....+....3....+....4....+....5....+....6....+....7. ..*
IPEMPL DS
01
07
06 EMPNO
18 FIRSTN
19
20
35
19 MIDINT
34 LASTNA
37 DEPTNO
...
C MOVE ’000220’ EMPNO
...
C/EXEC SQL
C+ SELECT * INTO :PEMPL
C+ FROM CORPDATA.EMPLOYEE
C+ WHERE EMPNO = :EMPNO
C/END-EXEC
When writing an SQL statement, referrals to subfields can be qualified. Use the name of the data structure, followed by a period and the name of the subfield. For example, PEMPL.MIDINT is the same as specifying only MIDINT.
Using host structure arrays in RPG/400 applications that use SQL
A host structure array is defined as an occurrence data structure. An occurrence data structure can be used on the SQL FETCH statement when fetching multiple rows.
In these examples, the following are true: v All items in BARRAY must be valid host variables.
v All items in BARRAY must be contiguous. The first FROM position must be 1 and there cannot be overlaps in the TO and FROM positions.
v For all statements other than the multiple-row FETCH and blocked INSERT, if an occurrence data structure is used, the current occurrence is used. For the multiple-row FETCH and blocked INSERT, the occurrence is set to 1.
I
I
*...1....+....2....+....3....+....4....+....5....+....6....+....7. ..*
IBARRAY DS 10
B
01 20 C1VAR
21 220C2VAR
92
IBM i: Embedded SQL programming
The following example uses a host structure array called DEPT and a multiple-row FETCH statement to retrieve 10 rows from the DEPARTMENT table.
*...1....+....2....+....3....+....4....+....5....+....6....+....7...*
E INDS 4 4 0
IDEPT
I
DS 10
01 03 DEPTNO
I
I
I
IINDARR
I
DS
04
33
39
10
32 DEPTNM
38 MGRNO
41 ADMRD
B 1 80INDS
...
C/EXEC SQL
C+ DECLARE C1 CURSOR FOR
C+
C+
SELECT *
FROM
CORPDATA.DEPARTMENT
C/END-EXEC
C/EXEC SQL
C+ OPEN C1
C/END-EXEC
C/EXEC SQL
C+ FETCH C1 FOR 10 ROWS INTO :DEPT:INDARR
C/END-EXEC
Using external file descriptions in RPG/400 applications that use SQL
The SQL precompiler processes the RPG/400 source in much the same manner as the ILE RPG compiler.
This means that the precompiler processes the /COPY statement for definitions of host variables.
Field definitions for externally described files are obtained and renamed, if different names are specified.
The external definition form of the data structure can be used to obtain a copy of the column names to be used as host variables.
In the following example, the sample table DEPARTMENT is used as a file in an RPG/400 program. The
SQL precompiler retrieves the field (column) definitions for DEPARTMENT for use as host variables.
I
I
*...1....+....2....+....3....+....4....+....5....+....6....+....7....*
FTDEPT IP E DISK
F
IDEPTREC
TDEPT KRENAMEDEPTREC
DEPTNAME
ADMRDEPT
DEPTN
ADMRD
Note:
Code an F-spec for a file in your RPG program only if you use RPG/400 statements to do I/O operations to the file. If you use only SQL statements to do I/O operations to the file, you can include the external definition by using an external data structure.
In the following example, the sample table is specified as an external data structure. The SQL precompiler retrieves the field (column) definitions as subfields of the data structure. Subfield names can be used as host variable names, and the data structure name TDEPT can be used as a host structure name. The field names must be changed because they are greater than six characters.
I
I
*...1....+....2....+....3....+....4....+....5....+....6....+....7....*
ITDEPT E DSDEPARTMENT
DEPTNAME
ADMRDEPT
DEPTN
ADMRD
Note:
DATE, TIME, and TIMESTAMP columns will generate host variable definitions that are treated by
SQL with the same comparison and assignment rules as a DATE, TIME, and TIMESTAMP column. For example, a date host variable can only be compared against a DATE column or a character string that is a valid representation of a date.
Embedded SQL programming
93
Although varying-length columns generate fixed-length character-host variable definitions, to SQL they are varying-length character variables.
Although GRAPHIC and VARGRAPHIC columns are mapped to character variables in RPG/400, SQL considers these GRAPHIC and VARGRAPHIC variables. If the GRAPHIC or VARGRAPHIC column has a
UCS-2 CCSID, the generated host variable will have the UCS-2 CCSID assigned to it. If the GRAPHIC or
VARGRAPHIC column has a UTF-16 CCSID, the generated host variable will have the UTF-16 CCSID assigned to it.
|
| CLOB, BLOB, and DBCLOB columns in the external file are ignored. No host variable definition will be generated in the host structure for these types.
External file description considerations for host structure arrays in RPG/400 applications that use SQL
Field definitions for externally described files, including renaming of fields, are recognized by the SQL precompiler.
The external definition form of the data structure can be used to obtain a copy of the column names to be used as host variables.
In the following example, the DEPARTMENT table is included in the RPG/400 program and is used to declare a host structure array. A multiple-row FETCH statement is then used to retrieve 10 rows into the host structure array.
I
I
*...1....+....2....+....3....+....4....+....5....+....6....*
ITDEPT E DSDEPARTMENT 10
DEPARTMENT
ADMRDEPT
DEPTN
ADMRD
...
C/EXEC SQL
C+ DECLARE C1 CURSOR FOR
C+
C+
SELECT *
C/END-EXEC
FROM CORPDATA.DEPARTMENT
...
C/EXEC SQL
C+ FETCH C1 FOR 10 ROWS INTO :TDEPT
C/END-EXEC
Determining equivalent SQL and RPG/400 data types
The precompiler determines the base SQLTYPE and SQLLEN of host variables based on the table. If a host variable appears with an indicator variable, the SQLTYPE is the base SQLTYPE plus one.
Table 7. RPG/400 declarations mapped to typical SQL data types
RPG/400 data type
Data Structure subfield
Data structure
(without subfields)
Input field
Col 43
blank n/a blank
Col 52
blank n/a blank
Other RPG/400 coding
Length = n where n ≤
256
Length = n where n ≤
9999
Length = n where n ≤
256
SQLTYPE of host variable
452
SQLLEN of host variable
n
452
452 n n
SQL data type
CHAR(n)
CHAR(n)
CHAR(n)
94
IBM i: Embedded SQL programming
Table 7. RPG/400 declarations mapped to typical SQL data types (continued)
RPG/400 data type
Calculation result field
Data Structure subfield
Data Structure subfield
Data Structure subfield
Col 43
n/a
B
B
B
Col 52
blank
0
0
1-4
Other RPG/400 coding
Length = n where n ≤
256
Length = 2
Length = 4
Length = 2
SQLTYPE of host variable
452
500
496
500
SQLLEN of host variable
n
2
4
Data Structure subfield
Data Structure subfield
Input field
Input field
Input field
Calculation result field
Data Structure subfield
B
P
P blank
B n/a blank
1-9
0 to 9
0 to 9
0 to 9
0 to 4 if n
= 2; 0 to 9 if n = 4
0 to 9
0 to 9
Length = 4
Length = n where n is
1 to 16
Length = n where n is
1 to 16
Length = n where n is
1 to 30
Length = 2 or 4
Length = n where n is
1 to 30
Length = n where n is
1 to 30
496
484
484
484
484
484
488
SQL data type
CHAR(n)
SMALLINT
INTEGER
2
4 p in byte 1, s in byte 2 p in byte 1, s in byte 2 p in byte 1, s in byte 2 p in byte 1, s in byte 2 p in byte 1, s in byte 2 p in byte 1, s in byte 2
DECIMAL(4,s) where s=column 52
DECIMAL(9,s) where s=column 52
DECIMAL(p,s) where p = n*2-1 and s = column 52
DECIMAL(p,s) where p = n*2-1 and s = column 52
DECIMAL(p,s) where p = n and s = column
52
DECIMAL(p,s) where p=4 if n=2 or 9 if n=4 and s = column
52
DECIMAL(p,s) where p = n and s = column
52
NUMERIC(p,s) where p = n and s = column
52
Use the information in the following table to determine the RPG/400 data type that is equivalent to a given SQL data type.
Table 8. SQL data types mapped to typical RPG/400 declarations
SQL data type
SMALLINT
INTEGER
RPG/400 data type
Subfield of a data structure. B in position 43, length must be 2 and 0 in position 52 of the subfield specification.
Subfield of a data structure. B in position 43, length must be 4 and 0 in position 52 of the subfield specification.
Notes
Embedded SQL programming
95
Table 8. SQL data types mapped to typical RPG/400 declarations (continued)
SQL data type
BIGINT
DECIMAL
RPG/400 data type
No exact equivalent
Subfield of a data structure. P in position 43 and 0 through 9 in position 52 of the subfield specification.
Notes
Use P in position 43 and 0 in position 52 of the subfield specification.
Maximum length of 16 (precision 30) and maximum scale of 9.
NUMERIC
DECFLOAT
FLOAT (single precision)
FLOAT (double precision)
CHAR(n)
OR
Defined as numeric and not a subfield of a data structure.
Subfield of the data structure. Blank in position 43 and 0 through 9 in position 52 of the subfield
Not supported
No exact equivalent
No exact equivalent
Maximum length of 30 (precision 30) and maximum scale of 9.
Not supported
Use one of the alternative numeric data types described above.
Use one of the alternative numeric data types described above.
n can be from 1 to 256.
Subfield of a data structure or input field.
Blank in positions 43 and 52 of the specification.
OR
CHAR(n)
VARCHAR(n)
CLOB
GRAPHIC(n)
VARGRAPHIC(n)
DBCLOB
BINARY
VARBINARY
BLOB
DATE
TIME
Calculation result field defined without decimal places.
Data structure name with no subfields in the data structure.
No exact equivalent
Not supported
Not supported
Not supported
Not supported
Not supported
Not supported
Not supported
Subfield of a data structure. Blank in position
52 of the subfield specification.
OR
n can be from 1 to 9999.
Use a character host variable large enough to contain the largest expected VARCHAR value.
Not supported
Not supported
Not supported
Not supported
Not supported
Not supported
Not supported
If the format is *USA, *JIS, *EUR, or *ISO, the length must be at least 10. If the format is
*YMD, *DMY, or *MDY, the length must be at least 8. If the format is *JUL, the length must be at least 6.
Field defined without decimal places.
Subfield of a data structure. Blank in position
52 of the subfield specification.
Length must be at least 6; to include seconds, length must be at least 8.
OR
Field defined without decimal places.
96
IBM i: Embedded SQL programming
Table 8. SQL data types mapped to typical RPG/400 declarations (continued)
SQL data type
TIMESTAMP
RPG/400 data type
Subfield of a data structure. Blank in position
52 of the subfield specification.
OR
Notes
Length must be at least 19. To include microseconds at full precision, length must be
26. If length is less than 26, truncation occurs on the microseconds part.
XML
DATALINK
ROWID
Result set locator
Field defined without decimal places.
Not supported
Not supported
Not supported
Not supported
Not supported
Not supported
Not supported
Not supported
Assignment rules in RPG/400 applications that use SQL
RPG/400 associates precision and scale with all numeric types.
RPG/400 defines numeric operations, assuming the data is in packed format. This means that operations involving binary variables include an implicit conversion to packed format before the operation is performed (and back to binary, if necessary). Data is aligned to the implied decimal point when SQL operations are performed.
Using indicator variables in RPG/400 applications that use SQL
An indicator variable is a two-byte integer.
See the entry for the SMALLINT SQL data type in Table 7 on page 94.
An indicator structure can be defined by declaring the variable as an array with an element length of 4,0 and declaring the array name as a subfield of a data structure with B in position 43.
Indicator variables are declared in the same way as host variables and the declarations of the two can be mixed in any way that seems appropriate to the programmer.
Related reference
:
References to variables
“Indicator variables in applications that use SQL” on page 4
An indicator variable is a halfword integer variable used to communicate additional information about its associated host variable.
Example: Using indicator variables in RPG/400 applications that use SQL
This example shows declaring indicator variables in RPG.
Given the statement:
*...1....+....2....+....3....+....4....+....5....+....6....+....7...*
C/EXEC SQL FETCH CLS_CURSOR INTO :CLSCD,
C+
C+
:DAY :DAYIND,
:BGN :BGNIND,
C+
C/END-EXEC
:END :ENDIND variables can be declared as follows:
I
I
*...1....+....2....+....3....+....4....+....5....+....6....+....7...*
I DS
I
B
B
1
8
10
7 CLSCD
90DAY
110DAYIND
Embedded SQL programming
97
I
I
I
I
12 19 BGN
B 20 210BGNIND
22 29 END
B 30 310ENDIND
Differences in RPG/400 because of structure parameter passing techniques
The SQL RPG/400 precompiler attempts to use the structure parameter passing technique, if possible.
The precompiler generates code where each host variable is a separate parameter when the following conditions are true: v The data length of the host variables, referred to in the statement, is greater than 9935. Because SQL uses 64 bytes of the structure, 9935 + 64 = 9999, the maximum length of a data structure.
v An indicator is specified on the statement where the length of the indexed indicator name plus the required index value is greater than six characters. The precompiler must generate an assignment statement for the indicator with the indicator name in the result field that is limited to six characters
("INDIC,1" requires seven characters).
v The length of a host variable is greater than 256. This can happen when a data structure without subfields is used as a host variable, and its length exceeds 256. Subfields cannot be defined with a length greater than 256.
Related concepts
:
Application design tips for database performance
Correctly ending a called RPG/400 program that uses SQL
SQL run time builds and maintains data areas (internal SQLDAs) for each SQL statement that contains host variables.
These internal SQLDAs are built the first time the statement is run and then reused on subsequent executions of the statement to increase performance. The internal SQLDAs can be reused as long as there is at least one SQL program active. The SQL precompiler allocates static storage used by SQL run time to manage the internal SQLDAs properly.
If an RPG/400 program containing SQL is called from another program that also contains SQL, the
RPG/400 program should not set the Last Record (LR) indicator on. Setting the LR indicator on causes the static storage to be re-initialized the next time the RPG/400 program is run. Re-initializing the static storage causes the internal SQLDAs to be rebuilt, thus causing a performance degradation.
An RPG/400 program containing SQL statements that is called by a program that also contains SQL statements, should be ended one of two ways: v By the RETRN statement v By setting the RT indicator on.
This allows the internal SQLDAs to be used again and reduces the total run time.
Coding SQL statements in ILE RPG applications
You need to be aware of the unique application and coding requirements for embedding SQL statements in an ILE RPG program. In this topic, the coding requirements for host variables are defined.
|
|
|
Not all features implemented by the ILE RPG compiler are supported by the SQL precompiler.
v If a control specification is not present in the program source, the RPG compiler searches for a data area containing control specification keywords. This feature is not supported by the SQL precompiler.
98
IBM i: Embedded SQL programming
Note:
For more information about programming using ILE RPG, see the ILE RPG Programmer's Guide topic and the ILE RPG Language Reference
Related concepts
: topic.
“Writing applications that use SQL” on page 2
You can create database applications in host languages that use DB2 for i SQL statements and functions.
Related reference
:
“Example programs: Using DB2 for i statements” on page 149
Here is a sample application that shows how to code SQL statements in each of the languages that DB2 for i supports.
“Example: SQL statements in ILE RPG programs” on page 177
This example program is written in the ILE RPG programming language.
Defining the SQL communication area in ILE RPG applications that use SQL
The SQL precompiler automatically places the SQL communication area (SQLCA) in the definition specifications of the ILE RPG program before the first calculation specification, unless a SET OPTION
SQLCA = *NO statement is found.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
INCLUDE SQLCA should not be coded in the source program. If the source program specifies INCLUDE
SQLCA, the statement will be accepted, but it is redundant. The SQLCA source statements for ILE RPG are:
// SQL COMMUNICATION AREA
DCL-DS SQLCA;
SQLCAID CHAR(8) INZ(X’0000000000000000’);
SQLAID CHAR(8) OVERLAY(SQLCAID);
SQLCABC INT(10);
SQLABC BINDEC(9) OVERLAY(SQLCABC);
SQLCODE INT(10);
SQLCOD BINDEC(9) OVERLAY(SQLCODE);
SQLERRML INT(5);
SQLERL BINDEC(4) OVERLAY(SQLERRML);
SQLERRMC CHAR(70);
SQLERM CHAR(70) OVERLAY(SQLERRMC);
SQLERRP CHAR(8);
SQLERP CHAR(8) OVERLAY(SQLERRP);
SQLERR CHAR(24);
SQLER1 BINDEC(9) OVERLAY(SQLERR:*NEXT);
SQLER2 BINDEC(9) OVERLAY(SQLERR:*NEXT);
SQLER3 BINDEC(9) OVERLAY(SQLERR:*NEXT);
SQLER4 BINDEC(9) OVERLAY(SQLERR:*NEXT);
SQLER5 BINDEC(9) OVERLAY(SQLERR:*NEXT);
SQLER6 BINDEC(9) OVERLAY(SQLERR:*NEXT);
SQLERRD INT(10) DIM(6) OVERLAY(SQLERR);
SQLWRN CHAR(11);
SQLWN0 CHAR(1) OVERLAY(SQLWRN:*NEXT);
SQLWN1 CHAR(1) OVERLAY(SQLWRN:*NEXT);
SQLWN2 CHAR(1) OVERLAY(SQLWRN:*NEXT);
SQLWN3 CHAR(1) OVERLAY(SQLWRN:*NEXT);
SQLWN4 CHAR(1) OVERLAY(SQLWRN:*NEXT);
SQLWN5 CHAR(1) OVERLAY(SQLWRN:*NEXT);
SQLWN6 CHAR(1) OVERLAY(SQLWRN:*NEXT);
SQLWN7 CHAR(1) OVERLAY(SQLWRN:*NEXT);
SQLWN8 CHAR(1) OVERLAY(SQLWRN:*NEXT);
SQLWN9 CHAR(1) OVERLAY(SQLWRN:*NEXT);
SQLWNA CHAR(1) OVERLAY(SQLWRN:*NEXT);
Embedded SQL programming
99
|
|
|
|
SQLWARN CHAR(1) DIM(11) OVERLAY(SQLWRN);
SQLSTATE CHAR(5);
SQLSTT CHAR(5) OVERLAY(SQLSTATE);
END-DS SQLCA;
|
|
If a SET OPTION SQLCA = *NO statement is found, the SQL precompiler automatically places
SQLCODE and SQLSTATE variables in the definition specification. They are defined as follows when the
SQLCA is not included:
DCL-S SQLCODE INT(10);
DCL-S SQLSTATE CHAR(5);
Related reference
:
SQL communication area
Defining SQL descriptor areas in ILE RPG applications that use SQL
There are two types of SQL descriptor areas (SQLDAs). One is defined with the ALLOCATE
DESCRIPTOR statement. The other is defined using the SQLDA structure. In this topic, only the SQLDA form is discussed.
The following statements can use an SQLDA: v EXECUTE...USING DESCRIPTOR descriptor-name v FETCH...USING DESCRIPTOR descriptor-name v OPEN...USING DESCRIPTOR descriptor-name v CALL...USING DESCRIPTOR descriptor-name v DESCRIBE statement-name INTO descriptor-name v
DESCRIBE CURSOR cursor-name INTO descriptor-name v DESCRIBE INPUT statement-name INTO descriptor-name v DESCRIBE PROCEDURE procedure-name INTO descriptor-name v DESCRIBE TABLE host-variable INTO descriptor-name v PREPARE statement-name INTO descriptor-name
Unlike the SQLCA, there can be more than one SQLDA in a program and an SQLDA can have any valid name.
Dynamic SQL is a programming technique. With dynamic SQL, your program can develop and then run
SQL statements while the program is running. A SELECT statement with a variable SELECT list (that is, a list of columns to be returned as part of the query) that runs dynamically requires an SQL descriptor area
(SQLDA). This is because you cannot know in advance how many or what type of variables to allocate in order to receive the results of the SELECT.
You can specify an INCLUDE SQLDA statement in an ILE RPG program. If an INCLUDE SQLDA statement is found anywhere in your program, the SQLDA structure is generated one time as part of the global definitions in your program.
EXEC SQL INCLUDE SQLDA;
The INCLUDE SQLDA generates the following data structure.
// SQL DESCRIPTOR AREA
DCL-DS SQLDA;
SQLDAID CHAR(8);
SQLDABC INT(10);
SQLN INT(5);
SQLD INT(5);
SQL_VAR CHAR(80) DIM(SQL_NUM);
*N POINTER OVERLAY(SQL_VAR:17);
*N POINTER OVERLAY(SQL_VAR:33);
100
IBM i: Embedded SQL programming
END-DS SQLDA;
DCL-DS SQLVAR;
SQLTYPE INT(5);
SQLLEN INT(5);
SQLRES CHAR(12);
SQLINFO1 CHAR(16);
SQLDATA POINTER OVERLAY(SQLINFO1);
SQL_RESULT_SET_LOCATOR INT(20) OVERLAY(SQLINFO1);
SQLINFO2 CHAR(16);
SQLIND POINTER OVERLAY(SQLINFO2);
SQL_ROW_CHANGE INT(10) OVERLAY(SQLINFO2);
SQL_RESULT_SET_ROWS INT(10) OVERLAY(SQLINFO2);
SQLNAMELEN INT(5);
SQLNAME CHAR(30);
END-DS SQLVAR;
// EXTENDED SQLDA
DCL-DS SQLVAR2;
SQLLONGL INT(10);
SQLRSVDL CHAR(28);
SQLDATAL POINTER;
SQLTNAMELN INT(5);
SQLTNAME CHAR(30);
END-DS SQLVAR2;
The user is responsible for the definition of SQL_NUM. SQL_NUM must be defined as a numeric constant with the dimension required for SQL_VAR.
The INCLUDE SQLDA generates two data structures. The second data structure is used to setup and reference the part of the SQLDA that contains the field descriptions.
To set the field descriptions of the SQLDA the program sets up the field description in the subfields of
SQLVAR and then assigns SQLVAR to SQL_VAR(n), where n is the number of the field in the SQLDA.
This is repeated until all the field descriptions are set.
When the SQLDA field descriptions are to be referenced the user assigns SQLVAR(n) to SQL_VAR where n is the number of the field description to be processed.
Related concepts
:
Dynamic SQL applications
Related reference
:
SQL descriptor area
Embedding SQL statements in ILE RPG applications that use SQL
SQL statements coded in an ILE RPG program can be placed in the calculation section or in a free-form calculation block.
SQL statements can be placed in detail calculations, in total calculations, or in RPG subroutines. The SQL statements are run based on the logic of the RPG statements.
Both uppercase and lowercase letters are acceptable in SQL statements.
Fixed-form RPG
The keywords EXEC SQL indicate the beginning of an SQL statement. EXEC SQL must occupy positions
8 through 16 of the source statement, preceded by a / in position 7. The SQL statement may start in position 17 and continue through position 80.
The keyword END-EXEC ends the SQL statement. END-EXEC must occupy positions 8 through 16 of the source statement, preceded by a slash (/) in position 7. Positions 17 through 80 must be blank.
Embedded SQL programming
101
An UPDATE statement coded in an ILE RPG program might be coded as follows:
C/EXEC SQL UPDATE DEPARTMENT
C+ SET MANAGER = :MGRNUM
C+
C/END-EXEC
WHERE DEPTNO = :INTDEP
Free-form RPG
Each SQL statement must begin with EXEC SQL and end with a semicolon (;). The EXEC SQL keywords must be on one line. The remaining part of the SQL statement can be on more than one line. Each SQL statement should start on a new line. No other statement should be on the same line as the SQL statement.
An UPDATE statement coded in free form might be coded in the following way:
EXEC SQL UPDATE DEPARTMENT
SET MGRNO = :MGR_NUM
WHERE DEPTNO = :INT_DEP;
Comments in ILE RPG applications that use SQL
In addition to SQL comments (--), ILE RPG comments can be included within SQL statements wherever
SQL allows a blank character.
Fixed-form RPG
To embed an ILE RPG comment within the SQL statement, place an asterisk (*) in position 7.
Free-form RPG
Bracketed comments (/*...*/) are allowed within embedded SQL statements whenever a blank is allowed, except between the keywords EXEC and SQL. Comments can span any number of lines. Single-line comments (//) can also be used.
Continuation for SQL statements in ILE RPG applications that use SQL
SQL statements can be continued across many records in ILE RPG.
Fixed-form RPG
When additional records are needed to contain the SQL statement, positions 9 through 80 can be used.
Position 7 must be a plus sign (+), and position 8 must be blank. Position 80 of the continued line is concatenated with position 9 of the continuation line.
Constants containing DBCS data can be continued across multiple lines by placing the shift-in character in position 81 of the continued line and placing the shift-out character in position 8 of the continuation line.
In this example, the SQL statement has a valid graphic constant of G'<AABBCCDDEEFFGGHHIIJJKK>'.
C/EXEC SQL SELECT * FROM GRAPHTAB WHERE GRAPHCOL = G’<AABBCCDDEE>
C+<FFGGHHIIJJKK>’
C/END-EXEC
Free-form RPG
SQL statements can be contained on one or more lines. To continue an SQL statement across multiple lines, the SQL statement can be split wherever a blank is allowed. The plus sign (+) can be used to indicate a continuation of a string constant. The literal continues with the first nonblank character on the next line.
102
IBM i: Embedded SQL programming
Including code in ILE RPG applications that use SQL
To include SQL statements and RPG specifications in ILE RPG applications, use the SQL INCLUDE statement.
C/EXEC SQL INCLUDE member-name
C/END-EXEC
RPG directives are handled by the SQL precompiler according to the value of the RPG preprocessor options parameter (RPGPPOPT).
Related reference
:
“Using directives in ILE RPG applications that use SQL”
RPG directives are handled by the SQL precompiler according to the value of the RPG preprocessor options parameter (RPGPPOPT). If the RPG preprocessor is used, the SQL precompile will run using the expanded preprocessed source.
|
|
|
|
Using directives in ILE RPG applications that use SQL
RPG directives are handled by the SQL precompiler according to the value of the RPG preprocessor options parameter (RPGPPOPT). If the RPG preprocessor is used, the SQL precompile will run using the expanded preprocessed source.
v When the value is *NONE, the RPG preprocessor is not called to preprocess the RPG source. When a source stream file is precompiled, no directives are recognized by SQL. When a source member is precompiled, the only directive that is handled by the SQL precompiler is /COPY. Nested /COPY statements are not handled. In fully free-form source mode, /COPY statements that start in any column are handled by the SQL precompiler. In column-limited source mode, only /COPY statements that start in column 7 are handled by the SQL precompiler. All /COPY statements must reference a source member; they cannot reference a source stream file. All other directives are ignored until the RPG compiler is called. This means that all RPG and SQL statements within conditional logic blocks are processed unconditionally by the SQL precompiler.
v When the value is *LVL1, the RPG preprocessor will be called to preprocess the RPG source. All
/COPY statements are expanded, even nested /COPY statements, and the conditional compilation directives will be handled.
v When the value is *LVL2, the RPG preprocessor will be called to preprocess the RPG source. All
/COPY and /INCLUDE statements are expanded and the conditional compilation directives will be handled.
v When *LVL1 or *LVL2 is used, there is a possibility that the expanded source generated by the RPG preprocessor will become very large and reach a resource limit due to the expansion of the /COPY and
/INCLUDE statements. If this happens you must either break up your source into smaller pieces, or not use the RPG preprocessor.
Related reference
:
“Including code in ILE RPG applications that use SQL”
To include SQL statements and RPG specifications in ILE RPG applications, use the SQL INCLUDE statement.
Sequence numbers in ILE RPG applications that use SQL
The sequence numbers of the source statements generated by the SQL precompiler are based on the
*NOSEQSRC/*SEQSRC keywords of the OPTION parameter on the CRTSQLRPGI command.
When *NOSEQSRC is specified, the sequence number from the input source member is used. For
*SEQSRC, the sequence numbers start at 000001 and are incremented by 1.
Names in ILE RPG applications that use SQL
Any valid ILE RPG variable name can be used for a host variable with these restrictions.
v Do not use host variable names or external entry names that begin with the characters SQ, SQL, RDI, or DSN. These names are reserved for the database manager.
v The maximum length of host variable names is 64 characters.
Embedded SQL programming
103
Statement labels in ILE RPG applications that use SQL
A TAG statement can precede any SQL statement. Code the TAG statement on the line preceding EXEC
SQL.
WHENEVER statement in ILE RPG applications that use SQL
The target for the GOTO clause must be the label of the TAG statement. The scope rules for the
GOTO/TAG must be observed.
Using host variables in ILE RPG applications that use SQL
All host variables used in SQL statements must be explicitly declared.
SQL embedded in ILE RPG does not use the SQL BEGIN DECLARE SECTION and END DECLARE
SECTION statements to identify host variables. Do not put these statements in the source program.
All host variables within an SQL statement must be preceded by a colon (:). Names of host variables do not need to be unique within the program. The precompiler recognizes variables with the same name in different procedures and scopes them correctly.
An SQL statement that uses a host variable must be within the scope of the variable's declaration. A
DECLARE CURSOR statement must be in the same scope as its OPEN statement to guarantee that any variables used by the DECLARE CURSOR will use the definition in the scope of the OPEN.
If an error stating that a host variable is not defined or not usable is issued, look at the cross-reference in the precompiler listing to see how the precompiler defined the variable. To generate a cross-reference in the listing, run the precompile command with *XREF specified on the OPTIONS parameter.
Declaring host variables in ILE RPG applications that use SQL
The SQL ILE RPG precompiler only recognizes a subset of valid ILE RPG declarations as valid host variable declarations.
Most variables defined in ILE RPG can be used in SQL statements. A partial listing of variables that are not supported includes the following: v Unsigned integers v Pointer v Tables v UDATE v UDAY v
UMONTH v UYEAR v Look-ahead fields v Named constants v Multiple dimension arrays v Definitions requiring the resolution of %SIZE or %ELEM v Definitions requiring the resolution of constants unless the constant is used in OCCURS, DIM,
OVERLAY, or POS and the constant is declared before it is used in the OCCURS, DIM, OVERLAY, or
POS.
Fields used as host variables are passed to SQL using the CALL/PARM functions of ILE RPG. If a field cannot be used in the result field of the PARM, it cannot be used as a host variable.
Date and time host variables are always assigned to corresponding date and time subfields in the structures generated by the SQL precompiler. The generated date and time subfields are declared using
104
IBM i: Embedded SQL programming
the format and separator specified by the DATFMT, DATSEP, TIMFMT, and TIMSEP parameters on the
CRTSQLRPGI command or with the SET OPTION statement. Conversion from the user declared host variable format to the precompile specified format occurs on assignment to and from the SQL generated structure. If the DATFMT parameter value is a system format (*MDY, *YMD, *DMY, or *JUL), then all input and output host variables must contain date values within the range 1940-2039. If any date value is outside of this range, then the DATFMT on the precompile must be specified as one of the IBM SQL formats of *ISO, *USA, *EUR, or *JIS.
The SQL precompiler accepts variables defined as VARYING(2), but does not support VARYING(4). The
LEN keyword is recognized, but only lengths up to the SQL limit for the data type are accepted.
Graphic host variables will use the RPG CCSID value if one is specified. An SQL DECLARE VARIABLE statement cannot be used to change the CCSID of a host variable whose CCSID has been defined in RPG, or a host variable that is defined as UCS-2 or UTF-16.
The precompiler will generate an RPG logical (indicator) variable as a character of length 1. This type can be used wherever SQL allows a character host variable. It cannot be used as an SQL indicator variable. It is up to the user to make sure that only values of 1 or 0 are assigned to it.
The precompiler supports EXTNAME, but does not support EXTNAME(filename : fmtname : fieldtype), where fieldtype is *ALL, *INPUT, *OUTPUT, or *KEY.
The precompiler supports LIKEREC(intrecname), but does not support the optional second parameter.
The precompiler supports EXTDESC(literal), but does not support EXTDESC(constant).
|
|
For SQLTYPE declarations, the precompiler only supports the CCSID keyword. All other keywords are ignored.
Declaring binary host variables in ILE RPG applications that use SQL:
ILE RPG does not have variables that correspond to the SQL binary data types.
To create host variables that can be used with these data types, use the SQLTYPE keyword. The SQL precompiler replaces this declaration with an ILE RPG language declaration in the output source member.
Binary declarations can be either standalone or within a data structure.
BINARY example
v The following declaration in free-form:
DCL-S MYBINARY SQLTYPE(BINARY:50); results in the generation of the following code:
DCL-S MYBINARY CHAR(50) CCSID(*HEX); v The following declaration in fixed-form:
D MYBINARY S SQLTYPE(BINARY:50) results in the generation of the following code:
D MYBINARY S 50A CCSID(*HEX)
VARBINARY example
v The following declaration in free-form:
DCL-S MYVARBINARY SQLTYPE(VARBINARY:100); results in the generation of the following code:
DCL-S MYVARBINARY VARCHAR(100) CCSID(*HEX) v The following declaration in fixed-form:
Embedded SQL programming
105
D MYVARBINARY S SQLTYPE(VARBINARY:100) results in the generation of the following code:
D MYVARBINARY S 100A VARYING CCSID(*HEX)
Notes:
1.
For BINARY host variables, the length must be in the range 1 to 32766.
2.
For VARBINARY host variables, the length must be in the range 1 to 32740.
3.
BINARY and VARBINARY host variables are allowed to be declared in host structures.
4.
SQLTYPE, BINARY, and VARBINARY can be in mixed case.
5.
SQLTYPE must be between positions 44 to 80 for fixed-form declarations.
6.
When a BINARY or VARBINARY is declared as a standalone host variable, position 24 must contain the character S and position 25 must be blank for fixed-form declarations.
7.
The standalone field indicator S in position 24 for fixed-form declarations should be omitted when a
BINARY or VARBINARY host variable is declared in a host structure.
Declaring LOB host variables in ILE RPG applications that use SQL:
ILE RPG does not have variables that correspond to the SQL data types for LOBs (large objects).
To create host variables that can be used with these data types, use the SQLTYPE keyword. The SQL precompiler replaces this declaration with an ILE RPG language structure in the output source member.
LOB declarations can be either standalone or within a data structure.
LOB host variables in ILE RPG applications that use SQL:
Here are some examples of LOB host variables (CLOB, DBCLOB, BLOB) in ILE RPG applications.
CLOB example
v The following declaration in free-form:
DCL-S MYCLOB SQLTYPE(CLOB:1000); results in the generation of the following structure:
DCL-DS MYCLOB;
MYCLOB_LEN UNS(10);
MYCLOB_DATA CHAR(1000);
END-DS MYCLOB; v The following declaration in fixed-form:
D MYCLOB S SQLTYPE(CLOB:1000) results in the generation of the following structure:
D MYCLOB
D MYCLOB_LEN
D MYCLOB_DATA
DS
10U
1000A
DBCLOB example
v The following declaration in free-form:
DCL-S MYDBCLOB SQLTYPE(DBCLOB:400); results in the generation of the following structure:
DCL-DS MYDBCLOB;
MYDBCLOB_LEN UNS(10);
MYDBCLOB_DATA GRAPH(400);
END-DS MYDBCLOB; v The following declaration in fixed-form:
D MYDBCLOB S SQLTYPE(DBCLOB:400)
106
IBM i: Embedded SQL programming
results in the generation of the following structure:
D MYDBCLOB
D MYDBCLOB_LEN
D MYDBCLOB_DATA
DS
10U
400G
BLOB example
v The following declaration in free-form:
DCL-S MYBLOB SQLTYPE(BLOB:500); results in the generation of the following structure:
DCL-DS MYBLOB;
MYBLOB_LEN UNS(10);
MYBLOB_DATA CHAR(500) CCSID(*HEX);
END-DS MYBLOB; v The following declaration in fixed-form:
D MYBLOB S SQLTYPE(BLOB:500) results in the generation of the following structure:
D MYBLOB
D MYBLOB_LEN
D MYBLOB_DATA
DS
10U
500A CCSID(*HEX)
Notes:
1.
For BLOB and CLOB, 1 ≤ lob-length ≤ 16 773 100.
2.
For DBCLOB, 1≤ lob-length ≤ 8 386 550.
3.
LOB host variables are allowed to be declared in host structures.
4.
LOB host variables are not allowed in host structure arrays. LOB locators should be used instead.
5.
LOB host variables declared in structure arrays cannot be used as standalone host variables.
6.
SQLTYPE, BLOB, CLOB, DBCLOB can be in mixed case.
7.
SQLTYPE must be between positions 44 to 80 for fixed-form declarations.
8.
When a LOB is declared as a stand-alone host variable, position 24 must contain the character 'S' and position 25 must be blank for fixed-form declarations.
9.
The stand-alone field indicator S in position 24 for fixed-form declarations should be omitted when a
LOB is declared in a host structure.
10.
LOB host variables cannot be initialized.
LOB locators in ILE RPG applications that use SQL:
BLOB, CLOB, and DBCLOB locators have similar syntax. Here is an example of a BLOB locator.
Example: BLOB locator
v The following declaration in free-form:
DCL-S MYBLOB SQLTYPE(BLOB_LOCATOR); results in the following generation:
DCL-S MYBLOB UNS(10); v The following declaration in fixed-form:
D MYBLOB S SQLTYPE(BLOB_LOCATOR) results in the following generation:
D MYBLOB S 10U
Notes:
1.
LOB locators are allowed to be declared in host structures.
2.
SQLTYPE, BLOB_LOCATOR, CLOB_LOCATOR, DBCLOB_LOCATOR can be in mixed case.
Embedded SQL programming
107
3.
SQLTYPE must be between positions 44 to 80 for fixed-form declarations.
4.
When a LOB locator is declared as a standalone host variable, position 24 must contain the character
'S' and position 25 must be blank for fixed-form declarations.
5.
The standalone field indicator S in position 24 for fixed-form declarations should be omitted when a
LOB locator is declared in a host structure.
6.
LOB locators cannot be initialized.
LOB file reference variables in ILE RPG applications that use SQL:
Here is an example of a CLOB file reference variable in ILE RPG. BLOB and DBCLOB file reference variables have similar syntax.
CLOB file reference example
v The following declaration in free-form:
DCL-S MY_FILE SQLTYPE(CLOB_FILE); results in the generation of the following structure:
DCL-DS MY_FILE;
MY_FILE_NL UNS(10);
MY_FILE_DL UNS(10);
MY_FILE_FO UNS(10);
MY_FILE_NAME CHAR(255);
END-DS MY_FILE; v The following declaration in fixed-form:
D MY_FILE S SQLTYPE(CLOB_FILE) results in the generation of the following structure:
D MY_FILE
D MY_FILE_NL
D MY_FILE_DL
D MY_FILE_FO
D MY_FILE_NAME
DS
10U
10U
10U
255A
Notes:
1.
LOB file reference variables are allowed to be declared in host structures.
2.
SQLTYPE, BLOB_FILE, CLOB_FILE, DBCLOB_FILE can be in mixed case.
3.
SQLTYPE must be between positions 44 to 80 for fixed-form declarations.
4.
When a LOB file reference is declared as a standalone host variable, position 24 must contain the character 'S' and position 25 must be blank for fixed-form declarations.
5.
The standalone field indicator 'S' in position 24 for fixed-form declarations should be omitted when a
LOB file reference variable is declared in a host structure.
6.
LOB file reference variables cannot be initialized.
The pre-compiler will generate declarations for the following file option constants. You can use these constants to set the xxx_FO variable when you use file reference host variables.
v SQFRD (2) v SQFCRT (8) v SQFOVR (16) v SQFAPP (32)
Related reference
:
LOB file reference variables
108
IBM i: Embedded SQL programming
Declaring XML host variables in ILE RPG applications that use SQL:
ILE RPG does not have variables that correspond to the SQL data type for XML.
To create host variables that can be used with this data type, use the SQLTYPE keyword. The SQL precompiler replaces this declaration with an ILE RPG language structure in the output source member.
XML declarations can be either standalone or within a data structure.
XML host variables in ILE RPG applications that use SQL
Here are some examples of XML host variables in ILE RPG applications.
XML AS CLOB example
v The following declaration in free-form:
DCL-S MYXMLCLOB SQLTYPE(XML_CLOB:3000); results in the generation of the following structure:
DCL-DS MYXMLCLOB;
MYXMLCLOB_LEN UNS(10);
MYXMLCLOB_DATA CHAR(3000);
END-DS MYXMLCLOB; v The following declaration in fixed-form:
D MYXMLCLOB S SQLTYPE(XML_CLOB:3000) results in the generation of the following structure:
D MYXMLCLOB
D MYXMLCLOB_LEN
D MYXMLCLOB_DATA
DS
10U
3000A
XML AS DBCLOB example
v The following declaration in free-form:
DCL-S MYXMLDBCLOB SQLTYPE(XML_DBCLOB:400); results in the generation of the following structure:
DCL-DS MYXMLDBCLOB;
MYXMLDBCLOB_LEN UNS(10);
MYXMLDBCLOB_DATA UCS2(400) CCSID(13488);
END-DS MYXMLDBCLOB; v The following declaration in fixed-form:
D MYXMLDBCLOB S SQLTYPE(XML_DBCLOB:400) results in the generation of the following structure:
D MYXMLDBCLOB
D MYXMLDBCLOB_LEN
D MYXMLDBCLOB_DATA
DS
10U
400C
XML AS BLOB example
v The following declaration in free-form:
DCL-S MYXMLBLOB SQLTYPE(XML_BLOB:780); results in the generation of the following structure:
DCL-DS MYXMLBLOB;
MYXMLBLOB_LEN UNS(10);
MYXMLBLOB_DATA CHAR(780) CCSID(*HEX);
END-DS MYXMLBLOB; v The following declaration in fixed-form:
D MYXMLBLOB S SQLTYPE(XML_BLOB:780)
Embedded SQL programming
109
results in the generation of the following structure:
D MYXMLBLOB
D MYXMLBLOB_LEN
D MYXMLBLOB_DATA
DS
10U
780A CCSID(*HEX)
Notes:
1.
For XML_BLOB and XML_CLOB, 1 ≤ lob-length ≤ 16 773 100.
2.
For XML_DBCLOB, 1≤ lob-length ≤ 8 386 550.
3.
XML host variables are allowed to be declared in host structures.
4.
XML host variables are not allowed in host structure arrays. XML locators should be used instead.
5.
XML host variables declared in structure arrays cannot be used as standalone host variables.
6.
SQLTYPE, XML_BLOB, XML_CLOB, XML_DBCLOB can be in mixed case.
7.
SQLTYPE must be between positions 44 to 80 for fixed-form declarations.
8.
The CCSID value for an XML host variable can be explicitly set by the DECLARE VARIABLE statement. Otherwise, the value specified by the SQL_XML_DATA_CCSID QAQQINI option will be used. The default for this QAQQINI option is CCSID 1208.
9.
When XML is declared as a standalone host variable, position 24 must contain the character 'S' and position 25 must be blank for fixed-form declarations.
10.
The stand-alone field indicator S in position 24 for fixed-form declarations should be omitted when
XML is declared in a host structure.
11.
XML host variables cannot be initialized.
XML locators in ILE RPG applications that use SQL
Here is an example of an XML locator.
XML locator example
v The following declaration in free-form:
DCL-S MYXMLLOC SQLTYPE(XML_LOCATOR); results in the following generation:
DCL-S MYXMLLOC UNS(10); v The following declaration in fixed-form:
D MYXMLLOC S SQLTYPE(XML_LOCATOR) results in the following generation:
D MYXMLLOC S 10U
Notes:
1.
XML locators are allowed to be declared in host structures.
2.
SQLTYPE, XML_LOCATOR can be in mixed case.
3.
SQLTYPE must be between positions 44 to 80 for fixed-form declarations.
4.
When an XML locator is declared as a standalone host variable, position 24 must contain the character
'S' and position 25 must be blank for fixed-form declarations.
5.
The standalone field indicator S in position 24 for fixed-form declarations should be omitted when an
XML locator is declared in a host structure.
6.
XML locators cannot be initialized.
XML file reference variables in ILE RPG applications that use SQL
Here is an example of a XML file reference variable in ILE RPG.
110
IBM i: Embedded SQL programming
XML file reference example
v
The following declaration in free-form:
DCL-S MY_XMLFILE SQLTYPE(XML_CLOB_FILE); results in the generation of the following structure:
DCL-DS MY_XMLFILE;
MY_XMLFILE_NL UNS(10);
MY_XMLFILE_DL UNS(10);
MY_XMLFILE_FO UNS(10);
MY_XMLFILE_NAME CHAR(255);
END-DS MY_XMLFILE; v The following declaration in fixed-form:
D MY_XMLFILE S SQLTYPE(XML_CLOB_FILE) results in the generation of the following structure:
D MY_XMLFILE
D MY_XMLFILE_NL
D MY_XMLFILE_DL
D MY_XMLFILE_FO
D MY_XMLFILE_NAME
DS
10U
10U
10U
255A
XML_BLOB_FILE and XML_DBCLOB_FILE file reference variables have similar syntax.
Notes:
1.
XML file reference variables are allowed to be declared in host structures.
2.
SQLTYPE, XML_BLOB_FILE, XML_CLOB_FILE, XML_DBCLOB_FILE can be in mixed case.
3.
SQLTYPE must be between positions 44 to 80 for fixed-form declarations.
4.
When an XML file reference is declared as a standalone host variable, position 24 must contain the character 'S' and position 25 must be blank for fixed-form declarations.
5.
The standalone field indicator 'S' in position 24 for fixed-form declarations should be omitted when an
XML file reference variable is declared in a host structure.
6.
XML file reference variables cannot be initialized.
The precompiler will generate declarations for the following file option constants. You can use these constants to set the xxx_FO variable when you use file reference host variables.
v SQFRD (2) v SQFCRT (8) v SQFOVR (16) v
SQFAPP (32)
Declaring ROWID variables in ILE RPG applications that use SQL:
ILE RPG does not have a variable that corresponds to the SQL data type ROWID.
To create host variables that can be used with this data type, use the SQLTYPE keyword. The SQL precompiler replaces this declaration with an ILE RPG language declaration in the output source member.
ROWID declarations can be either standalone or within a data structure.
ROWID example
v The following declaration in free-form:
DCL-S MY_ROWID SQLTYPE(ROWID); results in the following generation:
DCL_S MY_ROWID VARCHAR(40) CCSID(*HEX); v The following declaration in fixed-form:
Embedded SQL programming
111
D MY_ROWID S SQLTYPE(ROWID) results in the following generation:
D MY_ROWID S 40A VARYING CCSID(*HEX)
Notes:
1.
SQLTYPE, ROWID can be in mixed case.
2.
ROWID host variables are allowed to be declared in host structures.
3.
SQLTYPE must be between positions 44 and 80 for fixed-form declarations.
4.
When a ROWID is declared as a standalone host variable, position 24 must contain the character 'S' and position 25 must be blank for fixed-form declarations.
5.
The standalone field indicator 'S' in position 24 for fixed-form declarations should be omitted when a
ROWID is declared in a host structure.
6.
ROWID host variables cannot be initialized.
Declaring result set locator variables in ILE RPG applications that use SQL:
ILE RPG does not have a variable that corresponds to the SQL result set locator data type.
To create host variables that can be used with this data type, use the SQLTYPE keyword. The SQL precompiler replaces this declaration with an ILE RPG language declaration in the output source member.
Result set locator declarations can be either standalone or within a data structure.
Result set locator example
v The following declaration in free-form:
DCL-S RS_LOC1 SQLTYPE(RESULT_SET_LOCATOR); results in the following generation:
DCL-S RS_LOC1 INT(20); v The following declaration in fixed-form:
D RS_LOC1 S SQLTYPE(RESULT_SET_LOCATOR) results in the following generation:
D RS_LOC1 S 20I 0
Notes:
1.
SQLTYPE, RESULT_SET_LOCATOR can be in mixed case.
2.
Result set locator host variables are allowed to be declared in host structures.
3.
SQLTYPE must be between positions 44 and 80 for fixed-form declarations.
4.
When a result set locator is declared as a standalone host variable, position 24 must contain the character 'S' and position 25 must be blank for fixed-form declarations.
5.
The standalone field indicator 'S' in position 24 for fixed-form declarations should be omitted when a result set locator is declared in a host structure.
6.
Result set locator host variables cannot be initialized.
Using host structures in ILE RPG applications that use SQL
The ILE RPG data structure name can be used as a host structure name. The use of the data structure name in an SQL statement implies the specification of the list of subfield names that make up the data structure.
When a data structure contains one or more unnamed subfields, the data structure name cannot be used as a host structure in an SQL statement. The named subfields can be used as host variables.
The following must be considered when using a data structure as a host structure name:
112
IBM i: Embedded SQL programming
v All subfields must be valid host variable declarations.
v
All subfields must have a name.
v No subfield can be defined with the DIM or OCCUR keywords.
Any subfields within a data structure which are defined out of order or that overlap earlier bytes in the data structure will be skipped by the precompiler. This includes bytes that were skipped for alignment or positioning. For example, in the following structure declaration the FIRSTNAME subfield will be skipped since it is defined to use storage prior to the LASTNAME subfield.
DCL-DS PEMPL;
LASTNAME CHAR(10) POS(11);
FIRSTNAME CHAR(10) POS(1);
END-DS;
In the following example, BIGCHR is an ILE data structure without subfields. SQL treats any references to BIGCHR as a character string with a length of 642.
DBIGCHR DS 642
In the next example, PEMPL is the name of the host structure consisting of the subfields EMPNO,
FIRSTN, MIDINT, LASTNA, and DEPTNO. A reference to PEMPL uses the subfields. For example, the first column of CORPDATA.EMPLOYEE is placed in EMPNO, the second column is placed in FIRSTN, and so on.
DPEMPL
D EMPNO
D FIRSTN
D MIDINT
D LASTNA
D DEPTNO
DS
01
07
19
20
35
06A
18A
19A
34A
37A
...
C MOVE
...
C/EXEC SQL
C+ SELECT * INTO :PEMPL
C+ FROM CORPDATA.EMPLOYEE
C+ WHERE EMPNO = :EMPNO
C/END-EXEC
’000220’ EMPNO
When writing an SQL statement, references to subfields that are not in a QUALIFIED data structure can be qualified. Use the name of the data structure, followed by a period and the name of the subfield. For example, PEMPL.MIDINT is the same as specifying only MIDINT. If the data structure has the
QUALIFIED keyword, then the subfield must be referenced using the data structure name to qualify the subfield name.
In this example, there are two data structures, one QUALIFIED and one not QUALIFIED, that contain the same subfield names:
Dfststruct
D sub1
D sub2
D sub3
D sub4
DS
4B 0
9B 0
20I 0
9B 0
DS QUALIFIED Dsecstruct
D sub1
D sub2
D sub3
D myvar
D sub5
D myvar S
4A
12A
20I 0
5A
20A
10I 0
Embedded SQL programming
113
Referencing secstruct.sub1 as a host variable will be a character variable with a length of 4.
sub1 as a host variable will have an SQL data type of small integer. It picks up its attributes from the data structure that is not QUALIFIED.
A host variable reference to myvar will use the standalone declaration to pick up the data type of integer.
If you use secstruct.myvar, the character variable in the QUALIFIED structure will be used.
You cannot refer to sub5 without qualifying it with secstruct because it is in a QUALIFIED data structure.
The precompiler will recognize a host structure defined using the LIKEDS keyword. However, the SQL syntax for a host variable only allows using a single level of qualification in an SQL statement. This means that if a data structure DS has a subfield S1 which is defined like a data structure with a subfield
S2, an SQL statement cannot refer to S2 using the fully qualified host variable name of DS.S1.S2. If you use S1.S2 as the host variable reference, the precompiler will recognize it as DS.S1.S2. The following additional restrictions apply: v The top level structure, DS, cannot be an array.
v S1.S2 must be unique. That is, there must be no other valid names in the program ending with S1.S2, such as a structure S1 with a subfield S1.S2, or a structure DS3 with a subfield DS3.S0.S1.S2.
Example
DCL-DS CustomerInfo QUALIFIED;
Name CHAR(20);
Address CHAR(50);
END-DS;
DCL-DS ProductInfo QUALIFIED;
Number CHAR(5);
Description CHAR(20);
Cost PACKED(9:2);
END-DS;
DCL-DS SalesTransaction QUALIFIED;
Buyer LIKEDS(CustomerInfo);
Seller LIKEDS(CustomerInfo);
NumProducts INT(10);
Product LIKEDS(ProductInfo) DIM(10);
END-DS;
EXEC SQL
SELECT * INTO :CustomerInfo.Name, :Buyer.Name FROM MYTABLE;
CustomerInfo.Name will be recognized as a reference to the QUALIFIED structure's variable. Buyer.Name will be defined as SalesTransaction.Buyer.Name.
You cannot use SalesTransaction.Buyer.Name in an SQL statement because only one level of qualification is allowed in SQL syntax. You cannot use Product.Cost in an SQL statement because cost is in a dimensioned array.
If there is a SalesTransaction2 defined like SalesTransaction, then the subfields that are structures cannot be used in SQL statements. Because only one level of qualification is supported by SQL, a reference to
Buyer.Name is ambiguous.
Using host structure arrays in ILE RPG applications that use SQL
A host structure array is defined as an occurrence data structure or a data structure with the keyword
DIM coded. Both types of data structures can be used on the SQL FETCH or INSERT statement when processing multiple rows.
114
IBM i: Embedded SQL programming
The following list of items must be considered when using a data structure with multiple row blocking support.
v
All subfields must be valid host variables.
v All subfields must be contiguous. The first FROM position must be 1 and there cannot be overlaps in the TO and FROM positions.
v No subfields using the POS or OVERLAY keywords can be included in the data structure.
v If the date and time format and separator of date and time subfields within the host structure are not the same as the DATFMT, DATSEP, TIMFMT, and TIMSEP parameters on the CRTSQLRPGI command
(or in the SET OPTION statement), then the host structure array is not usable.
For all statements, other than the blocked FETCH and blocked INSERT, if an occurrence data structure is used, the current occurrence is used. For the blocked FETCH and blocked INSERT, the occurrence is set to 1.
The following example uses a host structure array called DEPARTMENT and a blocked FETCH statement to retrieve 10 rows from the DEPARTMENT table.
DDEPARTMENT
D DEPTNO
D DEPTNM
D MGRNO
D ADMRD
DS
01
04
33
39
03A
32A
38A
41A
OCCURS(10)
DIND_ARRAY
D INDS
...
C/EXEC SQL
DS
C+ DECLARE C1 CURSOR FOR
C+ SELECT *
C+
FROM
CORPDATA.DEPARTMENT
C/END-EXEC
...
OCCURS(10)
5I 0 DIM(4)
C/EXEC SQL
C+ FETCH C1 FOR 10 ROWS
C+ INTO :DEPARTMENT:IND_ARRAY
C/END-EXEC
Blocked FETCH and blocked INSERT are the only SQL statements that allow a data structure with the
DIM keyword. A host variable reference with a subscript like MyStructure(index).Mysubfield is not supported by SQL.
Example
Dfststruct
D sub1
D sub2
D sub3
D sub4
DS
4B 0
9B 0
20I 0
9B 0
C/EXEC SQL
C+ FETCH C1 FOR 10 ROWS INTO :fststruct
C/END-EXEC
DIM(10) QUALIFIED
Using external file descriptions in ILE RPG applications that use SQL
Field definitions for externally described files, including renaming of fields, are recognized by the SQL precompiler. The external definition form of the data structure can be used to obtain a copy of the column names to be used as host variables.
How date and time field definition are retrieved and processed by the SQL precompiler depends on whether *NOCVTDT or *CVTDT is specified on the OPTION parameter of the CRTSQLRPGI command.
Embedded SQL programming
115
If *NOCVTDT is specified, then date and time field definitions are retrieved including the format and separator. If *CVTDT is specified, then the format and separator are ignored when date and time field definitions are retrieved, and the precompiler assumes that the variable declarations are date/time host variables in character format. *CVTDT is a compatibility option for the ILE RPG precompiler.
If the GRAPHIC or VARGRAPHIC column has a UCS-2 CCSID, the generated host variable will have the
UCS-2 CCSID assigned to it. If the GRAPHIC or VARGRAPHIC column has a UTF-16 CCSID, the generated host variable will have the UTF-16 CCSID assigned to it.
|
| CLOB, BLOB, and DBCLOB columns in the external file are ignored. No host variable definition will be generated in the host structure for these types.
In the following example, the sample table DEPARTMENT is used as a file in an ILE RPG program. The
SQL precompiler retrieves the field (column) definitions for DEPARTMENT for use as host variables.
FDEPARTMENTIP E DISK RENAME(ORIGREC:DEPTREC)
Note:
Code an F-spec for a file in your ILE RPG program only if you use ILE RPG statements to do I/O operations to the file. If you use only SQL statements to do I/O operations to the file, you can include the external definition of the file (table) by using an external data structure.
In the following example, the sample table is specified as an external data structure. The SQL precompiler retrieves the field (column) definitions as subfields of the data structure. Subfield names can be used as host variable names, and the data structure name TDEPT can be used as a host structure name. The example shows that the field names can be renamed if required by the program.
DTDEPT
D DEPTN
D ADMRD
E DS
E
E
EXTNAME(DEPARTMENT)
EXTFLD(DEPTNAME)
EXTFLD(ADMRDEPT)
External file description considerations for host structure arrays in ILE RPG applications that use SQL
For device files, if INDARA was not specified and the file contains indicators, the declaration is not used as a host structure array. The indicator area is included in the structure that is generated and would cause the storage to be separated.
If OPTION(*NOCVTDT) is specified and the date and time format and separator of date and time field definitions within the file are not the same as the DATFMT, DATSEP, TIMFMT, and TIMSEP parameters on the CRTSQLRPGI command, then the host structure array is not usable.
In the following example, the DEPARTMENT table is included in the ILE RPG program and used to declare a host structure array. A blocked FETCH statement is then used to retrieve 10 rows into the host structure array.
DDEPARTMENT E DS OCCURS(10)
C/EXEC SQL
C+ DECLARE C1 CURSOR FOR
C+
C+
SELECT *
C/END-EXEC
FROM CORPDATA.DEPARTMENT
...
C/EXEC SQL
C+ FETCH C1 FOR 10 ROWS
C+
C/END-EXEC
INTO :DEPARTMENT
116
IBM i: Embedded SQL programming
|
|
|
|
|
|
|
Determining equivalent SQL and ILE RPG data types
The precompiler determines the base SQLTYPE and SQLLEN of host variables according to this table. If a host variable appears with an indicator variable, the SQLTYPE is the base SQLTYPE plus one.
Table 9. ILE RPG declarations mapped to typical SQL data types
RPG data type
Data structure
(without subfields)
RPG coding
Free-form:
v DCL-DS name LEN(n)
END-DS;
SQLTYPE of host variable
452
Zoned data
Packed data
Fixed-form:
v
Length = n where n ≤
32766.
Free-form:
v ZONED(p:s)
Fixed-form:
v Defined on Definition specification as subfield with data type S or blank.
v Defined on Definition specification with data type S.
v Defined on Input specification with data type S or blank.
Free-form:
v PACKED(p:s)
Fixed-form:
v Defined on Definition specification with decimal positions (pos 69-70) not blank.
v Defined on Definition specification subfield with data type P.
v
Defined on Definition specification with data type P or blank.
v Defined on Input specification with data type P.
488
484
SQLLEN of host variable
n p in byte 1, s in byte 2 p in byte 1, s in byte 2
SQL data type
CHAR(n)
NUMERIC(p, s) where p is the number of digits and s is the number of decimal places
DECIMAL(p, s) where p is the number of digits and s is the number of decimal places
Embedded SQL programming
117
|
|
|
|
|
|
Table 9. ILE RPG declarations mapped to typical SQL data types (continued)
RPG data type RPG coding SQLTYPE of host variable
500 2-byte binary with zero decimal positions
Free-form:
v BINDEC(digits) where 1 <= digits <= 4
SQLLEN of host variable
2
4-byte binary with zero decimal positions
2-byte integer
Fixed-form:
v Defined on Definition specification as subfield with from and to positions and data type B and byte length 2.
v Defined on Definition specification with data type B and digits from 1 to 4.
v Defined on Input specification with data type B and byte length 2
Free-form:
v BINDEC(digits)
496 where 5 <= digits <= 9
Fixed-form:
v
Defined on Definition specification as subfield with from and to positions and data type B and byte length 4.
v Defined on Definition specification with data type B and digits from 5 to 9.
v Defined on Input specification with data type B and byte length 4.
Free-form:
v INT(5)
500
Fixed-form:
v Defined on Definition specification as subfield with from and to positions and data type I and byte length 2.
v Defined on Definition specification with data type I and digits 5.
v
Defined on Input specification with data type I and byte length 2.
4
2
SQL data type
SMALLINT
INTEGER
SMALLINT
118
IBM i: Embedded SQL programming
|
|
|
|
|
|
|
|
|
|
Table 9. ILE RPG declarations mapped to typical SQL data types (continued)
RPG data type
4-byte integer
8-byte integer short float long float
Character
RPG coding SQLTYPE of host variable
496
Free-form:
v INT(10)
Fixed-form:
v Defined on Definition specification as subfield with from and to positions and data type I and byte length 4.
v Defined on Definition specification with data type I and digits 10.
v Defined on Input specification with data type I and byte length 4.
Free-form:
v INT(20)
492
Fixed-form:
v Defined on Definition specification as subfield with from and to positions and data type I and byte length 8.
v Defined on Definition specification with data type I and digits 20.
v Defined on Input specification with data type I and byte length 8.
Free-form:
v FLOAT(4)
480
Fixed-form:
v Data type = F, length = 4.
Free-form:
v FLOAT(8)
Fixed-form:
v Data type = F, length = 8.
Free-form:
v CHAR(n)
480
452
SQLLEN of host variable
4
8
4
8 n
Fixed-form:
v Data type = A or blank, decimal positions blank, length between 1 and
32766.
SQL data type
INTEGER
BIGINT
FLOAT (single precision)
FLOAT (double precision)
CHAR (n) where n is the length
Embedded SQL programming
119
|
|
|
|
|
|
|
|
Table 9. ILE RPG declarations mapped to typical SQL data types (continued)
RPG data type
Character varying length greater than
254
Character varying length between 1 and 254
RPG coding
Free-form:
v VARCHAR(n)
Fixed-form:
v Data type = A or blank, decimal positions blank,
VARYING keyword on
Definition specification or format *VAR on Input specification.
Free-form:
v VARCHAR(n)
SQLTYPE of host variable
448
456
SQLLEN of host variable
n n graphic
Fixed-form:
v Data type = A or blank, decimal positions blank,
VARYING keyword on
Definition specification or format *VAR on Input specification.
Free-form:
v GRAPH(n)
468 m varying graphic
Fixed-form:
v Defined on Definition specification as subfield with from and to positions and data type G and byte-length b.
v Defined on Definition specification with data type G and length n.
v Defined on Input specification with data type G and byte-length b
Free-form:
v VARGRAPH(n)
464
Fixed-form:
v Defined on Definition specification as subfield with from and to positions and data type G and byte-length b and
VARYING keyword.
v Defined on Definition specification with data type G and length n and
VARYING keyword.
v Defined on Input specification with data type G and byte-length b and format *VAR.
m
SQL data type
VARCHAR (n) where n is the length
VARCHAR (n) where n is the length
GRAPHIC(m) where m = n or m = b/2
VARGRAPHIC(m) where m = n or m = (b-2)/2
120
IBM i: Embedded SQL programming
|
|
|
|
|
|
|
Table 9. ILE RPG declarations mapped to typical SQL data types (continued)
RPG data type
UCS-2 varying UCS-2
Date
RPG coding SQLTYPE of host variable
468
Free-form:
v UCS2(n)
Fixed-form:
v Defined on Definition specification as subfield with from and to positions and data type C and byte-length b.
v Defined on Definition specification with data type C and length n.
v Defined on Input specification with data type C and byte-length b.
Free-form:
v VARUCS2(n)
464
Fixed-form:
v Defined on Definition specification as subfield with from and to positions and data type C and byte-length b and
VARYING keyword.
v Defined on Definition specification with data type C and length n and
VARYING keyword.
v Defined on Input specification with data type C and byte-length b and format *VAR.
Free-form:
v DATE v DATE(fs)
384
Fixed-form:
v Defined on Definition specification with data type D, format f and separator s from DATFMT keyword.
v Defined on Input specification with data type D and format in pos
31-34, separator in pos 35.
SQLLEN of host variable
m m
SQL data type
GRAPHIC(m) with CCSID
13488 or CCSID 1200 where m = n or m = b/2
VARGRAPHIC(m) with
CCSID 13488 or CCSID
1200 where m = n or m = b/2
DATE DATFMT(f)
DATSEP(s)
1
Embedded SQL programming
121
|
|
|| || |
|
|
|
|
|
Table 9. ILE RPG declarations mapped to typical SQL data types (continued)
RPG data type
Time
RPG coding SQLTYPE of host variable
388
SQLLEN of host variable
Timestamp
Free-form:
v TIME v TIME(fs)
Fixed-form:
v Defined on Definition specification with data type T, format f and separator s from TIMFMT keyword.
v Defined on Input specification with data type T and format in pos
31-34, separator in pos 35.
Free-form:
v TIMESTAMP(n)
392 19 when n = 0, otherwise 20+n
SQL data type
TIME TIMFMT(f)
TIMSEP(s)
1
TIMESTAMP(n)
Fixed-form:
v Data type Z.
1
SQL creates the date/time subfield using the DATE/TIME format specified on the CRTSQLRPGI command. The conversion to the host variable DATE/TIME format occurs when the mapping is done between the host variables and the SQL-generated subfields.
|
|
|
|
|
|
The following table can be used to determine the RPG data type that is equivalent to a given SQL data type.
Table 10. SQL data types mapped to typical RPG declarations
SQL data type
SMALLINT
RPG data type
Free-form:
v INT(5) v BINDEC(n) where 1 <= n <= 4
INTEGER
Fixed-form:
v Definition specification. I in position 40, length must be 5 and 0 in position 42.
v Definition specification. B in position 40, length must be ≤ 4 and
0 in position 42.
Free-form:
v
INT(10) v BINDEC(n) where 5 <= n <= 9
Fixed-form:
v Definition specification. I in position 40, length must be 10 and
0 in position 42.
v Definition specification. B in position 40, length must be ≤ 9 and
≥ 5 and 0 in position 42.
Notes
122
IBM i: Embedded SQL programming
|
|
|
|
|
|
|
|
|
|
|
|
Table 10. SQL data types mapped to typical RPG declarations (continued)
SQL data type
BIGINT
RPG data type
Free-form:
v INT(20)
DECIMAL
NUMERIC
DECFLOAT
FLOAT (single precision)
Fixed-form:
v Definition specification. I in position 40, length must be 20 and
0 in position 42.
Free-form:
v PACKED(p:s)
Fixed-form:
v Definition specification. P in position 40 or blank in position 40 for a non-subfield, 0 through 63 in position 41,42.
v Defined as numeric on non-definition specification.
Free-form:
v ZONED(p:s)
Fixed-form:
v Definition specification. S in position 40 or blank in position 40 for a subfield, 0 through 63 in position 41,42.
Not supported
Free-form:
v FLOAT(4)
FLOAT (double precision)
CHAR(n)
Notes
Maximum length of 32 (precision 63) and maximum scale of 63.
Maximum length of 63 (precision 63) and maximum scale of 63.
Not supported
Fixed-form:
v Definition specification. F in position 40, length must be 4.
Free-form:
v FLOAT(8)
Fixed-form:
v
Definition specification. F in position 40, length must be 8.
Free-form:
v CHAR(n)
Fixed-form:
v Definition specification. A or blank in positions 40 and blanks in position 41,42.
v Input field defined without decimal places.
v
Calculation result field defined without decimal places.
n can be from 1 to 32766.
Embedded SQL programming
123
|
|
|
|
|
|
|
|
|
|
Table 10. SQL data types mapped to typical RPG declarations (continued)
SQL data type
CHAR(n)
RPG data type
Free-form:
v DCL-DS name LEN(n) END-DS;
VARCHAR(n)
CLOB
Fixed-form:
v Data structure name with no subfields in the data structure.
Free-form:
v VARCHAR(n)
Fixed-form:
v
Definition specification. A or blank in position 40 and VARYING in positions 44-80.
Not supported
GRAPHIC(n)
VARGRAPHIC(n)
DBCLOB
BINARY
VARBINARY
BLOB
DATE
Notes
n can be from 1 to 32766.
n can be from 1 to 32740.
Use SQLTYPE keyword to declare a
CLOB.
n can be 1 to 16383.
Free-form:
v GRAPH(n)
Fixed-form:
v Definition specification. G in position 40.
v Input field defined with G in position 36.
Free-form:
v VARGRAPH(n)
Fixed-form:
v Definition specification. G in position 40 and VARYING in positions 44-80.
Not supported n can be from 1 to 16370.
Not supported
Not supported
Not supported
Free-form:
v DATE
Fixed-form:
v A character field v Definition specification with a D in position 40.
v
Input field defined with D in position 36.
Use SQLTYPE keyword to declare a
DBCLOB.
Use SQLTYPE keyword to declare a
BINARY.
Use SQLTYPE keyword to declare a
VARBINARY.
Use SQLTYPE keyword to declare a
BLOB.
If the format is *USA, *JIS, *EUR, or
*ISO, the length must be at least 10. If the format is *YMD, *DMY, or *MDY, the length must be at least 8. If the format is *JUL, the length must be at least 6.
124
IBM i: Embedded SQL programming
|
|
|
|
|
|
|
|
|
|
|
| ||
|
|
Table 10. SQL data types mapped to typical RPG declarations (continued)
SQL data type
TIME
RPG data type
Free-form:
v TIME
TIMESTAMP(n)
XML
Fixed-form:
v A character field v Definition specification with a T in position 40.
v Input field defined with T in position 36.
Free-form:
v
TIMESTAMP(n)
Fixed-form:
v A character field v Definition specification with a Z in position 40.
v Input field defined with Z in position 36.
Not supported
Notes
Length must be at least 6; to include seconds, length must be at least 8.
For a character field, the length must be at least 19; to include fractional seconds, the length can be 21 to 32. If less than 32, some fractional seconds will be truncated.
Use SQLTYPE keyword to declare an
XML.
DATALINK
ROWID
Not supported
Not supported
Result set locator Not supported
Use SQLTYPE keyword to declare a
ROWID.
Use SQLTYPE keyword to declare a result set locator.
Notes on ILE RPG variable declaration and usage
ILE RPG associates precision and scale with all numeric types.
ILE RPG defines numeric operations, assuming the data is in packed format. This means that operations involving binary variables include an implicit conversion to packed format before the operation is performed (and back to binary, if necessary). Data is aligned to the implied decimal point when SQL operations are performed.
Using indicator variables in ILE RPG applications that use SQL
An indicator variable is a binary field with length less than 5 (2 bytes).
An indicator array can be defined by declaring the variable element length of 4,0 and specifying the DIM on the definition specification.
Indicator variables are declared in the same way as host variables and the declarations of the two can be mixed in any way that seems appropriate to the programmer.
Related reference
:
References to variables
“Indicator variables in applications that use SQL” on page 4
An indicator variable is a halfword integer variable used to communicate additional information about its associated host variable.
Embedded SQL programming
125
Example: Using indicator variables in ILE RPG applications that use SQL
Here is an example of declaring indicator variables in ILE RPG.
Given the statement:
C/EXEC SQL FETCH CLS_CURSOR INTO :CLSCD,
C+ :DAY :DAYIND,
C+
C+
C/END-EXEC
:BGN :BGNIND,
:END :ENDIND variables can be declared as follows:
D CLSCD
D DAY
D DAYIND
D BGN
D BGNIND
D END
D ENDIND
S
S
S
S
S
S
S
7
5I 0
5I 0
8A
5I 0
8
5I 0
Example: SQLDA for a multiple row-area fetch in ILE RPG applications that use SQL
Here is an example of the SQL descriptor area (SQLDA) for a multiple row-area fetch in ILE RPG.
C/EXEC SQL INCLUDE SQLDA
C/END-EXEC
DDEPARTMENT
D DEPTNO
DS
D DEPTNM
D MGRNO
D ADMRD
...
01
04
33
39
03A
32A
38A
41A
OCCURS(10)
C
C
C
DIND_ARRAY
D INDS
DS OCCURS(10)
5I 0 DIM(4)
...
C* setup number of sqlda entries and length of the sqlda eval eval eval sqld = 4 sqln = 4 sqldabc = 336
C
C
C*
C* setup the first entry in the sqlda
C*
C eval eval sqltype = 453 sqllen = 3 eval sql_var(1) = sqlvar
C
C
C*
C* setup the second entry in the sqlda
C*
C eval eval sqltype = 453 sqllen = 29 eval sql_var(2) = sqlvar
C
C
C
...
C*
C* setup the forth entry in the sqlda
C* eval eval eval sqltype = 453 sqllen = 3 sql_var(4) = sqlvar
...
C/EXEC SQL
C+ DECLARE C1 FOR
C+ SELECT *
C+
FROM
CORPDATA.DEPARTMENT
126
IBM i: Embedded SQL programming
C/END-EXEC
...
C/EXEC SQL
C+ FETCH C1 FOR 10 ROWS
C+
C+
USING DESCRIPTOR :SQLDA
INTO :DEPARTMENT:IND_ARRAY
C/END-EXEC
Example: Dynamic SQL in an ILE RPG application that uses SQL
Here is an example of using dynamic SQL in ILE RPG.
D**************************************************
D* Declare program variables.
*
D* STMT initialized to the
D* listed SQL statement.
*
*
D
D
D**************************************************
D EMPNUM S 6A
D NAME
D STMT
S
S
15A
500A INZ(’SELECT LASTNAME -
FROM CORPDATA.EMPLOYEE WHERE -
EMPNO = ?’)
...
C*************************************************************
C* Prepare STMT as initialized in declare section *
C*************************************************************
C/EXEC SQL
C+ PREPARE S1 FROM :STMT
C/END-EXEC
C*
C*************************************
C* Declare Cursor for STMT *
C*************************************
C/EXEC SQL
C+ DECLARE C1 CURSOR FOR S1
C/END-EXEC
C*
C*****************************************************
C* Assign employee number to use in select statement *
C*****************************************************
C eval EMPNUM = ’000110’
C**********************
C* Open Cursor *
C**********************
C/EXEC SQL
C+ OPEN C1 USING :EMPNUM
C/END-EXEC
C*
C***********************************************
C* Fetch record and put value of
C* LASTNAME into NAME
C***********************************************
C/EXEC SQL
C+ FETCH C1 INTO :NAME
C/END-EXEC
...
*
*
C********************************
C* Program processes NAME here *
C********************************
...
C******************
C* Close cursor *
Embedded SQL programming
127
C******************
C/EXEC SQL
C+ CLOSE C1
C/END-EXEC
Coding SQL statements in REXX applications
REXX procedures do not have to be preprocessed. At run time, the REXX interpreter passes statements that it does not understand to the current active command environment for processing.
The command environment can be changed to *EXECSQL to send all unknown statements to the database manager in two ways:
1.
CMDENV parameter on the STRREXPRC CL command
2.
address positional parameter on the ADDRESS REXX command
For more information about the STRREXPRC CL command or the ADDRESS REXX command, see the
REXX/400 Programmer's Guide topic and the REXX/400 Reference topic.
Note:
Related concepts
:
“Writing applications that use SQL” on page 2
You can create database applications in host languages that use DB2 for i SQL statements and functions.
Related reference
:
“Example programs: Using DB2 for i statements” on page 149
Here is a sample application that shows how to code SQL statements in each of the languages that DB2 for i supports.
“Example: SQL statements in REXX programs” on page 183
This example program is written in the REXX programming language.
Using the SQL communication area in REXX applications
The fields that make up the SQL communication area (SQLCA) are automatically included by the
SQL/REXX interface.
An INCLUDE SQLCA statement is not required and is not allowed. The SQLCODE and SQLSTATE fields of the SQLCA contain SQL return codes. These values are set by the database manager after each SQL statement is run. An application can check the SQLCODE or SQLSTATE value to determine whether the last SQL statement was successful.
The SQL/REXX interface uses the SQLCA in a manner consistent with the typical SQL usage. However, the SQL/REXX interface maintains the fields of the SQLCA in separate variables rather than in a contiguous data area. The variables that the SQL/REXX interface maintains for the SQLCA are defined as follows:
SQLCODE
The primary SQL return code.
SQLERRMC
Error and warning message tokens.
SQLERRP
Product code and, if there is an error, the name of the module that returned the error.
SQLERRD.
n
Six variables (n is a number between 1 and 6) containing diagnostic information.
128
IBM i: Embedded SQL programming
SQLWARN.
n
Eleven variables (n is a number between 0 and 10) containing warning flags.
SQLSTATE
The alternate SQL return code.
Related reference
:
SQL communication area
Using SQL descriptor areas in REXX applications
There are two types of SQL descriptor areas. One is defined with the ALLOCATE DESCRIPTOR statement. The other is defined using the SQL descriptor area (SQLDA) structure. Only the SQLDA form is discussed here. Allocated descriptors are not supported in REXX.
The following statements can use an SQLDA: v EXECUTE...USING DESCRIPTOR descriptor-name v FETCH...USING DESCRIPTOR descriptor-name v OPEN...USING DESCRIPTOR descriptor-name v CALL...USING DESCRIPTOR descriptor-name v DESCRIBE statement-name INTO descriptor-name v DESCRIBE TABLE host-variable INTO descriptor-name
Unlike the SQLCA, more than one SQLDA can be in a procedure, and an SQLDA can have any valid name.
Each SQLDA consists of a set of REXX variables with a common stem, where the name of the stem is the
descriptor-name from the appropriate SQL statements. This must be a simple stem; that is, the stem itself must not contain any periods. The SQL/REXX interface automatically provides the fields of the SQLDA for each unique descriptor name. An INCLUDE SQLDA statement is not required and is not allowed.
The SQL/REXX interface uses the SQLDA in a manner consistent with the typical SQL usage. However, the SQL/REXX interface maintains the fields of the SQLDA in separate variables rather than in a contiguous data area.
The following variables are returned to the application after a DESCRIBE, a DESCRIBE TABLE, or a
PREPARE INTO statement:
stem.n.SQLNAME
The name of the nth column in the result table.
The following variables must be provided by the application before an EXECUTE...USING
DESCRIPTOR, an OPEN...USING DESCRIPTOR, a CALL...USING DESCRIPTOR, or a
FETCH...USING DESCRIPTOR statement. They are returned to the application after a DESCRIBE, a DESCRIBE TABLE, or a PREPARE INTO statement:
stem.SQLD
Number of variable elements that the SQLDA actually contains.
stem.n.SQLTYPE
An integer representing the data type of the nth element (for example, the first element is in stem.1.SQLTYPE).
The following data types are not allowed:
400/401
NUL-terminated graphic string
Embedded SQL programming
129
404/405
BLOB host variable
408/409
CLOB host variable
412/413
DBCLOB host variable
460/461
NUL-terminated character string
476/477
PASCAL L-string
496/497
Large integer (where scale is greater than 0)
500/501
Small integer (where scale is greater than 0)
504/505
DISPLAY SIGN LEADING SEPARATE
904/905
ROWID
908/909
VARBINARY host variable
912/913
BINARY host variable
916/917
BLOB file reference variable
920/921
CLOB file reference variable
924/925
DBCLOB file reference variable
960/961
BLOB locator
964/965
CLOB locator
968/969
DBCLOB locator
972
Result set locator
988/989
XML host variable
996/997
Decimal floating point host variable
2452/2453
XML locator
stem.n.SQLLEN
If SQLTYPE does not indicate a DECIMAL or NUMERIC data type, the maximum length of the data contained in stem.n.SQLDATA.
130
IBM i: Embedded SQL programming
stem.n.SQLLEN.SQLPRECISION
If the data type is DECIMAL or NUMERIC, this contains the precision of the number.
stem.n.SQLLEN.SQLSCALE
If the type is DECIMAL or NUMERIC, this contains the scale of the number.
stem.n.SQLCCSID
The CCSID of the nth column of the data.
The following variables must be provided by the application before an EXECUTE...USING
DESCRIPTOR or an OPEN...USING DESCRIPTOR statement, and they are returned to the application after a FETCH...USING DESCRIPTOR statement. They are not used after a
DESCRIBE, a DESCRIBE TABLE, or a PREPARE INTO statement:
stem.n.SQLDATA
This contains the input value supplied by the application, or the output value fetched by SQL.
This value is converted to the attributes specified in SQLTYPE, SQLLEN, SQLPRECISION, and
SQLSCALE.
stem.n.SQLIND
If the input or output value is null, this is a negative number.
Related reference
:
SQL descriptor area
Embedding SQL statements in REXX applications
An SQL statement can be placed anywhere a REXX command can be placed.
Each SQL statement in a REXX procedure must begin with EXECSQL (in any combination of uppercase and lowercase letters), followed by either: v The SQL statement enclosed in single or double quotation marks, or v A REXX variable containing the statement. Note that a colon must not precede a REXX variable when it contains an SQL statement.
For example:
EXECSQL “COMMIT” is equivalent to: rexxvar = “COMMIT”
EXECSQL rexxvar
The command follows normal REXX rules. For example, it can optionally be followed by a semicolon (;) to allow a single line to contain more than one REXX statement. REXX also permits command names to be included within single quotation marks, for example:
’EXECSQL COMMIT’
The SQL/REXX interface supports the following SQL statements:
Embedded SQL programming
131
ALTER FUNCTION
ALTER PROCEDURE
ALTER SEQUENCE
ALTER TABLE
CALL
2
CLOSE
COMMENT
COMMIT
CREATE ALIAS
CREATE FUNCTION
CREATE INDEX
CREATE PROCEDURE
CREATE SCHEMA
CREATE SEQUENCE
CREATE TABLE
CREATE TRIGGER
CREATE TYPE
CREATE VIEW
DECLARE CURSOR
2
DECLARE GLOBAL TEMPORARY TABLE
DELETE
2
DESCRIBE
DESCRIBE TABLE
DROP
EXECUTE
EXECUTE IMMEDIATE
FETCH
1
GRANT
INSERT
1
LABEL
LOCK TABLE
OPEN
PREPARE
REFRESH TABLE
RELEASE SAVEPOINT
RENAME
REVOKE
ROLLBACK
SAVEPOINT
SET CURRENT DECFLOAT ROUNDING MODE
SET CURRENT IMPLICIT XMLPARSE OPTION
SET ENCRYPTION PASSWORD
SET OPTION
3
SET PATH
SET SCHEMA
SET TRANSACTION
2
SET variable
UPDATE
2
The following SQL statements are not supported by the SQL/REXX interface:
ALLOCATE CURSOR
ALLOCATE DESCRIPTOR
ASSOCIATE LOCATORS
BEGIN DECLARE SECTION
CONNECT
DEALLOCATE DESCRIPTOR
DECLARE PROCEDURE
DECLARE STATEMENT
DECLARE VARIABLE
DESCRIBE CURSOR
DESCRIBE INPUT
DESCRIBE PROCEDURE
DISCONNECT
END DECLARE SECTION
FREE LOCATOR
GET DESCRIPTOR
GET DIAGNOSTICS
HOLD LOCATOR
INCLUDE
MERGE
RELEASE
SELECT INTO
SET CONNECTION
SET CURRENT DEGREE
SET DESCRIPTOR
SET RESULT SETS
SET SESSION AUTHORIZATION
SIGNAL
VALUES INTO
WHENEVER
4
1.
The blocked form of this statement is not supported.
2.
These statements cannot be run directly if they contain host variables; they must be the object of a
PREPARE and then an EXECUTE.
3.
The SET OPTION statement can be used in a REXX procedure to change some of the processing options used for running SQL statements. These options include the commitment control level and date format. See the DB2 for i SQL reference topic for more information about the SET OPTION statement.
4.
See “Handling errors and warnings in REXX applications that use SQL” on page 133 for more
information.
Comments in REXX applications that use SQL
Neither SQL comments (--) nor REXX comments are allowed in strings representing SQL statements.
132
IBM i: Embedded SQL programming
Continuation of SQL statements in REXX applications that use SQL
The string containing an SQL statement can be split into several strings on several lines, separated by commas or concatenation operators, according to standard REXX usage.
Including code in REXX applications that use SQL
Unlike the other host languages, support is not provided for including externally defined statements.
Margins in REXX applications that use SQL
There are no special margin rules for the SQL/REXX interface.
Names in REXX applications that use SQL
Any valid REXX name not ending in a period (.) can be used for a host variable. The name must be 64 characters or less.
Variable names should not begin with the characters 'SQL', 'RDI', 'DSN', 'RXSQL', or 'QRW'.
Nulls in REXX applications that use SQL
Although the term null is used in both REXX and SQL, the term has different meanings in the two languages.
REXX has a null string (a string of length zero) and a null clause (a clause consisting only of blanks and comments). The SQL null value is a special value that is distinct from all non-null values and denotes the absence of a (non-null) value.
Statement labels in REXX applications that use SQL
REXX command statements can be labeled as usual.
Handling errors and warnings in REXX applications that use SQL
The WHENEVER statement is not supported by the SQL/REXX interface. You can use one of several substitutes, however.
Any of the following may be used instead: v A test of the REXX SQLCODE or SQLSTATE variables after each SQL statement to detect error and warning conditions issued by the database manager, but not for those issued by the SQL/REXX interface.
v A test of the REXX RC variable after each SQL statement to detect error and warning conditions. Each use of the EXECSQL command sets the RC variable to:
0
+10
-10
Statement completed successfully.
A SQL warning occurred.
An SQL error occurred
-100
An SQL/REXX interface error occurred.
This can be used to detect errors and warnings issued by either the database manager or by the
SQL/REXX interface.
v The SIGNAL ON ERROR and SIGNAL ON FAILURE facilities can be used to detect errors (negative
RC values), but not warnings.
Using host variables in REXX applications that use SQL
REXX does not provide for variable declarations.
LOB, XML, ROWID, binary, and result set locator host variables are not supported in REXX. New variables are recognized by their appearance in assignment statements. Therefore, there is no declare section, and the BEGIN DECLARE SECTION and END DECLARE SECTION statements are not supported.
Embedded SQL programming
133
All host variables within an SQL statement must be preceded by a colon (:).
The SQL/REXX interface performs substitution in compound variables before passing statements to the database manager. For example: a = 1 b = 2
EXECSQL ’OPEN c1 USING :x.a.b’ causes the contents of x.1.2 to be passed to SQL.
Determining data types of input host variables in REXX applications that use SQL
All data in REXX is in the form of strings.
The data type of input host variables (that is, host variables used in a 'USING host variable' clause in an
EXECUTE or OPEN statement) is inferred by the database manager at run time from the contents of the variable according to the table below.
These rules define either numeric, character, or graphic values. A numeric value can be used as input to a numeric column of any type. A character value can be used as input to a character column of any type, or to a date, time, or timestamp column. A graphic value can be used as input to a graphic column of any type.
Table 11. Determining data types of host variables in REXX
Host variable contents Assumed data type SQL type description SQL type code
496/497 INTEGER A number with neither decimal point nor exponent. It can have a leading plus or minus sign.
A number that includes a decimal point, but no exponent,
Signed integers
Packed decimal 484/485 DECIMAL(m,n) or a number that does not include a decimal point or an exponent and is greater than
2147483647 or smaller than -2147483647.
It can have a leading plus or minus sign. m is the total number of digits in the number. n is the number of digits to the left of the decimal point (if any).
A number that is in scientific or engineering notation (that is, followed immediately by an
'E' or 'e', an optional plus or minus sign, and a series of digits). It can have a leading plus or minus sign.
Floating point 480/481 DOUBLE PRECISION
134
IBM i: Embedded SQL programming
Table 11. Determining data types of host variables in REXX (continued)
Host variable contents
A string with leading and trailing single quotation marks (') or quotation marks ("), which has length n after removing the two delimiters,
Assumed data type
Varying-length character string
SQL type code
448/449
SQL type description
VARCHAR(n) or a string with a leading X or x followed by a single quotation mark (') or quotation mark ("), and a trailing single quotation mark (') or quotation mark ("). The string has a length of
2n after removing the X or x and the two delimiters. Each remaining pair of characters is the hexadecimal representation of a single character.
or a string of length n, which cannot be recognized as character, numeric, or graphic through other rules in this table
A string with a leading and trailing single quotation mark (') or quotation marks (") preceded by:
1 v A string that starts with a G, g, N, or n. This is followed by a single quotation mark or a quotation mark and a shift-out (x'0E') character. This is followed by n graphic characters, each 2 characters long. The string must end with a shift-in (X'0F') character and a single quotation mark or a quotation mark
(whichever the string started with).
v A string with a leading GX, Gx, gX, or gx, followed by a single quotation mark or a quotation mark and a shift-out (x'0E') character. This is followed by n graphic characters, each 2 characters long. The string must end with a shift-in (X'0F') character and a single quotation mark or a quotation mark
(whichever the string started with). The string has a length of 4n after removing the
GX and the delimiters. Each remaining group of 4 characters is the hexadecimal representation of a single graphic character.
Varying-length graphic string
464/465 VARGRAPHIC(n)
Undefined Variable Variable for which a value has not been assigned
None Data that is not valid was detected.
1
The byte immediately following the leading single quotation mark is a X'0E' shift-out character, and the byte immediately preceding the trailing single quotation mark is a X'0F' shift-in character.
The format of output host variables in REXX applications that use SQL
It is not necessary to determine the data type of an output host variable (that is, a host variable used in an
'INTO host variable' clause in a FETCH statement).
Output values are assigned to host variables as follows: v Character values are assigned without leading and trailing apostrophes.
Embedded SQL programming
135
v Graphic values are assigned without a leading G or apostrophe, without a trailing apostrophe, and without shift-out and shift-in characters.
v
Numeric values are translated into strings.
v Integer values do not retain any leading zeros. Negative values have a leading minus sign.
v Decimal values retain leading and trailing zeros according to their precision and scale. Negative values have a leading minus sign. Positive values do not have a leading plus sign.
v Floating-point values are in scientific notation, with one digit to the left of the decimal place. The 'E' is in uppercase.
Avoiding REXX conversion in REXX applications that use SQL
To guarantee that a string is not converted to a number or assumed to be of graphic type, strings should be enclosed in “'”. Enclosing the string in single quotation marks does not work.
For example: stringvar = ’100’ causes REXX to set the variable stringvar to the string of characters 100 (without the single quotation marks). This is evaluated by the SQL/REXX interface as the number 100, and it is passed to SQL as such.
On the other hand, stringvar = “’“100”’” causes REXX to set the variable stringvar to the string of characters '100' (with the single quotation marks). This is evaluated by the SQL/REXX interface as the string 100, and it is passed to SQL as such.
Using indicator variables in REXX applications that use SQL
An indicator variable is an integer.
Unlike other languages, a valid value must be specified in the host variable even if its associated indicator variable contains a negative value.
Related reference
:
References to variables
“Indicator variables in applications that use SQL” on page 4
An indicator variable is a halfword integer variable used to communicate additional information about its associated host variable.
Preparing and running a program with SQL statements
This topic describes some of the tasks for preparing and running an application program.
Related concepts
:
“Writing applications that use SQL” on page 2
You can create database applications in host languages that use DB2 for i SQL statements and functions.
Basic processes of the SQL precompiler
You must precompile and compile an application program containing embedded SQL statements before you can run it.
Note:
SQL statements in a REXX procedure are not precompiled and compiled.
Precompiling of such programs is done by the SQL precompiler. The SQL precompiler scans each statement of the application program source and does the following:
136
IBM i: Embedded SQL programming
v Looks for SQL statements and for the definition of host variable names. The variable names and definitions are used to verify the SQL statements. You can examine the listing after the SQL precompiler completes processing to see if any errors occurred.
v Verifies that each SQL statement is valid and free of syntax errors. The validation procedure supplies error messages in the output listing that help you correct any errors that occur.
v Validates the SQL statements using the description in the database. During the precompile, SQL statements are checked for valid table, column, and other object references. If a specified object does not exist or you are not authorized to it at the time of the precompile, complete validation will be done at run time. If an object does not exist at run time, an error occurs.
Notes:
1.
Overrides are processed when retrieving external definitions.
2.
You need some authority (at least *OBJOPR) to any tables or views referred to in the SQL statements in order to validate the SQL statements. The actual authority required to process any
SQL statement is checked at run time.
3.
When the RDB parameter is specified on the CRTSQLxxx commands, the precompiler accesses the specified relational database to obtain the table and view descriptions.
v Prepares each SQL statement for compilation in the host language. For most SQL statements, the SQL precompiler inserts a comment and a CALL statement to one of the SQL interface modules. For some
SQL statements (for example, DECLARE statements), the SQL precompiler produces no host language statement except a comment.
v Produces information about each precompiled SQL statement. The information is stored internally in a temporary source file member, where it is available for use during the bind process.
To get complete diagnostic information when you precompile, specify either of the following: v OPTION(*SOURCE *XREF) for CRTSQLxxx (where xxx=CBL, PLI, or RPG) v OPTION(*XREF) OUTPUT(*PRINT) for CRTSQLxxx (where xxx=CI, CPPI, CBLI, or RPGI)
Related concepts
:
Database programming
Database file management
DB2 for i5/OS SQL reference
Input to the SQL precompiler
Application programming statements and embedded SQL statements are the primary input to the SQL precompiler. The statements can be in a source member or, for any ILE precompile, in a source stream file.
In PL/I, C, and C++ source members, the SQL statements must use the margins that are specified in the
MARGINS parameter of the CRTSQLPLI, CRTSQLCI, and CRTSQLCPPI commands. The MARGINS parameter is ignored when you precompile from a source stream file.
The SQL precompiler assumes that the host language statements are syntactically correct. If the host language statements are not syntactically correct, the precompiler might not correctly identify SQL statements and host variable declarations. Literals and comments that are not accepted by the application language compiler can interfere with the precompiler source scanning process and cause errors.
You can use the SQL INCLUDE statement to embed secondary input from the file that is specified by the
INCFILE or INCDIR parameter of the CRTSQLxxx command. The SQL INCLUDE statement causes the specified member or source stream file to be read. The included source cannot contain other precompiler
INCLUDE statements, but can contain both application program and SQL statements.
When you precompile a source member, the INCFILE parameter is used to find the source that is specified in the SQL INCLUDE statement. When you precompile a source stream file, the INCDIR
Embedded SQL programming
137
parameter is used. If a relative path is specified in the INCLUDE statement, the precompiler first searches the current directory. If that file is not found, the name specified on the INCLUDE statement is appended to the INCDIR value. If that is not found, the precompiler searches the directory where the input source is found. If an absolute path is specified for the INCLUDE statement, the precompiler ignores the
INCDIR value. No suffixes are appended to the name specified on the INCLUDE statement.
If mixed DBCS constants are specified in the application program source, the source file must be a mixed
CCSID.
You can specify many of the precompiler command parameter values directly in the input source by using the SQL SET OPTION statement. These include options such as DATFMT, COMMIT, and
NAMING. By specifying them in the input source, you do not need to remember to specify them on the precompiler command.
Note:
If a value is provided for an option on both the precompile command and on the SET OPTION statement, the value from the SET OPTION statement is used.
The RPG preprocessor options (RPGPPOPT) parameter of the CRTSQLRPGI command has two options to call the RPG preprocessor. If *LVL1 or *LVL2 is specified, the RPG compiler will be called to preprocess the source before the SQL precompile is run. Preprocessing the SQL source will allow many compiler directives to be handled before the SQL precompile. The preprocessed source will be placed in file
QSQLPRE in QTEMP. This source will be used as the input for the SQL precompile. The CCSID used by the SQL precompile is the CCSID of QSQLPRE.
Related reference
:
SET OPTION
Create SQL ILE RPG Object (CRTSQLRPGI) command
Source file CCSIDs in the SQL precompiler
The SQL precompiler reads the source records by using the CCSID of the source file or source stream file.
When processing SQL INCLUDE statements, the include source is converted to the CCSID of the primary source if necessary. If the include source cannot be converted to the CCSID of the primary source, an error occurs.
The SQL precompiler processes SQL statements using the source CCSID. This affects variant characters the most. For example, the not sign (¬) is located at 'BA'X in CCSID 500. This means that if the CCSID of your source file is 500, SQL expects the not sign (¬) to be located at 'BA'X.
If the source file CCSID is 65535, SQL processes variant characters as if they had a CCSID of 37. This means that SQL looks for the not sign (¬) at '5F'X.
Output from the SQL precompiler
The SQL precompiler generates two pieces of output: a listing and a source file number.
Listing:
The output listing is sent to the printer file that is specified by the PRTFILE parameter of the CRTSQLxxx command.
The following items are written to the printer file: v Precompiler options
Options specified in the CRTSQLxxx command.
v Precompiler source
138
IBM i: Embedded SQL programming
This output supplies precompiler source statements with the record numbers that are assigned by the precompiler, if the listing option is in effect.
v
Precompiler cross-reference
If *XREF was specified in the OPTION parameter, this output supplies a cross-reference listing. The listing shows the precompiler record numbers of SQL statements that contain the referred to host names and column names.
v Precompiler diagnostics
This output supplies diagnostic messages, showing the precompiler record numbers of statements in error.
The output to the printer file will use a CCSID value of 65535. The data will not be converted when it is written to the printer file.
Temporary source file members created by the SQL precompiler:
Source statements processed by the precompiler are written to an output source file.
In the precompiler-changed source code, SQL statements have been converted to comments and calls to the SQL run time code. Include files that are processed by SQL are expanded.
|
|
|
|
|
|
|
|
|
|
|
|
|
The output source file is specified on the CRTSQLxxx command in the TOSRCFILE parameter.
v For languages other than C, C++, and ILE RPG, the default file is QSQLTEMP in the QTEMP library.
v For C and C++ when *CALC is specified as the output source file, QSQLTEMP will be used if the source file's record length is 92 or less. For a C or C++ source file where the record length is greater than 92, the output source file name will be generated as QSQLTxxxxx, where xxxxx is the record length.
v
For RPG when *CALC is specified as the output source file, QSQLTEMP1 will be used if the source file's record length is 112 or less. For an RPG source file where the record length is greater than 112, the output source file name will be generated as QSQLTxxxxx, where xxxxx is the record length.
The name of the output source file member is the same as the name specified in the PGM or OBJ parameter of the CRTSQLxxx command. This member cannot be changed before being used as input to the compiler. When SQL creates the output source file, it uses the CCSID value of the source file as the
CCSID value for the new file.
If the precompile generates output in a source file in QTEMP, the file can be moved to a permanent library after the precompile if you want to compile at a later time. You cannot change the records of the source member, or the attempted compile fails.
The source member that is generated by SQL as the result of the precompile should never be edited and reused as an input member to another precompile step. The additional SQL information that is saved with the source member during the first precompile will cause the second precompile to work incorrectly.
Once this information is attached to a source member, it stays with the member until the member is deleted.
The SQL precompiler uses the CRTSRCPF command to create the output source file. If the defaults for this command have changed, then the results may be unpredictable. If the source file is created by the user, not the SQL precompiler, the file's attributes may be different as well. It is recommended that the user allow SQL to create the output source file. Once it has been created by SQL, it can be reused on later precompiles.
Sample SQL precompiler output:
The precompiler output can provide information about your program source.
To generate the listing:
Embedded SQL programming
139
v For non-ILE precompilers, specify the *SOURCE (*SRC) and *XREF options on the OPTION parameter of the CRTSQLxxx command.
v
For ILE precompilers, specify OPTION(*XREF) and OUTPUT(*PRINT) on the CRTSQLxxx command.
The format of the precompiler output is:
1
2
xxxxST1 VxRxMx yymmdd Create SQL COBOL Program
Source type...............COBOL
Program name..............CORPDATA/CBLTEST1
Source file...............CORPDATA/SRC
Member....................CBLTEST1
To source file............QTEMP/QSQLTEMP
(1)Options...................*SRC *XREF *SQL
Target release............VxRxMx
INCLUDE file..............*SRCFILE
Commit....................*CHG
Allow copy of data........*YES
Close SQL cursor..........*ENDPGM
Allow blocking............*READ
Delay PREPARE.............*NO
Generation level..........10
Printer file..............*LIBL/QSYSPRT
Date format...............*JOB
Date separator............*JOB
Time format...............*HMS
Time separator ...........*JOB
Replace...................*YES
Relational database.......*LOCAL
User .....................*CURRENT
RDB connect method........*DUW
Default collection........*NONE
Dynamic default collection..............*NO
Package name..............*PGMLIB/*PGM
Path......................*NAMING
SQL rules.................*DB2
User profile..............*NAMING
Dynamic user profile......*USER
Sort sequence.............*JOB
Language ID...............*JOB
IBM SQL flagging..........*NOFLAG
ANS flagging..............*NONE
Text......................*SRCMBRTXT
Source file CCSID.........65535
Job CCSID.................65535
Decimal result options:
Maximum precision.......31
Maximum scale...........31
Minimum divide scale....0
DECFLOAT rounding mode....*HALFEVEN
Compiler options..........*NONE
(2) Source member changed on 06/06/00 10:16:44
CBLTEST1
A list of the options you specified when the SQL precompiler was called.
The date the source member was last changed.
08/06/07 11:14:21 Page 1
Figure 2. Sample COBOL precompiler output format
140
IBM i: Embedded SQL programming
xxxxST1 VxRxMx yymmdd Create SQL COBOL Program CBLTEST1 08/06/07 11:14:21 Page 2
(1)Record *...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 (2)SEQNBR (3)Last Change
1
2
3
31
32
33
34
27
28
29
30
21
22
23
24
25
26
17
18
19
20
13
14
15
16
9
10
11
12
7
8
5
6
3
4
1
2
43
44
45
46
47
48
39
40
41
42
35
36
37
38
IDENTIFICATION DIVISION.
PROGRAM-ID.
CBLTEST1.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. IBM-AS400.
OBJECT-COMPUTER. IBM-AS400.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT OUTFILE, ASSIGN TO PRINTER-QPRINT,
FILE STATUS IS FSTAT.
DATA DIVISION.
FILE SECTION.
FD OUTFILE
DATA RECORD IS REC-1,
LABEL RECORDS ARE OMITTED.
01 REC-1.
05 CC
05 DEPT-NO
PIC X.
PIC X(3).
05 FILLER PIC X(5).
05 AVERAGE-EDUCATION-LEVEL PIC ZZZ.
05
05
FILLER
AVERAGE-SALARY
01 ERROR-RECORD.
05 CC
05 ERROR-CODE
05 ERROR-MESSAGE
PIC X(5).
PIC ZZZZ9.99.
PIC X.
PIC S9(5).
PIC X(70).
WORKING-STORAGE SECTION.
EXEC SQL
INCLUDE SQLCA
END-EXEC.
77 FSTAT
01 AVG-RECORD.
05
05
WORKDEPT
AVG-EDUC
PIC XX.
PIC X(3).
PIC S9(4) USAGE COMP-4.
PIC S9(6)V99 COMP-3.
05 AVG-SALARY
PROCEDURE DIVISION.
***************************************************************
* This program will get the average education level and the *
* average salary by department.
*
***************************************************************
A000-MAIN-PROCEDURE.
OPEN OUTPUT OUTFILE.
***************************************************************
* Set up WHENEVER statement to handle SQL errors.
*
***************************************************************
EXEC SQL
WHENEVER SQLERROR GO TO B000-SQL-ERROR
END-EXEC.
100
200
300
400
500
600
700
800
900
1000
1100
1200
1300
1400
1500
1600
1700
1800
1900
2000
2100
2200
2300
2400
2500
2600
2700
2800
2900
3000
3100
3200
3300
3400
3500
3600
3700
3800
3900
4000
4100
4200
4300
4400
4500
4600
4700
4800
Record number assigned by the precompiler when it reads the source record. Record numbers are used to identify the source record in error messages and SQL run-time processing.
Sequence number taken from the source record. The sequence number is the number seen when you use the source entry utility (SEU) to edit the source member.
Date when the source record was last changed. If Last Change is blank, it indicates that the record has not been changed since it was created.
Embedded SQL programming
141
73
74
75
76
77
78
79
69
70
71
72
65
66
67
68 xxxxST1 VxRxMx yymmdd Create SQL COBOL Program CBLTEST1 08/06/07 11:14:21 Page 3
Record *...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 SEQNBR Last change
49 *************************************************************** 4900
50
51
52
53
* Declare cursor
EXEC SQL
DECLARE CURS CURSOR FOR
*
***************************************************************
5000
5100
5200
5300
58
59
60
61
54
55
56
57
62
63
64
***************************************************************
*
SELECT WORKDEPT, AVG(EDLEVEL), AVG(SALARY)
FROM CORPDATA.EMPLOYEE
GROUP BY WORKDEPT
END-EXEC.
Open cursor
EXEC SQL
OPEN CURS
END-EXEC.
*
***************************************************************
***************************************************************
5400
5500
5600
5700
5800
5900
6000
6100
6200
6300
6400
*
***************************************************************
***************************************************************
*
Fetch all result rows
PERFORM A010-FETCH-PROCEDURE THROUGH A010-FETCH-EXIT
UNTIL SQLCODE IS = 100.
Close cursor
EXEC SQL
CLOSE CURS
END-EXEC.
CLOSE OUTFILE.
STOP RUN.
*
*
***************************************************************
***************************************************************
* Fetch a row and move the information to the output record. *
***************************************************************
6500
6600
6700
6800
6900
7000
7100
7200
7300
7400
7500
7600
7700
7800
7900
88
89
90
91
92
93
94
84
85
86
87
80
81
82
83
*
*
A010-FETCH-PROCEDURE.
MOVE SPACES TO REC-1.
EXEC SQL
FETCH CURS INTO :AVG-RECORD
END-EXEC.
IF SQLCODE IS = 0
MOVE WORKDEPT TO DEPT-NO
MOVE AVG-SALARY TO AVERAGE-SALARY
MOVE AVG-EDUC TO AVERAGE-EDUCATION-LEVEL
WRITE REC-1 AFTER ADVANCING 1 LINE.
A010-FETCH-EXIT.
EXIT.
***************************************************************
An SQL error occurred.
record and stop running.
Move the error number to the error *
*
95
96
97
98
***************************************************************
B000-SQL-ERROR.
MOVE SPACES TO ERROR-RECORD.
MOVE SQLCODE TO ERROR-CODE.
99
100
101
102
MOVE "AN SQL ERROR HAS OCCURRED" TO ERROR-MESSAGE.
WRITE ERROR-RECORD AFTER ADVANCING 1 LINE.
CLOSE OUTFILE.
STOP RUN.
* * * * * E N D O F S O U R C E * * * * *
8000
8100
8200
8300
8400
8500
8600
8700
8800
8900
9000
9100
9200
9300
9400
9500
9600
9700
9800
9900
10000
10100
10200
142
IBM i: Embedded SQL programming
1
2
xxxxST1 VxRxMx yymmdd
CROSS REFERENCE
1
Data Names
AVERAGE-EDUCATION-LEVEL
AVERAGE-SALARY
AVG-EDUC
AVG-RECORD
AVG-SALARY
BIRTHDATE
BONUS
B000-SQL-ERROR
CC
CC
COMM
CORPDATA
CURS
DEPT-NO
EDLEVEL
EDLEVEL
EMPLOYEE
Create SQL COBOL Program CBLTEST1 08/06/07 11:14:21 Page
2
Define
20
22
34
32
3
Reference
IN REC-1
IN REC-1
SMALL INTEGER PRECISION(4,0) IN AVG-RECORD
35
55
55
****
STRUCTURE
83
DECIMAL(8,2) IN AVG-RECORD
DATE(10) COLUMN IN CORPDATA.EMPLOYEE
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
LABEL
47
CHARACTER(1) IN REC-1 17
24
55
CHARACTER(1) IN ERROR-RECORD
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
**** (4) SCHEMA
53
18
****
55
****
55
25
26
23
55
(5) 55
CURSOR
62 73 83
CHARACTER(3) IN REC-1
COLUMN
54
(6)
SMALL INTEGER PRECISION(4,0) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
TABLE IN CORPDATA
55
(7)
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
NUMERIC(5,0) IN ERROR-RECORD
CHARACTER(70) IN ERROR-RECORD
STRUCTURE
VARCHAR(12) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
EMPNO
ERROR-CODE
ERROR-MESSAGE
ERROR-RECORD
FIRSTNME
FSTAT
HIREDATE
JOB
LASTNAME
31
55
55
55
CHARACTER(2)
DATE(10) COLUMN IN CORPDATA.EMPLOYEE
CHARACTER(8) COLUMN IN CORPDATA.EMPLOYEE
VARCHAR(15) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
MIDINIT
PHONENO
REC-1
SALARY
55
55
16
****
CHARACTER(1) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
CHARACTER(4) COLUMN IN CORPDATA.EMPLOYEE
COLUMN
54
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
SALARY
SEX
WORKDEPT
WORKDEPT
55
55
33
****
CHARACTER(1) COLUMN IN CORPDATA.EMPLOYEE
CHARACTER(3) IN AVG-RECORD
COLUMN
54 56
CHARACTER(3) COLUMN IN CORPDATA.EMPLOYEE
WORKDEPT
No errors found in source
102 Source records processed
55
* * * * * E N D O F L I S T I N G * * * * *
4
3
Data names are the symbolic names used in source statements.
The define column specifies the line number at which the name is defined. The line number is generated by the SQL precompiler. **** means that the object was not defined or the precompiler did not recognize the declarations.
The reference column contains two types of information: v The definition of the symbolic name (4) v The line numbers where the symbolic name occurs (5)
If the symbolic name refers to a valid host variable, the data-type (6) or data-structure (7) is also noted.
Non-ILE SQL precompiler commands
The IBM DB2 Query Manager and SQL Development Kit for i licensed program includes non-ILE precompiler commands for the following host languages: CRTSQLCBL (for OPM COBOL), CRTSQLPLI (for
PL/I PRPQ), and CRTSQLRPG (for RPG III, which is part of RPG/400).
Embedded SQL programming
143
Some options only apply to certain languages. For example, the options *APOST and *QUOTE are unique to COBOL. They are not included in the commands for the other languages.
Related concepts
:
“CL command descriptions for host language precompilers” on page 188
The IBM DB2 Query Manager and SQL Development Kit for i licensed program provides commands for precompiling programs coded in these programming languages.
Compiling a non-ILE application program that uses SQL
The SQL precompiler automatically calls the host language compiler after the successful completion of a precompile, unless *NOGEN is specified.
The CRTxxxPGM command is run specifying the program name, source file name, precompiler created source member name, text, and USRPRF.
Within these languages, the following parameters are passed: v For COBOL, the *QUOTE or *APOST is passed on the CRTCBLPGM command.
v For RPG and COBOL, SAAFLAG (*FLAG) is passed on the CRTxxxPGM command.
v For RPG and COBOL, the SRTSEQ and LANGID parameter from the CRTSQLxxx command is specified on the CRTxxxPGM command.
v For RPG and COBOL, the CVTOPT (*DATETIME *VARCHAR) is always specified on the CRTxxxPGM command.
v For COBOL and RPG, the TGTRLS parameter value from the CRTSQLxxx command is specified on the
CRTxxxPGM
command. TGTRLS is not specified on the CRTPLIPGM command. The program can be saved or restored to the level specified on the TGTRLS parameter of the CRTSQLPLI command.
v
For PL/I, the MARGINS are set in the temporary source file.
v For all languages, the REPLACE parameter from the CRTSQLxxx command is specified on the CRTxxxPGM command.
If a package is created as part of the precompile process, the REPLACE parameter value from the
CRTSQLxxx
command is specified on the CRTSQLPKG command.
v For all languages, if USRPRF(*USER) or system naming (*SYS) with USRPRF(*NAMING) is specified, then USRPRF(*USER) is specified on the CRTxxxPGM command. If USRPRF(*OWNER) or SQL naming
(*SQL) with USRPRF(*NAMING) is specified, then USRPRF(*OWNER) is specified on the CRTxxxPGM command.
Defaults are used for all other parameters with CRTxxxPGM commands.
You can interrupt the call to the host language compiler by specifying *NOGEN on the OPTION parameter of the precompiler command. *NOGEN specifies that the host language compiler will not be called. Using the object name in the CRTSQLxxx command as the member name, the precompiler created the source member in the output source file (specified as the TOSRCFILE parameter on the CRTSQLxxx command). You now can explicitly call the host language compilers, specify the source member in the output source file, and change the defaults. If the precompile and compile were done as separate steps, the CRTSQLPKG command can be used to create the SQL package for a distributed program.
Note:
You must not change the source member in QTEMP/QSQLTEMP prior to issuing the CRTxxxPGM command or the compile will fail.
ILE SQL precompiler commands
In the IBM DB2 Query Manager and SQL Development Kit for i licensed program, these ILE precompiler commands exist: CRTSQLCI, CRTSQLCPPI, CRTSQLCBLI, and CRTSQLRPGI.
A precompiler command exists for each of the host languages: ILE C, ILE C++, ILE COBOL, and ILE
RPG. For each command, you can specify the required parameters and use the defaults for the remaining
144
IBM i: Embedded SQL programming
parameters. Some options are applicable only to one language. The defaults are applicable only to the language you are using. For example, the options *APOST and *QUOTE are unique to COBOL. They are not included in the commands for the other languages.
Related concepts
:
“CL command descriptions for host language precompilers” on page 188
The IBM DB2 Query Manager and SQL Development Kit for i licensed program provides commands for precompiling programs coded in these programming languages.
Compiling an ILE application program that uses SQL
The SQL precompiler automatically calls the host language compiler after the successful completion of a precompile for the CRTSQLxxx commands, unless *NOGEN is specified.
If the *MODULE option is specified, the SQL precompiler issues the CRTxxxMOD command to create the module. If the *PGM option is specified, the SQL precompiler issues the CRTBNDxxx command to create the program. If the *SRVPGM option is specified, the SQL precompiler issues the CRTxxxMOD command to create the module, followed by the Create Service Program (CRTSRVPGM) command to create the service program. The CRTSQLCPPI command only creates *MODULE objects.
Within these languages, the following parameters are passed: v If DBGVIEW(*SOURCE) is specified on the CRTSQLxxx command, then DBGVIEW(*ALL) is specified on both the CRTxxxMOD and CRTBNDxxx commands.
v If OUTPUT(*PRINT) is specified on the CRTSQLxxx command, it is passed on both the CRTxxxMOD and
CRTBNDxxx
commands.
If OUTPUT(*NONE) is specified on the CRTSQLxxx command, it is not specified on either the CRTxxxMOD command or the CRTBNDxxx command.
v
The TGTRLS parameter value from the CRTSQLxxx command is specified on the CRTxxxMOD, CRTBNDxxx, and Create Service Program (CRTSRVPGM) commands.
v The REPLACE parameter value from the CRTSQLxxx command is specified on the CRTxxxMOD, CRTBNDxxx, and CRTSRVPGM commands.
If a package is created as part of the precompile process, the REPLACE parameter value from the
CRTSQLxxx
command is specified on the CRTSQLPKG command.
v If OBJTYPE is either *PGM or *SRVPGM, and USRPRF(*USER) or system naming (*SYS) with
USRPRF(*NAMING) is specified, USRPRF(*USER) is specified on the CRTBNDxxx or the CRTSRVPGM commands.
If OBJTYPE is either *PGM or *SRVPGM, and USRPRF(*OWNER) or SQL naming (*SQL) with
USRPRF(*NAMING) is specified, USRPRF(*OWNER) is specified on the CRTBNDxxx or the CRTSRVPGM commands.
v
The DBGENCKEY value from the CRTSQLxxx command is specified on the CRTxxxMOD or CRTBNDxxx commands.
v For C and C++, the MARGINS are set in the temporary source file.
If the precompiler calculates that the total length of the LOB host variables is close to 15M, the
TERASPACE( *YES *TSIFC) option is specified on the CRTCMOD, CRTBNDC, or CRTCPPMOD commands.
v For C and C++, the DECFLTRND value is passed on the CRTCMOD, CRTBNDC, or CRTCPPMOD commands.
v For COBOL, the *QUOTE or *APOST is passed on the CRTBNDCBL or the CRTCBLMOD commands.
v For RPG and COBOL, the SRTSEQ and LANGID parameter from the CRTSQLxxx command is specified on the CRTxxxMOD and CRTBNDxxx commands.
v For COBOL, CVTOPT(*VARCHAR *DATETIME *PICGGRAPHIC *FLOAT) is always specified on the
CRTCBLMOD
and CRTBNDCBL commands. If OPTION(*NOCVTDT) is specified (the shipped command default), the additional options *DATE *TIME *TIMESTAMP are also specified for the CVTOPT.
v For RPG, if OPTION(*CVTDT) is specified, then CVTOPT(*DATETIME) is specified on the CRTRPGMOD and CRTBNDRPG commands.
Embedded SQL programming
145
You can interrupt the call to the host language compiler by specifying *NOGEN on the OPTION parameter of the precompiler command. *NOGEN specifies that the host language compiler is not called.
Using the specified program name in the CRTSQLxxx command as the member name, the precompiler creates the source member in the output source file (TOSRCFILE parameter). You can now explicitly call the host language compiler, specify the source member in the output source file, and change the defaults.
If the precompile and compile were done as separate steps, the CRTSQLPKG command can be used to create the SQL package for a distributed program.
If the program or service program is created later, the USRPRF parameter may not be set correctly on the
CRTBNDxxx
, Create Program (CRTPGM), or Create Service Program (CRTSRVPGM) command. The SQL program runs predictably only after the USRPRF parameter is corrected. If system naming is used, then the USRPRF parameter must be set to *USER. If SQL naming is used, then the USRPRF parameter must be set to *OWNER.
Setting compiler options using the precompiler commands
The COMPILEOPT string is available on the precompiler command and on the SET OPTION statement to allow additional parameters to be used on the compiler command.
The COMPILEOPT string is added to the compiler command built by the precompiler. This allows specifying compiler parameters without requiring a two step process of precompiling and then compiling.
Do not specify parameters in the COMPILEOPT string that the SQL precompiler passes. Doing so will cause the compiler command to fail with a duplicate parameter error. It is possible that the SQL precompiler will pass additional parameters to the compiler in the future. This could lead to a duplicate parameter error, requiring your COMPILEOPT string to be changed at that time.
|
|
|
If "*EVENTF" is anywhere in the COMPILEOPT string specified on the precompiler command, the precompiler will behave as if "OPTION(*EVENTF)" was specified on the precompiler command. This does not apply to the COMPILEOPT string specified on the SET OPTION statement.
If "INCDIR(" is anywhere in the COMPILEOPT string, the precompiler will call the compiler using the
SRCSTMF parameter.
EXEC SQL SET OPTION COMPILEOPT =’OPTION(*SHOWINC *EXPMAC)
INCDIR(’’/QSYS.LIB/MYLIB.LIB/MYFILE.MBR ’’)’;
Interpreting compile errors in applications that use SQL
Sometimes you will encounter compile errors. Use the following information to interpret these errors.
If you separate the precompile and compile steps, and the source program refers to externally described files, the referred-to files must not be changed between precompile and compile steps. Otherwise, results that are not predictable might occur because the changes to the field definitions are not changed in the temporary source member.
Examples of externally described files are: v COPY DDS in COBOL v %INCLUDE in PL/I v #pragma mapinc and #include in C or C++ v Externally-described files and externally-described data structures in RPG
When the SQL precompiler does not recognize host variables, try compiling the source. The compiler will not recognize the EXEC SQL statements, ignore these errors. Verify that the compiler interprets the host variable declaration as defined by the SQL precompiler for that language.
146
IBM i: Embedded SQL programming
Binding an application that uses SQL
Before you can run your application program, a relationship between the program and any specified tables and views must be established. This process is called binding. The result of binding is an access
plan.
The access plan is a control structure that describes the actions necessary to satisfy each SQL request. An access plan contains information about the program and about the data the program intends to use.
For a nondistributed SQL program, the access plan is stored in the program. For a distributed SQL program (where the RDB parameter is specified on the CRTSQLxxx command), the access plan is stored in the SQL package at the specified relational database.
SQL automatically attempts to bind and create access plans when the program object is created. For non-ILE compilations, this occurs as the result of running a successful CRTxxxPGM command. For ILE compilations, this occurs as the result of running a successful CRTBNDxxx, CRTPGM, or CRTSRVPGM command.
If DB2 for i detects at run time that an access plan is not valid (for example, the referenced tables are in a different library) or detects that changes have occurred to the database that might improve performance
(for example, the addition of indexes), a new access plan is automatically created. Binding does the following things:
1.
It revalidates the SQL statements using the description in the database.
During the bind process, the SQL statements are checked for valid table, column, and other object names. If a specified table or object does not exist at the time of the precompile or compile, the validation is done at run time. If the table or object does not exist at run time, a negative SQLCODE is returned.
2.
It selects the index needed to access the data your program wants to process.
In selecting an index, table sizes, and other factors are considered. It considers all indexes available to access the data and decides which ones (if any) to use when selecting a path to the data.
3.
It attempts to build access plans.
For each SQL statement that is valid, the bind process builds and stores an access plan in the program.
If the characteristics of a table or view your program accesses have changed, the access plan may no longer be valid. When you attempt to run a program that contains an access plan that is not valid, the system automatically attempts to rebuild the access plan. If the access plan cannot be rebuilt, a negative
SQLCODE is returned. In this case, you might have to change the program's SQL statements and reissue the CRTSQLxxx command to correct the situation.
Assume that a program contains an SQL statement that refers to COLUMNA in TABLEA and the user deletes and re-creates TABLEA so that COLUMNA no longer exists. When you call the program, the automatic rebind will be unsuccessful because COLUMNA no longer exists. In this case you must change the program source and reissue the CRTSQLxxx command.
Program references in applications that use SQL
All schemas, tables, views, SQL packages, and indexes referenced in SQL statements in an SQL program are placed in the object information repository (OIR) of the library when the program is created.
You can use the CL command Display Program References (DSPPGMREF) to display all object references in the program. If the SQL naming convention is used, the library name is stored in the OIR in one of three ways:
1.
If the SQL name is fully qualified, the schema name is stored as the name qualifier.
2.
If the SQL name is not fully qualified and the DFTRDBCOL parameter is not specified, the authorization ID of the statement is stored as the name qualifier.
3.
If the SQL name is not fully qualified and the DFTRDBCOL parameter is specified, the schema name specified on the DFTRDBCOL parameter is stored as the name qualifier.
If the system naming convention is used, the library name is stored in the OIR in one of three ways:
Embedded SQL programming
147
1.
If the object name is fully qualified, the library name is stored as the name qualifier.
2.
If the object is not fully qualified and the DFTRDBCOL parameter is not specified, *LIBL is stored.
3.
If the SQL name is not fully qualified and the DFTRDBCOL parameter is specified, the schema name specified on the DFTRDBCOL parameter is stored as the name qualifier.
Displaying SQL precompiler options
When the SQL application program is successfully compiled, the Display Module (DSPMOD), the Display
Program (DSPPGM)
, or the Display Service Program (DSPSRVPGM) command can be used to determine some of the options that were specified on the SQL precompile.
This information may be needed when the source of the program has to be changed. These same SQL precompiler options can then be specified on the CRTSQLxxx command when the program is compiled again.
The Print SQL Information (PRTSQLINF) command can also be used to determine some of the options that were specified on the SQL precompile.
Running a program with embedded SQL
Running a host language program with embedded SQL statements, after the precompile and compile have been successfully done, is the same as running any host program.
Enter the following CALL statement:
CALL pgm-name on the system command line.
Note:
After installing a new release, users may encounter message CPF2218 in QHST using any
Structured Query Language (SQL) program if the user does not have *CHANGE authority to the program. Once a user with *CHANGE authority calls the program, the access plan is updated and the message will be issued.
Related concepts
:
Control language
Running a program with embedded SQL: DDM considerations
|
|
|
SQL does not support remote file access through distributed data management (DDM) files, except for the case when a RDB is specified in the DDM file. SQL does support remote access through Distributed
Relational Database Architecture
™
(DRDA
®
).
Running a program with embedded SQL: Override considerations
You can use overrides (specified by the OVRDBF command) to direct a reference to a different table or view or to change certain operational characteristics of the program or SQL Package.
The following parameters are processed if an override is specified: v TOFILE v MBR v SEQONLY v INHWRT v
WAITRCD
All other override parameters are ignored. Overrides of statements in SQL packages are accomplished by doing both of the following:
1.
Specifying the OVRSCOPE(*JOB) parameter on the OVRDBF command
148
IBM i: Embedded SQL programming
2.
Sending the command to the application server by using the Submit Remote Command (SBMRMTCMD) command
To override tables and views that are created with long names, you can create an override using the system name that is associated with the table or view. When the long name is specified in an SQL statement, the override is found using the corresponding system name.
An alias is actually created as a DDM file. You can create an override that refers to an alias name (DDM file). In this case, an SQL statement that refers to the file that has the override actually uses the file to which the alias refers.
Related concepts
:
Database programming
Database file management
Running a program with embedded SQL: SQL return codes
An SQL return code is sent by the database manager after the completion of each SQL statement. Your program can check the SQLCODE or SQLSTATE after every SQL statement.
Related concepts
:
SQL messages and codes
Example programs: Using DB2 for i statements
Here is a sample application that shows how to code SQL statements in each of the languages that DB2 for i supports.
The sample application gives raises based on commission.
Each sample program produces the same report, which is shown at the end of this topic. The first part of the report shows, by project, all employees working on the project who received a raise. The second part of the report shows the new salary expense for each project.
Notes about the sample programs
The following notes apply to all the sample programs:
SQL statements can be entered in uppercase or lowercase.
1
This host language statement retrieves the external definitions for the SQL table PROJECT. These definitions can be used as host variables or as a host structure.
2
3
Notes:
1.
In RPG/400, field names in an externally described structure that are longer than 6 characters must be renamed.
2.
REXX does not support the retrieval of external definitions.
The SQL INCLUDE SQLCA statement is used to include the SQLCA for PL/I, C, and COBOL programs. For RPG programs, the SQL precompiler automatically places the SQLCA data structure into the source at the end of the Input specification section. For REXX, the SQLCA fields are maintained in separate variables rather than in a contiguous data area mapped by the
SQLCA.
This SQL WHENEVER statement defines the host language label to which control is passed if an
SQLERROR (SQLCODE < 0) occurs in an SQL statement. This WHENEVER SQLERROR statement applies to all the following SQL statements until the next WHENEVER SQLERROR statement is encountered. REXX does not support the WHENEVER statement. Instead, REXX uses the SIGNAL ON ERROR facility.
Embedded SQL programming
149
4
5
This SQL UPDATE statement updates the SALARY column, which contains the employee salary by the percentage in the host variable PERCENTAGE (PERCNT for RPG). The updated rows are those that have employee commissions greater than 2000. For REXX, this is PREPARE and
EXECUTE since UPDATE cannot be run directly if there is a host variable.
This SQL COMMIT statement commits the changes made by the SQL UPDATE statement. Record locks on all changed rows are released.
6
Note:
The program was precompiled using COMMIT(*CHG). (For REXX, *CHG is the default.)
This SQL DECLARE CURSOR statement defines cursor C1, which joins two tables, EMPLOYEE and EMPPROJACT, and returns rows for employees who received a raise (commission > 2000).
Rows are returned in ascending order by project number and employee number (PROJNO and
EMPNO columns). For REXX, this is a PREPARE and DECLARE CURSOR since the DECLARE
CURSOR statement cannot be specified directly with a statement string if it has host variables.
This SQL OPEN statement opens cursor C1 so that the rows can be fetched.
7
8
9
10
11
12
This SQL WHENEVER statement defines the host language label to which control is passed when all rows are fetched (SQLCODE = 100). For REXX, the SQLCODE must be explicitly checked.
This SQL FETCH statement returns all columns for cursor C1 and places the returned values into the corresponding elements of the host structure.
After all rows are fetched, control is passed to this label. The SQL CLOSE statement closes cursor
C1.
This SQL DECLARE CURSOR statement defines cursor C2, which joins the three tables,
EMPPROJACT, PROJECT, and EMPLOYEE. The results are grouped by columns PROJNO and
PROJNAME. The COUNT function returns the number of rows in each group. The SUM function calculates the new salary cost for each project. The ORDER BY 1 clause specifies that rows are retrieved based on the contents of the final results column (EMPPROJACT.PROJNO). For REXX, this is a PREPARE and DECLARE CURSOR since the DECLARE CURSOR statement cannot be specified directly with a statement string if it has host variables.
This SQL FETCH statement returns the results columns for cursor C2 and places the returned values into the corresponding elements of the host structure described by the program.
13
This SQL WHENEVER statement with the CONTINUE option causes processing to continue to the next statement regardless if an error occurs on the SQL ROLLBACK statement. Errors are not expected on the SQL ROLLBACK statement; however, this prevents the program from going into a loop if an error does occur. REXX does not support the WHENEVER statement. Instead, REXX uses the SIGNAL OFF ERROR facility.
14
This SQL ROLLBACK statement restores the table to its original condition if an error occurred during the update.
Related concepts
:
“Coding SQL statements in C and C++ applications” on page 11
To embed SQL statements in an ILE C or C++ program, you need to be aware of some unique application and coding requirements. This topic also defines the requirements for host structures and host variables.
“Coding SQL statements in COBOL applications” on page 44
There are unique application and coding requirements for embedding SQL statements in a COBOL program. In this topic, requirements for host structures and host variables are defined.
“Coding SQL statements in PL/I applications” on page 73
There are some unique application and coding requirements for embedding SQL statements in a PL/I program. In this topic, requirements for host structures and host variables are defined.
“Coding SQL statements in ILE RPG applications” on page 98
You need to be aware of the unique application and coding requirements for embedding SQL statements in an ILE RPG program. In this topic, the coding requirements for host variables are defined.
150
IBM i: Embedded SQL programming
“Coding SQL statements in RPG/400 applications” on page 88
The RPG/400 licensed program supports both RPG II and RPG III programs.
“Coding SQL statements in REXX applications” on page 128
REXX procedures do not have to be preprocessed. At run time, the REXX interpreter passes statements that it does not understand to the current active command environment for processing.
Example: SQL statements in ILE C and C++ programs
This example program is written in the C programming language.
The same program would work in C++ if the following conditions are true: v An SQL BEGIN DECLARE SECTION statement was added before line 18 v An SQL END DECLARE SECTION statement was added after line 42
Note:
Embedded SQL programming
151
xxxxST1 VxRxMx yymmdd
Source type...............C
Create SQL ILE C Object
Object name...............CORPDATA/CEX
Source file...............CORPDATA/SRC
Member....................CEX
To source file............QTEMP/QSQLTEMP
Options...................*XREF
Listing option............*PRINT
Target release............VxRxMx
INCLUDE file..............*SRCFILE
Commit....................*CHG
Allow copy of data........*YES
Close SQL cursor..........*ENDACTGRP
Allow blocking............*READ
Delay PREPARE.............*NO
Generation level..........10
Margins...................*SRCFILE
Printer file..............*LIBL/QSYSPRT
Date format...............*JOB
Date separator............*JOB
Time format...............*HMS
Time separator ...........*JOB
Replace...................*YES
Relational database.......*LOCAL
User .....................*CURRENT
RDB connect method........*DUW
Default collection........*NONE
Dynamic default collection..............*NO
Package name..............*OBJLIB/*OBJ
Path......................*NAMING
SQL rules.................*DB2
Created object type.......*PGM
Debugging view............*NONE
User profile..............*NAMING
Dynamic user profile......*USER
Sort sequence.............*JOB
Language ID...............*JOB
IBM SQL flagging..........*NOFLAG
ANS flagging..............*NONE
Text......................*SRCMBRTXT
Source file CCSID.........65535
Job CCSID.................65535
Decimal result options:
Maximum precision.......31
Maximum scale...........31
Minimum divide scale....0
DECFLOAT rounding mode....*HALFEVEN
Compiler options..........*NONE
Source member changed on 06/06/00 17:15:17
Figure 3. Sample C program using SQL statements
CEX 08/06/07 15:52:26 Page 1
152
IBM i: Embedded SQL programming
51
52
53
54
47
48
49
50
55
56
57
58
59
60
40
41
42
43
44
45
46
36
37
38
39
32
33
34
35
25
26
27
28
29
30
31
21
22
23
24
17
18
19
20 xxxxST1 VxRxMx yymmdd Create SQL ILE C Object CEX 08/06/07 15:52:26 Page 2
Record *...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 SEQNBR Last change
1 #include "string.h" 100
2 #include "stdlib.h"
3 #include "stdio.h"
4
5 main()
200
300
400
500
6 {
7 /* A sample program which updates the salaries for those employees */
8 /* whose current commission total is greater than or equal to the
9 /* value of ’commission’. The salaries of those who qualify are
*/
*/
10 /* increased by the value of ’percentage’, retroactive to ’raise_date’.*/
11 /* A report is generated showing the projects that these employees */
12 /* have contributed to, ordered by project number and employee ID.
13 /* A second report shows each project having an end date occurring */
*/
14 /* after ’raise_date’ (is potentially affected by the retroactive */
15 /* raises) with its total salary expenses and a count of employees */
16 /* who contributed to the project.
*/
600
700
800
900
1000
1100
1200
1300
1400
1500
1600 short work_days char raise_date??(12??) = "1982-06-01"; /* effective raise date */
/* File declaration for qprint */
FILE *qprint; struct { char
= 253; float commission = 2000.00; float percentage = 1.04;
/* Structure for report 1 */
/* work days during in one year */
/* cutoff to qualify for raise
/* raised salary as percentage
*/
*/
1 #pragma mapinc ("project","CORPDATA/PROJECT(PROJECT)","both","p z")
#include "project"
CORPDATA_PROJECT_PROJECT_both_t Proj_struct; empno??(7??); char name??(30??); float salary;
} rpt1;
1700
1800
1900
2000
2100
2200
2300
2400
2500
2600
2700
2800
2900
3000
3100
/* Structure for report 2 */ struct { char projno??(7??); char project_name??(37??); short employee_count; double total_proj_cost;
} rpt2;
2 exec sql include SQLCA; qprint=fopen("QPRINT","w");
4000
4100
4200
4300
4400
4500
4600
3200
3300
3400
3500
3600
3700
3800
3900
/* Update the selected projects by the new percentage. If an error */
/* occurs during the update, ROLLBACK the changes.
3 EXEC SQL WHENEVER SQLERROR GO TO update_error;
4 EXEC SQL
UPDATE CORPDATA/EMPLOYEE
SET SALARY = SALARY * :percentage
WHERE COMM >= :commission ;
/* Commit changes */
5 EXEC SQL
COMMIT;
EXEC SQL WHENEVER SQLERROR GO TO report_error;
*/
4700
4800
4900
5000
5100
5200
5300
5400
5500
5600
5700
5800
5900
6000
Embedded SQL programming
153
115
116
117
118
119
120
121
122
123
100
101
102
103
104
105
106
96
97
98
99
92
93
94
95
81
82
83
84
77
78
79
80 xxxxST1 VxRxMx yymmdd Create SQL ILE C Object CEX 08/06/07 15:52:26 Page 3
Record *...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 SEQNBR Last change
61 /* Report the updated statistics for each employee assigned to the */ 6100
*/ 62
63
64
65
/* selected projects.
66 BY RAISES");
67 fprintf(qprint,"\n\nPROJECT EMPID
68
69
/* Write out the header for Report 1 */ fprintf(qprint," REPORT OF PROJECTS AFFECTED \ fprintf(qprint, "
EMPLOYEE NAME
SALARY\n");
");
6200
6300
6400
6500
6600
6700
6800
6900
70
71
72
73
74
75
76
6 exec sql declare c1 cursor for select distinct projno, empprojact.empno, lastname||’, ’||firstnme, salary from corpdata/empprojact, corpdata/employee where empprojact.empno = employee.empno and comm >= :commission order by projno, empno;
7 EXEC SQL
OPEN C1;
7000
7100
7200
7300
7400
7500
7600
/* Fetch and write the rows to QPRINT */
8 EXEC SQL WHENEVER NOT FOUND GO TO done1; do {
10 EXEC SQL
FETCH C1 INTO :Proj_struct.PROJNO, :rpt1.empno,
:rpt1.name,:rpt1.salary;
7700
7800
7900
8000
8100
8200
8300
8400
85
86
87
88
89
90
91 fprintf(qprint,"\n%6s
}
%6s %-30s %8.2f", rpt1.Proj_struct.PROJNO,rpt1.empno, rpt1.name,rpt1.salary); while (SQLCODE==0);
8500
8600
8700
8800
8900
9000
9100 done1:
EXEC SQL
CLOSE C1;
/* For all projects ending at a date later than the ’raise_date’
/* the count of employees participating in the project, and the
/* total salary cost of the project.
/* Write out the header for Report 2 */ fprintf(qprint,"\n\n\n
BY PROJECT"); fprintf(qprint, "\n\nPROJECT
ACCUMULATED STATISTICS\
107
108
109
110
NUMBER OF fprintf(qprint,
EMPLOYEES
TOTAL");
"\nNUMBER
COST\n");
PROJECT NAME
111 11 EXEC SQL
112 DECLARE C2 CURSOR FOR
113
114
SELECT EMPPROJACT.PROJNO, PROJNAME, COUNT(*),
SUM ( ( DAYS(EMENDATE) - DAYS(EMSTDATE) ) * EMPTIME *
\
\
* /
/* (that is, those projects potentially affected by the salary raises), */
/* generate a report containing the project number, project name */
*/
*/
10000
10100
10200
10300
10400
10500
10600
9200
9300
9400
9500
9600
9700
9800
9900
FROM CORPDATA/EMPPROJACT, CORPDATA/PROJECT, CORPDATA/EMPLOYEE
WHERE EMPPROJACT.PROJNO=PROJECT.PROJNO
AND
EMPPROJACT.EMPNO =EMPLOYEE.EMPNO
AND
PRENDATE > :raise_date
GROUP BY EMPPROJACT.PROJNO, PROJNAME
ORDER BY 1;
EXEC SQL
OPEN C2;
(DECIMAL( SALARY / :work_days ,8,2))) 11500
11600
11700
11800
11900
12000
12100
12200
12300
10700
10800
10900
11000
11100
11200
11300
11400
154
IBM i: Embedded SQL programming
xxxxST1 VxRxMx yymmdd Create SQL ILE C Object CEX 08/06/07 15:52:26 Page 4
Record *...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 SEQNBR Last change
124 12400
125
126
127
128
/* Fetch and write the rows to QPRINT */
EXEC SQL WHENEVER NOT FOUND GO TO done2;
12500
12600
12700
12800
129
130
131
132 do {
12 EXEC SQL
FETCH C2 INTO :rpt2; fprintf(qprint,"\n%6s %-36s %6d %9.2f", rpt2.projno,rpt2.project_name,rpt2.employee_count,
12900
13000
13100
13200
133
134
135
136
137
138
139
} rpt2.total_proj_cost); while (SQLCODE==0); done2:
EXEC SQL
CLOSE C2; goto finished; 140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
/* Error occurred while updating table.
Inform user and rollback */
/* changes.
*/ update_error:
13 EXEC SQL WHENEVER SQLERROR CONTINUE; fprintf(qprint,"*** ERROR Occurred while updating table.
SQLCODE="
"%5d\n",SQLCODE);
14 EXEC SQL
ROLLBACK; goto finished;
/* Error occurred while generating reports.
Inform user and exit.
*/ report_error: fprintf(qprint,"*** ERROR Occurred while generating reports.
"
"SQLCODE=%5d\n",SQLCODE); goto finished;
/* All done finished:
*/ fclose(qprint); exit(0);
163 }
* * * * * E N D O F S O U R C E * * * * *
13300
13400
13500
13600
13700
13800
13900
14000
14100
14200
14300
14400
14500
14600
14700
14800
14900
15000
15100
15200
15300
15400
15500
15600
15700
15800
15900
16000
16100
16200
16300
Embedded SQL programming
155
xxxxST1 VxRxMx yymmdd
CROSS REFERENCE
Data Names commission done1 done2 employee_count empno name percentage project_name projno raise_date report_error rpt1 rpt2 salary total_proj_cost update_error work_days
ACTNO
BIRTHDATE
BONUS
COMM
COMM
CORPDATA
C1
C2
DEPTNO
DEPTNO
EDLEVEL
EMENDATE
EMENDATE
EMPLOYEE
EMPLOYEE
EMPNO
EMPNO
EMPNO
EMPNO
EMPPROJACT
EMPPROJACT
Create SQL ILE C Object CEX 08/06/07 15:52:26 Page 5
71
112
27
116
74
74
****
74
74
74
****
74
****
****
34
42
33
41
****
18
****
****
****
****
74
74
****
****
Define
19
****
****
40
31
32
20
39
38
21
Reference
FLOAT(24)
54 75
LABEL
81
LABEL
126
SMALL INTEGER PRECISION(4,0) IN rpt2
VARCHAR(7) IN rpt1
85
VARCHAR(30) IN rpt1
86
FLOAT(24)
53
VARCHAR(37) IN rpt2
VARCHAR(7) IN rpt2
VARCHAR(12)
119
LABEL
59
STRUCTURE
130
FLOAT(24) IN rpt1
86
FLOAT(53) IN rpt2
LABEL
50
SMALL INTEGER PRECISION(4,0)
115
SMALL INTEGER PRECISION(4,0) COLUMN (NOT NULL) IN CORPDATA.EMPPROJACT
DATE(10) COLUMN IN CORPDATA.EMPLOYEE
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
COLUMN
54 75
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
SCHEMA
52 74 74 116 116 116
CURSOR
78 85 95
CURSOR
123 130 139
VARCHAR(3) IN Proj_struct
CHARACTER(3) COLUMN (NOT NULL) IN CORPDATA.PROJECT
SMALL INTEGER PRECISION(4,0) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
DATE(10) COLUMN IN CORPDATA.EMPPROJACT
COLUMN
114
TABLE IN CORPDATA
52 74 116
TABLE
75 118
COLUMN IN EMPPROJACT
72 75 76 118
COLUMN IN EMPLOYEE
75 118
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPPROJACT
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
TABLE
72 75 113 117 118 120
TABLE IN CORPDATA
74 116
156
IBM i: Embedded SQL programming
xxxxST1 VxRxMx yymmdd
CROSS REFERENCE
Create SQL ILE C Object CEX 08/06/07 15:52:26
EMPTIME
EMPTIME
EMSTDATE
EMSTDATE
FIRSTNME
FIRSTNME
HIREDATE
JOB
LASTNAME
LASTNAME
MAJPROJ
MAJPROJ
MIDINIT
Proj_struct
PHONENO
PRENDATE
PRENDATE
PRENDATE
PROJECT
PROJECT
PROJNAME
PROJNAME
74
****
74
****
****
74
74
74
****
73
74
27
116
74
30
74
27
****
116
****
****
27
****
DECIMAL(5,2) COLUMN IN CORPDATA.EMPPROJACT
COLUMN
114
DATE(10) COLUMN IN CORPDATA.EMPPROJACT
COLUMN
114
COLUMN
73
VARCHAR(12) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
DATE(10) COLUMN IN CORPDATA.EMPLOYEE
CHARACTER(8) COLUMN IN CORPDATA.EMPLOYEE
COLUMN
VARCHAR(15) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
VARCHAR(6) IN Proj_struct
CHARACTER(6) COLUMN IN CORPDATA.PROJECT
CHARACTER(1) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
STRUCTURE IN rpt1
CHARACTER(4) COLUMN IN CORPDATA.EMPLOYEE
DATE(10) IN Proj_struct
COLUMN
119
DATE(10) COLUMN IN CORPDATA.PROJECT
TABLE IN CORPDATA
116
TABLE
117
VARCHAR(24) IN Proj_struct
COLUMN
113 120
PROJNAME
PROJNO
PROJNO
PROJNO
PROJNO
PROJNO
PROJNO
PRSTAFF
PRSTAFF
PRSTDATE
PRSTDATE
116
27
****
74
****
****
116
27
116
27
116
VARCHAR(24) COLUMN (NOT NULL) IN CORPDATA.PROJECT
VARCHAR(6) IN Proj_struct
85
COLUMN
72 76
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPPROJACT
COLUMN IN EMPPROJACT
113 117 120
COLUMN IN PROJECT
117
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.PROJECT
DECIMAL(5,2) IN Proj_struct
DECIMAL(5,2) COLUMN IN CORPDATA.PROJECT
DATE(10) IN Proj_struct
DATE(10) COLUMN IN CORPDATA.PROJECT
RESPEMP
RESPEMP
SALARY
SALARY
SEX
WORKDEPT
No errors found in source
27
116
****
74
74
74
VARCHAR(6) IN Proj_struct
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.PROJECT
COLUMN
53 53 73 115
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
CHARACTER(1) COLUMN IN CORPDATA.EMPLOYEE
CHARACTER(3) COLUMN IN CORPDATA.EMPLOYEE
163 Source records processed
* * * * * E N D O F L I S T I N G * * * * *
Page 6
Related concepts
:
“Coding SQL statements in C and C++ applications” on page 11
To embed SQL statements in an ILE C or C++ program, you need to be aware of some unique application and coding requirements. This topic also defines the requirements for host structures and host variables.
Example: SQL statements in COBOL and ILE COBOL programs
This example program is written in the COBOL programming language.
Note:
Embedded SQL programming
157
xxxxST1 VxRxMx yymmdd Create SQL COBOL Program
Source type...............COBOL
Program name..............CORPDATA/CBLEX
Source file...............CORPDATA/SRC
Member....................CBLEX
To source file............QTEMP/QSQLTEMP
*XREF Options...................*SRC
Target release............VxRxMx
INCLUDE file..............*SRCFILE
Commit....................*CHG
Allow copy of data........*YES
Close SQL cursor..........*ENDPGM
Allow blocking............*READ
Delay PREPARE.............*NO
Generation level..........10
Printer file..............*LIBL/QSYSPRT
Date format...............*JOB
Date separator............*JOB
Time format...............*HMS
Time separator ...........*JOB
Replace...................*YES
Relational database.......*LOCAL
User .....................*CURRENT
RDB connect method........*DUW
Default collection........*NONE
Dynamic default collection..............*NO
Package name..............*PGMLIB/*PGM
Path......................*NAMING
SQL rules.................*DB2
Created object type.......*PGM
User profile..............*NAMING
Dynamic user profile......*USER
Sort sequence.............*JOB
Language ID...............*JOB
IBM SQL flagging..........*NOFLAG
ANS flagging..............*NONE
Text......................*SRCMBRTXT
Source file CCSID.........65535
Job CCSID.................65535
Decimal result options:
Maximum precision.......31
Maximum scale...........31
Minimum divide scale....0
DECFLOAT rounding mode....*HALFEVEN
Compiler options..........*NONE
Source member changed on 07/01/96 09:44:58
Figure 4. Sample COBOL program using SQL statements
CBLEX 08/06/07 11:09:13 Page 1
158
IBM i: Embedded SQL programming
40
41
42
43
44
45
46
36
37
38
39
32
33
34
35
51
52
53
54
55
47
48
49
50
25
26
27
28
29
30
31
21
22
23
24
17
18
19
20 xxxxST1 VxRxMx yymmdd Create SQL COBOL Program CBLEX 08/06/07 11:09:13 Page 2
Record *...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 SEQNBR Last change
1
4
5
2
3
****************************************************************
* A sample program that updates the salaries for those *
* employees whose current commission total is greater than or *
* equal to the value of COMMISSION. The salaries of those who *
10
11
12
13
14
15
16
8
9
6
7
* qualify are increased by the value of PERCENTAGE retroactive *
* to RAISE-DATE. A report is generated showing the projects
* that these employees have contributed to ordered by the
*
*
* project number and employee ID. A second report shows each *
* project having an end date occurring after RAISE-DATE *
* (that is, potentially affected by the retroactive raises ) *
* with its total salary expenses and a count of employees
* who contributed to the project.
*
*
****************************************************************
IDENTIFICATION DIVISION.
PROGRAM-ID.
CBLEX.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. IBM-AS400.
OBJECT-COMPUTER. IBM-AS400.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT PRINTFILE ASSIGN TO PRINTER-QPRINT
ORGANIZATION IS SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
*
FD
01
PRINTFILE
BLOCK CONTAINS 1 RECORDS
LABEL RECORDS ARE OMITTED.
PRINT-RECORD PIC X(132).
WORKING-STORAGE SECTION.
77 WORK-DAYS PIC S9(4) BINARY VALUE 253.
77 RAISE-DATE PIC X(11) VALUE "1982-06-01".
77
77
PERCENTAGE PIC S999V99 PACKED-DECIMAL.
COMMISSION PIC S99999V99 PACKED-DECIMAL VALUE 2000.00.
***************************************************************
Structure for report 1.
1 01 RPT1.
COPY DDS-PROJECT OF CORPDATA-PROJECT.
05 EMPNO
05 NAME
05 SALARY
PIC X(6).
PIC X(30).
PIC S9(6)V99 PACKED-DECIMAL.
*
***************************************************************
Embedded SQL programming
159
110
111
112
113
114
115
116
117
118
102
103
104
105
106
107
108
109
95
96
97
98
99
100
101
91
92
93
94
87
88
89
90
76
77
78
79
72
73
74
75 xxxxST1 VxRxMx yymmdd Create SQL COBOL Program CBLEX 08/06/07 11:09:13 Page 3
Record *...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 SEQNBR Last change
56 ***************************************************************
57
58
59
60
* Structure for report 2.
*
***************************************************************
61
62
63
64
01 RPT2.
15 PROJNO PIC X(6).
15 PROJECT-NAME PIC X(36).
15
15
EMPLOYEE-COUNT PIC S9(4) BINARY.
TOTAL-PROJ-COST PIC S9(10)V99 PACKED-DECIMAL.
65
66
67
68
69
70
71
2 EXEC SQL
77
INCLUDE SQLCA
END-EXEC.
CODE-EDIT PIC ---99.
***************************************************************
* Headers for reports.
*
***************************************************************
01 RPT1-HEADERS.
05 RPT1-HEADER1.
10 FILLER PIC X(21) VALUE SPACES.
10 FILLER PIC X(111)
VALUE "REPORT OF PROJECTS AFFECTED BY RAISES".
05 RPT1-HEADER2.
10 FILLER PIC X(9) VALUE "PROJECT".
80
81
82
83
84
85
86
10
10
FILLER PIC X(10) VALUE "EMPID".
FILLER PIC X(35) VALUE "EMPLOYEE NAME".
10 FILLER PIC X(40) VALUE "SALARY".
01 RPT2-HEADERS.
05 RPT2-HEADER1.
01
05
05
05
10
10
10
10
10
10
10
10
10
10
FILLER PIC X(21) VALUE SPACES.
FILLER PIC X(111)
RPT2-HEADER2.
FILLER PIC X(9) VALUE "PROJECT".
FILLER PIC X(38) VALUE SPACES.
FILLER PIC X(16) VALUE "NUMBER OF".
FILLER PIC X(10) VALUE "TOTAL".
RPT2-HEADER3.
FILLER PIC X(9) VALUE "NUMBER".
FILLER PIC X(38) VALUE "PROJECT NAME".
FILLER PIC X(16) VALUE "EMPLOYEES".
FILLER PIC X(65) VALUE "COST".
RPT1-DATA.
PROJNO
VALUE "ACCUMULATED STATISTICS BY PROJECT".
PIC X(6).
05 FILLER
05 EMPNO
05 FILLER
05 NAME
05 FILLER
05 SALARY
05 FILLER
01 RPT2-DATA.
PIC XXX VALUE SPACES.
PIC X(6).
PIC X(4) VALUE SPACES.
PIC X(30).
PIC X(3) VALUE SPACES.
PIC ZZZZZ9.99.
PIC X(96) VALUE SPACES.
05 PROJNO PIC X(6).
05 FILLER PIC XXX VALUE SPACES.
05 PROJECT-NAME PIC X(36).
05 FILLER PIC X(4) VALUE SPACES.
05 EMPLOYEE-COUNT PIC ZZZ9.
05 FILLER PIC X(5) VALUE SPACES.
05 TOTAL-PROJ-COST PIC ZZZZZZZZ9.99.
05 FILLER PIC X(56) VALUE SPACES.
160
IBM i: Embedded SQL programming
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
158
159
160
161
162
163
164
150
151
152
153
154
155
156
157
143
144
145
146
147
148
149
135
136
137
138
139
140
141
142 xxxxST1 VxRxMx yymmdd Create SQL COBOL Program CBLEX 08/06/07 11:09:13 Page 4
Record *...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 SEQNBR Last change
119 PROCEDURE DIVISION.
120
121
122
123
A000-MAIN.
MOVE 1.04 TO PERCENTAGE.
OPEN OUTPUT PRINTFILE.
124
125
126
127
128
129
130
131
132
133
134
***************************************************************
* Update the selected employees by the new percentage. If an *
* error occurs during the update, roll back the changes,
3 EXEC SQL
WHENEVER SQLERROR GO TO E010-UPDATE-ERROR
END-EXEC.
4 EXEC SQL
UPDATE CORPDATA/EMPLOYEE
SET SALARY = SALARY * :PERCENTAGE
WHERE COMM >= :COMMISSION
END-EXEC.
*
***************************************************************
***************************************************************
* Commit changes.
*
***************************************************************
5 EXEC SQL
COMMIT
END-EXEC.
EXEC SQL
WHENEVER SQLERROR GO TO E020-REPORT-ERROR
END-EXEC.
***************************************************************
* Report the updated statistics for each employee receiving *
* a raise and the projects that the employee participates in
***************************************************************
***************************************************************
* Write out the header for Report 1.
*
***************************************************************
* write print-record from rpt1-header1 before advancing 2 lines.
write print-record from rpt1-header2 before advancing 1 line.
6 exec sql declare c1 cursor for
SELECT DISTINCT projno, empprojact.empno, lastname||", "||firstnme ,salary from corpdata/empprojact, corpdata/employee where empprojact.empno =employee.empno and comm >= :commission order by projno, empno end-exec.
7 EXEC SQL
OPEN C1
END-EXEC.
PERFORM B000-GENERATE-REPORT1 THRU B010-GENERATE-REPORT1-EXIT
UNTIL SQLCODE NOT EQUAL TO ZERO.
Embedded SQL programming
161
226
227
228
229
230
231
232
233
211
212
213
214
215
216
217
218
196
197
198
199
200
201
202
203 xxxxST1 VxRxMx yymmdd Create SQL COBOL Program CBLEX 08/06/07 11:09:13 Page 5
Record *...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 SEQNBR Last change
180 10 A100-DONE1.
181
182
183
184
EXEC SQL
CLOSE C1
END-EXEC.
185
186
187
188
189
190
191
192
193
194
195
*************************************************************
*
*
*
*
*
*
For all projects ending at a date later than the RAISEnumber, project name, the count of employees participating in the project, and the total salary cost for the project.
*
DATE (that is, those projects potentially affected by the* salary raises), generate a report containing the project *
*
*
*
*************************************************************
***************************************************************
* Write out the header for Report 2.
*
***************************************************************
204
205
206
207
208
209
210
MOVE SPACES TO PRINT-RECORD.
WRITE PRINT-RECORD BEFORE ADVANCING 2 LINES.
WRITE PRINT-RECORD FROM RPT2-HEADER1
BEFORE ADVANCING 2 LINES.
WRITE PRINT-RECORD FROM RPT2-HEADER2
BEFORE ADVANCING 1 LINE.
WRITE PRINT-RECORD FROM RPT2-HEADER3
BEFORE ADVANCING 2 LINES.
EXEC SQL
11 DECLARE C2 CURSOR FOR
SELECT EMPPROJACT.PROJNO, PROJNAME, COUNT(*),
SUM ( (DAYS(EMENDATE)-DAYS(EMSTDATE)) *
EMPTIME * DECIMAL((SALARY / :WORK-DAYS),8,2))
FROM CORPDATA/EMPPROJACT, CORPDATA/PROJECT,
CORPDATA/EMPLOYEE
219
220
221
222
223
224
225
WHERE EMPPROJACT.PROJNO=PROJECT.PROJNO AND
EMPPROJACT.EMPNO =EMPLOYEE.EMPNO AND
PRENDATE > :RAISE-DATE
GROUP BY EMPPROJACT.PROJNO, PROJNAME
ORDER BY 1
END-EXEC.
EXEC SQL
OPEN C2
END-EXEC.
PERFORM C000-GENERATE-REPORT2 THRU C010-GENERATE-REPORT2-EXIT
UNTIL SQLCODE NOT EQUAL TO ZERO.
A200-DONE2.
EXEC SQL
CLOSE C2
END-EXEC
***************************************************************
* All done.
*
***************************************************************
234
235
236
237
238
239
240
A900-MAIN-EXIT.
CLOSE PRINTFILE.
STOP RUN.
162
IBM i: Embedded SQL programming
300
301
302
303
304
305
306
307
287
288
289
290
291
292
293
294
295
296
297
298
299
280
281
282
283
284
285
286
272
273
274
275
276
277
278
279
261
262
263
264
265
266
267
268
269
270
271 xxxxST1 VxRxMx yymmdd Create SQL COBOL Program CBLEX 08/06/07 11:09:13 Page 6
Record *...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 SEQNBR Last change
241 ***************************************************************
242
243
244
245
* Fetch and write the rows to PRINTFILE.
*
***************************************************************
246
247
248
249
250
251
252
253
B000-GENERATE-REPORT1.
8 EXEC SQL
WHENEVER NOT FOUND GO TO A100-DONE1
END-EXEC.
9 EXEC SQL
FETCH C1 INTO :PROJECT.PROJNO, :RPT1.EMPNO,
:RPT1.NAME, :RPT1.SALARY
END-EXEC.
MOVE CORRESPONDING RPT1 TO RPT1-DATA.
254
255
256
257
258
259
260
MOVE PROJNO OF RPT1 TO PROJNO OF RPT1-DATA.
WRITE PRINT-RECORD FROM RPT1-DATA
BEFORE ADVANCING 1 LINE.
B010-GENERATE-REPORT1-EXIT.
EXIT.
***************************************************************
* Fetch and write the rows to PRINTFILE.
*
***************************************************************
C000-GENERATE-REPORT2.
EXEC SQL
EXIT.
WHENEVER NOT FOUND GO TO A200-DONE2
END-EXEC.
12 EXEC SQL
FETCH C2 INTO :RPT2
END-EXEC.
MOVE CORRESPONDING RPT2 TO RPT2-DATA.
WRITE PRINT-RECORD FROM RPT2-DATA
BEFORE ADVANCING 1 LINE.
C010-GENERATE-REPORT2-EXIT.
***************************************************************
* Error occurred while updating table.
Inform user and
* roll back changes.
***************************************************************
*
*
***************************************************************
*
*
***************************************************************
-
E010-UPDATE-ERROR.
13 EXEC SQL exit.
WHENEVER SQLERROR CONTINUE
END-EXEC.
MOVE SQLCODE TO CODE-EDIT.
STRING "*** ERROR Occurred while updating table.
SQLCODE="
CODE-EDIT DELIMITED BY SIZE INTO PRINT-RECORD.
WRITE PRINT-RECORD.
14 EXEC SQL
ROLLBACK
END-EXEC.
STOP RUN.
Error occurred while generating reports.
E020-REPORT-ERROR.
MOVE SQLCODE TO CODE-EDIT.
Inform user and *
*
STRING "*** ERROR Occurred while generating reports.
SQLCODE
"=" CODE-EDIT DELIMITED BY SIZE INTO PRINT-RECORD.
WRITE PRINT-RECORD.
STOP RUN.
* * * * * E N D O F S O U R C E * * * * *
Embedded SQL programming
163
xxxxST1 VxRxMx yymmdd
CROSS REFERENCE
Data Names
ACTNO
A100-DONE1
A200-DONE2
BIRTHDATE
BONUS
CODE-EDIT
COMM
COMM
COMMISSION
CORPDATA
C1
C2
DEPTNO
DEPTNO
EDLEVEL
EMENDATE
EMENDATE
EMPLOYEE
EMPLOYEE
EMPLOYEE-COUNT
EMPLOYEE-COUNT
EMPNO
EMPNO
EMPNO
EMPNO
EMPNO
EMPNO
EMPPROJACT
EMPPROJACT
EMPTIME
EMPTIME
EMSTDATE
EMSTDATE
E010-UPDATE-ERROR
E020-REPORT-ERROR
FIRSTNME
FIRSTNME
HIREDATE
JOB
LASTNAME
LASTNAME
MAJPROJ
MAJPROJ
MIDINIT
NAME
NAME
Create SQL COBOL Program
Define
168
****
****
134
134
69
****
Reference
LABEL
CBLEX
247
LABEL
267
DATE(10) COLUMN IN CORPDATA.EMPLOYEE
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
08/06/07 11:09:13 Page
SMALL INTEGER PRECISION(4,0) COLUMN (NOT NULL) IN CORPDATA.EMPPROJACT
7
134
43
****
165
209
50
213
134
168
****
****
****
63
114
51
103
134
****
****
168
****
****
168
****
168
****
****
****
134
****
134
134
134
****
50
213
134
52
105
COLUMN
136 170
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
DECIMAL(7,2)
136 170
SCHEMA
134 168 168 213 213 214
CURSOR
174 182 250
CURSOR
222 230 270
CHARACTER(3) IN PROJECT
CHARACTER(3) COLUMN (NOT NULL) IN CORPDATA.PROJECT
SMALL INTEGER PRECISION(4,0) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
DATE(10) COLUMN IN CORPDATA.EMPPROJACT
COLUMN
211
TABLE IN CORPDATA
134 168 214
TABLE
169 216
SMALL INTEGER PRECISION(4,0) IN RPT2
IN RPT2-DATA
CHARACTER(6) IN RPT1
250
CHARACTER(6) IN RPT1-DATA
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
COLUMN IN EMPPROJACT
166 169 171 216
COLUMN IN EMPLOYEE
169 216
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPPROJACT
TABLE
166 169 210 215 216 218
TABLE IN CORPDATA
168 213
DECIMAL(5,2) COLUMN IN CORPDATA.EMPPROJACT
COLUMN
212
DATE(10) COLUMN IN CORPDATA.EMPPROJACT
COLUMN
211
LABEL
131
LABEL
148
VARCHAR(12) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
COLUMN
167
DATE(10) COLUMN IN CORPDATA.EMPLOYEE
CHARACTER(8) COLUMN IN CORPDATA.EMPLOYEE
VARCHAR(15) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
COLUMN
167
CHARACTER(6) IN PROJECT
CHARACTER(6) COLUMN IN CORPDATA.PROJECT
CHARACTER(1) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
CHARACTER(30) IN RPT1
251
CHARACTER(30) IN RPT1-DATA
164
IBM i: Embedded SQL programming
xxxxST1 VxRxMx yymmdd
CROSS REFERENCE
PERCENTAGE
PHONENO
PRENDATE
PRENDATE
PRENDATE
PRINT-RECORD
PROJECT
PROJECT
PROJECT
PROJECT-NAME
PROJECT-NAME
PROJNAME
PROJNAME
PROJNAME
PROJNO
PROJNO
PROJNO
PROJNO
PROJNO
PROJNO
PROJNO
PROJNO
PROJNO
PRSTAFF
PRSTAFF
PRSTDATE
PRSTDATE
RAISE-DATE
Create SQL COBOL Program
42
134
50
****
213
37
50
****
****
62
112
50
****
213
50
61
101
110
****
168
****
****
213
50
213
50
213
41
CBLEX
RESPEMP
RESPEMP
RPT1
RPT1-DATA
RPT1-HEADERS
RPT1-HEADER1
RPT1-HEADER2
RPT2
50
213
49
100
75
76
80
60
IN RPT1-HEADERS
IN RPT1-HEADERS
STRUCTURE
270
RPT2-DATA
SS REFERENCE
RPT2-HEADERS
RPT2-HEADER1
RPT2-HEADER2
RPT2-HEADER3
SALARY
SALARY
SALARY
SALARY
SEX
TOTAL-PROJ-COST
TOTAL-PROJ-COST
WORK-DAYS
109
85
86
90
95
53
107
****
134
134
64
116
40
IN RPT2-HEADERS
IN RPT2-HEADERS
IN RPT2-HEADERS
DECIMAL(8,2) IN RPT1
251
IN RPT1-DATA
COLUMN
135 135 167 212
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
CHARACTER(1) COLUMN IN CORPDATA.EMPLOYEE
DECIMAL(12,2) IN RPT2
IN RPT2-DATA
SMALL INTEGER PRECISION(4,0)
212
CHARACTER(3) COLUMN IN CORPDATA.EMPLOYEE
WORKDEPT
No errors found in source
307 Source records processed
134
* * * * * E N D O F L I S T I N G * * * * *
08/06/07 11:09:13
DECIMAL(5,2)
135
CHARACTER(4) COLUMN IN CORPDATA.EMPLOYEE
DATE(10) IN PROJECT
COLUMN
217
DATE(10) COLUMN IN CORPDATA.PROJECT
CHARACTER(132)
STRUCTURE IN RPT1
TABLE IN CORPDATA
213
TABLE
215
CHARACTER(36) IN RPT2
CHARACTER(36) IN RPT2-DATA
VARCHAR(24) IN PROJECT
COLUMN
210 218
VARCHAR(24) COLUMN (NOT NULL) IN CORPDATA.PROJECT
CHARACTER(6) IN PROJECT
250
CHARACTER(6) IN RPT2
CHARACTER(6) IN RPT1-DATA
CHARACTER(6) IN RPT2-DATA
COLUMN
166 171
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPPROJACT
COLUMN IN EMPPROJACT
210 215 218
COLUMN IN PROJECT
215
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.PROJECT
DECIMAL(5,2) IN PROJECT
DECIMAL(5,2) COLUMN IN CORPDATA.PROJECT
DATE(10) IN PROJECT
DATE(10) COLUMN IN CORPDATA.PROJECT
CHARACTER(11)
217
CHARACTER(6) IN PROJECT
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.PROJECT
Page 8
Related concepts
:
Embedded SQL programming
165
“Coding SQL statements in COBOL applications” on page 44
There are unique application and coding requirements for embedding SQL statements in a COBOL program. In this topic, requirements for host structures and host variables are defined.
Example: SQL statements in PL/I programs
This example program is written in the PL/I programming language.
Note:
08/06/07 12:53:36 Page 1 xxxxST1 VxRxMx yymmdd Create SQL PL/I Program
Source type...............PLI
Program name..............CORPDATA/PLIEX
Source file...............CORPDATA/SRC
Member....................PLIEX
To source file............QTEMP/QSQLTEMP
*XREF Options...................*SRC
Target release............VxRxMx
INCLUDE file..............*SRCFILE
Commit....................*CHG
Allow copy of data........*YES
Close SQL cursor..........*ENDPGM
Allow blocking............*READ
Delay PREPARE.............*NO
Generation level..........10
Margins...................*SRCFILE
Printer file..............*LIBL/QSYSPRT
Date format...............*JOB
Date separator............*JOB
Time format...............*HMS
Time separator ...........*JOB
Replace...................*YES
Relational database.......*LOCAL
User .....................*CURRENT
RDB connect method........*DUW
Default collection........*NONE
Dynamic default collection..............*NO
Package name..............*PGMLIB/*PGM
Path......................*NAMING
SQL rules.................*DB2
User profile..............*NAMING
Dynamic user profile......*USER
Sort sequence.............*JOB
Language ID...............*JOB
IBM SQL flagging..........*NOFLAG
ANS flagging..............*NONE
Text......................*SRCMBRTXT
Source file CCSID.........65535
Job CCSID.................65535
Decimal result options:
Maximum precision.......31
Maximum scale...........31
Minimum divide scale....0
DECFLOAT rounding mode....*HALFEVEN
Compiler options..........*NONE
Source member changed on 07/01/96 12:53:08
Figure 5. Sample PL/I program using SQL statements
PLIEX
166
IBM i: Embedded SQL programming
xxxxST1 VxRxMx yymmdd Create SQL PL/I Program PLIEX 08/06/07 12:53:36 Page 2
Record *...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 SEQNBR Last change
39
40
41
42
43
44
45
35
36
37
38
31
32
33
34
9
10
11
12
13
14
15
7
8
5
6
3
4
1
2
/* A sample program that updates the salaries for those employees
/* whose current commission total is greater than or equal to the
*/
*/
/* value of COMMISSION. The salaries of those who qualify are */
/* increased by the value of PERCENTAGE, retroactive to RAISE_DATE.
*/
/* A report is generated showing the projects that these employees */
/* have contributed to, ordered by project number and employee ID.
*/
/* A second report shows each project having an end date occurring */
/* after RAISE_DATE (that is, those projects potentially affected */
/* by the retroactive raises) with its total salary expenses and a */
/* count of employees who contributed to the project.
*/
/*********************************************************************/
PLIEX: PROC;
20
21
22
23
16
17
18
19
DCL RAISE_DATE CHAR(10);
DCL WORK_DAYS FIXED BIN(15);
DCL COMMISSION FIXED DECIMAL(8,2);
DCL PERCENTAGE FIXED DECIMAL(5,2);
/* File declaration for sysprint */
DCL SYSPRINT FILE EXTERNAL OUTPUT STREAM PRINT;
24
25
/* Structure for report 1 */
DCL 1 RPT1,
26 1%INCLUDE PROJECT (PROJECT, RECORD,,COMMA);
27 15 EMPNO CHAR(6),
28
29
30
15 NAME
15 SALARY
CHAR(30),
FIXED DECIMAL(8,2);
/* Structure for report 2 */
DCL 1 RPT2,
15 PROJNO
15 PROJECT_NAME
CHAR(6),
CHAR(36),
15 EMPLOYEE_COUNT FIXED BIN(15),
15 TOTL_PROJ_COST FIXED DECIMAL(10,2);
2 EXEC SQL INCLUDE SQLCA;
COMMISSION = 2000.00;
PERCENTAGE = 1.04;
RAISE_DATE = ’1982-06-01’;
WORK_DAYS = 253;
OPEN FILE(SYSPRINT);
50
51
52
53
46
47
/* Update the selected employees’ salaries by the new percentage. */
/* If an error occurs during the update, roll back the changes.
*/
48 3 EXEC SQL WHENEVER SQLERROR GO TO UPDATE_ERROR;
49 4 EXEC SQL
UPDATE CORPDATA/EMPLOYEE
SET SALARY = SALARY * :PERCENTAGE
WHERE COMM >= :COMMISSION ;
54 /* Commit changes */
55 5 EXEC SQL
56
57
58
COMMIT;
EXEC SQL WHENEVER SQLERROR GO TO REPORT_ERROR;
4600
4700
4800
4900
5000
5100
5200
5300
5400
5500
5600
5700
5800
3900
4000
4100
4200
4300
4400
4500
3100
3200
3300
3400
3500
3600
3700
3800
2400
2500
2600
2700
2800
2900
3000
1600
1700
1800
1900
2000
2100
2200
2300
900
1000
1100
1200
1300
1400
1500
100
200
300
400
500
600
700
800
Embedded SQL programming
167
xxxxST1 VxRxMx yymmdd Create SQL PL/I Program PLIEX 08/06/07 12:53:36 Page 3
Record *...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 SEQNBR Last change
59 /* Report the updated statistics for each project supported by one */ 5900
*/ 60
61
62
63
/* of the selected employees.
64
65
66
67
/* Write out the header for Report 1 */ put file(sysprint) edit(’REPORT OF PROJECTS AFFECTED BY EMPLOYEE RAISES’)
(col(22),a); put file(sysprint) edit(’PROJECT’,’EMPID’,’EMPLOYEE NAME’,’SALARY’)
(skip(2),col(1),a,col(10),a,col(20),a,col(55),a); 68
69
70 6 exec sql
71 declare c1 cursor for
6000
6100
6200
6300
6400
6500
6600
6700
6800
6900
7000
7100
72
73
74 select DISTINCT projno, EMPPROJACT.empno, lastname||’, ’||firstnme, salary from CORPDATA/EMPPROJACT, CORPDATA/EMPLOYEE
75
76
79
80 where EMPPROJACT.empno = EMPLOYEE.empno and comm >= :COMMISSION
77
78 7 EXEC SQL order by projno, empno;
OPEN C1;
7200
7300
7400
7500
7600
7700
7800
81 /* Fetch and write the rows to SYSPRINT */
82 8 EXEC SQL WHENEVER NOT FOUND GO TO DONE1;
83
84
85
86
87
88
89
DO UNTIL (SQLCODE ^= 0);
9 EXEC SQL
FETCH C1 INTO :RPT1.PROJNO, :rpt1.EMPNO, :RPT1.NAME,
PUT FILE(SYSPRINT)
:RPT1.SALARY;
EDIT(RPT1.PROJNO,RPT1.EMPNO,RPT1.NAME,RPT1.SALARY)
7900
8000
8100
8200
8300
8400
8500
8600
8700
8800
8900
105
106
107
108
109
110
111
112
100
101
102
103
104
96
97
98
99
90
91
92
93
END;
(SKIP,COL(1),A,COL(10),A,COL(20),A,COL(54),F(8,2));
DONE1:
94 10 EXEC SQL
95 CLOSE C1;
/* For all projects ending at a date later than ’raise_date’
/* (that is, those projects potentially affected by the salary
/* raises), generate a report containing the project number,
/* project name, the count of employees participating in the
/* project, and the total salary cost of the project.
/* Write out the header for Report 2 */
PUT FILE(SYSPRINT) EDIT(’ACCUMULATED STATISTICS BY PROJECT’)
(SKIP(3),COL(22),A);
PUT FILE(SYSPRINT)
EDIT(’PROJECT’,’NUMBER OF’,’TOTAL’)
(SKIP(2),COL(1),A,COL(48),A,COL(63),A);
PUT FILE(SYSPRINT)
EDIT(’NUMBER’,’PROJECT NAME’,’EMPLOYEES’,’COST’)
(SKIP,COL(1),A,COL(10),A,COL(48),A,COL(63),A,SKIP);
*/
*/
*/
*/
*/
9000
9100
9200
9300
9400
9500
9600
9700
9800
9900
10000
10100
10200
10300
10400
10500
10600
10700
10800
10900
11000
11100
11200
168
IBM i: Embedded SQL programming
137
138
139
140
141
142
143
129
130
131
132
133
134
135
136 xxxxST1 VxRxMx yymmdd Create SQL PL/I Program PLIEX 08/06/07 12:53:36 Page 4
Record *...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 SEQNBR Last change
113 11 EXEC SQL 11300
114
115
116
117
DECLARE C2 CURSOR FOR
SELECT EMPPROJACT.PROJNO, PROJNAME, COUNT(*),
SUM( (DAYS(EMENDATE) - DAYS(EMSTDATE)) * EMPTIME *
DECIMAL(( SALARY / :WORK_DAYS ),8,2) )
11400
11500
11600
11700
118
119
120
121
122
123
124
125
126
127
128
FROM CORPDATA/EMPPROJACT, CORPDATA/PROJECT, CORPDATA/EMPLOYEE
WHERE EMPPROJACT.PROJNO=PROJECT.PROJNO
GROUP BY EMPPROJACT.PROJNO, PROJNAME
ORDER BY 1;
EXEC SQL
OPEN C2;
EMPPROJACT.EMPNO =EMPLOYEE.EMPNO
PRENDATE > :RAISE_DATE
/* Fetch and write the rows to SYSPRINT */
EXEC SQL WHENEVER NOT FOUND GO TO DONE2;
AND
AND
11800
11900
12000
12100
12200
12300
12400
12500
12600
12700
12800
DO UNTIL (SQLCODE ^= 0);
12 EXEC SQL
PUT FILE(SYSPRINT)
END;
DONE2:
FETCH C2 INTO :RPT2;
EDIT(RPT2.PROJNO,RPT2.PROJECT_NAME,EMPLOYEE_COUNT,
EXEC SQL
TOTL_PROJ_COST)
(SKIP,COL(1),A,COL(10),A,COL(50),F(4),COL(62),F(8,2));
CLOSE C2;
GO TO FINISHED;
12900
13000
13100
13200
13300
13400
13500
13600
13700
13800
13900
14000
14100
14200
14300
159
160
161
162
163
164
165
154
155
156
157
158
144
145
/* Error occurred while updating table. Inform user and roll back */
/* changes.
*/
146 UPDATE_ERROR:
147 13 EXEC SQL WHENEVER SQLERROR CONTINUE;
148
149
152
153
PUT FILE(SYSPRINT) EDIT(’*** ERROR Occurred while updating table.’||
’ SQLCODE=’,SQLCODE)(A,F(5));
150 14 EXEC SQL
151 ROLLBACK;
GO TO FINISHED;
/* Error occurred while generating reports.
Inform user and exit.
*/
REPORT_ERROR:
PUT FILE(SYSPRINT) EDIT(’*** ERROR Occurred while generating ’||
’reports.
SQLCODE=’,SQLCODE)(A,F(5));
GO TO FINISHED;
/* All done
FINISHED:
*/
CLOSE FILE(SYSPRINT);
RETURN;
END PLIEX;
* * * * * E N D O F S O U R C E * * * * *
14400
14500
14600
14700
14800
14900
15000
15100
15200
15300
15400
15500
15600
15700
15800
15900
16000
16100
16200
16300
16400
16500
Embedded SQL programming
169
FIRSTNME
FIRSTNME
HIREDATE
JOB
LASTNAME
LASTNAME
MAJPROJ
MAJPROJ
MIDINIT
NAME
PERCENTAGE
PHONENO
EMPLOYEE
EMPLOYEE
EMPLOYEE_COUNT
EMPNO
EMPNO
EMPNO
EMPNO
EMPNO
EMPPROJACT
EMPPROJACT
EMPTIME
EMPTIME
EMSTDATE
EMSTDATE xxxxST1 VxRxMx yymmdd
CROSS REFERENCE
Data Names
ACTNO
BIRTHDATE
BONUS
COMM
COMM
COMMISSION
CORPDATA
C1
C2
DEPTNO
DEPTNO
DONE1
DONE2
EDLEVEL
EMENDATE
EMENDATE
Create SQL PL/I Program
Define
74
74
74
****
74
18
****
71
114
26
118
****
****
74
74
****
****
****
35
27
****
****
74
74
****
****
74
****
74
****
****
74
74
74
****
74
26
118
74
28
19
74
Reference
COLUMN
PLIEX
DATE(10) COLUMN IN CORPDATA.EMPLOYEE
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
52 76
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
DECIMAL(8,2)
52 76
SCHEMA
50 74 74 118 118 118
CURSOR
79 86 95
CURSOR
125 132 141
CHARACTER(3) IN RPT1
08/06/07 12:53:36
COLUMN
116
COLUMN
73
VARCHAR(12) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
DATE(10) COLUMN IN CORPDATA.EMPLOYEE
CHARACTER(8) COLUMN IN CORPDATA.EMPLOYEE
COLUMN
73
VARCHAR(15) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
CHARACTER(6) IN RPT1
CHARACTER(6) COLUMN IN CORPDATA.PROJECT
CHARACTER(1) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
CHARACTER(30) IN RPT1
86
DECIMAL(5,2)
51
CHARACTER(4) COLUMN IN CORPDATA.EMPLOYEE
Page
SMALL INTEGER PRECISION(4,0) COLUMN (NOT NULL) IN CORPDATA.EMPPROJACT
CHARACTER(3) COLUMN (NOT NULL) IN CORPDATA.PROJECT
LABEL
82
LABEL
128
SMALL INTEGER PRECISION(4,0) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
DATE(10) COLUMN IN CORPDATA.EMPPROJACT
COLUMN
116
TABLE IN CORPDATA
50 74 118
TABLE
75 120
SMALL INTEGER PRECISION(4,0) IN RPT2
CHARACTER(6) IN RPT1
86
COLUMN IN EMPPROJACT
72 75 77 120
COLUMN IN EMPLOYEE
75 120
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPPROJACT
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
TABLE
72 75 115 119 120 122
TABLE IN CORPDATA
74 118
DECIMAL(5,2) COLUMN IN CORPDATA.EMPPROJACT
COLUMN
116
DATE(10) COLUMN IN CORPDATA.EMPPROJACT
5
170
IBM i: Embedded SQL programming
xxxxST1 VxRxMx yymmdd
CROSS REFERENCE
PRENDATE
PRENDATE
PRENDATE
PROJECT
PROJECT
PROJECT_NAME
PROJNAME
PROJNAME
PROJNAME
PROJNO
PROJNO
PROJNO
PROJNO
PROJNO
PROJNO
PROJNO
PRSTAFF
PRSTAFF
PRSTDATE
PRSTDATE
RAISE_DATE
REPORT_ERROR
RESPEMP
RESPEMP
RPT1
RPT2
SALARY
SALARY
Create SQL PL/I Program
26
****
118
****
****
34
26
****
118
26
33
****
74
****
****
118
26
118
26
118
16
****
26
118
25
32
29
****
PLIEX
SALARY
SEX
SYSPRINT
TOTL_PROJ_COST
UPDATE_ERROR
WORK_DAYS
74
74
22
36
****
17
DECIMAL(10,2) IN RPT2
LABEL
48
SMALL INTEGER PRECISION(4,0)
117
CHARACTER(3) COLUMN IN CORPDATA.EMPLOYEE
WORKDEPT
No errors found in source
165 Source records processed
74
* * * * * E N D O F L I S T I N G * * * * *
08/06/07 12:53:36
DATE(10) IN RPT1
COLUMN
121
DATE(10) COLUMN IN CORPDATA.PROJECT
TABLE IN CORPDATA
118
TABLE
119
CHARACTER(36) IN RPT2
VARCHAR(24) IN RPT1
COLUMN
115 122
VARCHAR(24) COLUMN (NOT NULL) IN CORPDATA.PROJECT
CHARACTER(6) IN RPT1
86
CHARACTER(6) IN RPT2
COLUMN
72 77
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPPROJACT
COLUMN IN EMPPROJACT
115 119 122
COLUMN IN PROJECT
119
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.PROJECT
DECIMAL(5,2) IN RPT1
DECIMAL(5,2) COLUMN IN CORPDATA.PROJECT
DATE(10) IN RPT1
DATE(10) COLUMN IN CORPDATA.PROJECT
CHARACTER(10)
121
LABEL
57
CHARACTER(6) IN RPT1
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.PROJECT
STRUCTURE
STRUCTURE
132
DECIMAL(8,2) IN RPT1
87
COLUMN
51 51 73 117
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
CHARACTER(1) COLUMN IN CORPDATA.EMPLOYEE
Page 6
Related concepts
:
“Coding SQL statements in PL/I applications” on page 73
There are some unique application and coding requirements for embedding SQL statements in a PL/I program. In this topic, requirements for host structures and host variables are defined.
Example: SQL statements in RPG/400 programs
This example program is written in the RPG programming language.
Note:
Embedded SQL programming
171
xxxxST1 VxRxMx yymmdd Create SQL RPG Program
Source type...............RPG
Program name..............CORPDATA/RPGEX
Source file...............CORPDATA/SRC
Member....................RPGEX
To source file............QTEMP/QSQLTEMP
Options...................*SRC *XREF
Target release............VxRxMx
INCLUDE file..............*SRCFILE
Commit....................*CHG
Allow copy of data........*YES
Close SQL cursor..........*ENDPGM
Allow blocking............*READ
Delay PREPARE.............*NO
Generation level..........10
Printer file..............*LIBL/QSYSPRT
Date format...............*JOB
Date separator............*JOB
Time format...............*HMS
Time separator ...........*JOB
Replace...................*YES
Relational database.......*LOCAL
User .....................*CURRENT
RDB connect method........*DUW
Default collection........*NONE
Dynamic default collection..............*NO
Package name..............*PGMLIB/*PGM
Path......................*NAMING
SQL rules.................*DB2
User profile..............*NAMING
Dynamic user profile......*USER
Sort sequence.............*JOB
Language ID...............*JOB
IBM SQL flagging..........*NOFLAG
ANS flagging..............*NONE
Text......................*SRCMBRTXT
Source file CCSID.........65535
Job CCSID.................65535
Decimal result options:
Maximum precision.......31
Maximum scale...........31
Minimum divide scale....0
DECFLOAT rounding mode....*HALFEVEN
Compiler options..........*NONE
Source member changed on 07/01/96 17:06:17
Figure 6. Sample RPG/400 program using SQL statements
RPGEX 08/06/07 12:55:22 Page 1
172
IBM i: Embedded SQL programming
51
52
53
54
47
48
49
50
55
56
57
58
59
60
40
41
42
43
44
45
46
36
37
38
39
32
33
34
35
25
26
27
28
29
30
31
21
22
23
24
17
18
19
20 xxxxST1 VxRxMx yymmdd Create SQL RPG Program RPGEX 08/06/07 12:55:22 Page 2
Record *...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 SEQNBR Last change
1 H 100
2
3
4
5
F* File declaration for QPRINT
F*
FQPRINT
I*
O F 132 PRINTER
200
300
400
500
10
11
12
13
14
15
16
8
9
6
7
I* Structure for report 1.
I*
1 IRPT1
I
I
I
I
I
I
I*
I
E DSPROJECT
DS
PROJNAME
RESPEMP
PRSTAFF
PRSTDATE
PRENDATE
MAJPROJ
PROJNM
RESEM
STAFF
PRSTD
PREND
MAJPRJ
600
700
800
900
1000
1100
1200
1300
1400
1500
1600
I
I
I
I*
I* Structure for report 2.
I*
IRPT2
I
DS
P
1
7
37
6 EMPNO
36 NAME
412SALARY
I
I
I
I*
B
P
1 6 PRJNUM
7
43
45
42 PNAME
440EMPCNT
492PRCOST
I
I
I
I
I
2 C*
C
DS
B 1 20WRKDAY
P 3 62COMMI
P
7
17
16 RDATE
202PERCNT
C
C
C
C
Z-ADD253
Z-ADD2000.00
Z-ADD1.04
WRKDAY
COMMI
PERCNT
MOVEL’1982-06-’RDATE
MOVE ’01’ RDATE
SETON C
C*
LR
C* Update the selected projects by the new percentage. If an
C* error occurs during the update, roll back the changes.
C*
3 C/EXEC SQL WHENEVER SQLERROR GOTO UPDERR
C/END-EXEC
C*
4 C/EXEC SQL
C+ UPDATE CORPDATA/EMPLOYEE
C+ SET SALARY = SALARY * :PERCNT
C+ WHERE COMM >= :COMMI
C/END-EXEC
C*
C* Commit changes.
C*
5 C/EXEC SQL COMMIT
C/END-EXEC
C*
C/EXEC SQL WHENEVER SQLERROR GO TO RPTERR
C/END-EXEC
1700
1800
1900
2000
2100
2200
2300
2400
2500
2600
2700
2800
2900
3000
3100
3200
3300
3400
3500
3600
3700
3800
3900
3901
4000
4100
4200
4300
4400
4500
4600
4700
4800
4900
5000
5100
5200
5300
5400
5500
5600
5700
5800
5900
Embedded SQL programming
173
115
116
117
118
119
120
121
122
123
124
107
108
109
110
111
112
113
114
100
101
102
103
104
105
106
96
97
98
99
92
93
94
95
85
86
87
88
89
90
91
81
82
83
84
77
78
79
80 xxxxST1 VxRxMx yymmdd Create SQL RPG Program RPGEX 08/06/07 12:55:22 Page 3
Record *...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 SEQNBR Last change
61 C* 6000
62
63
64
65
C* Report the updated statistics for each employee assigned to
C* selected projects.
C*
C* Write out the header for report 1.
6100
6200
6300
6400
70
71
72
73
66
67
68
69
74
75
76
C*
C
6 C/EXEC SQL DECLARE C1 CURSOR FOR
C+ SELECT DISTINCT PROJNO, EMPPROJACT.EMPNO,
C+
C+
C+
C+
EXCPTRECA
LASTNAME||’, ’||FIRSTNME, SALARY
FROM CORPDATA/EMPPROJACT, CORPDATA/EMPLOYEE
WHERE EMPPROJACT.EMPNO = EMPLOYEE.EMPNO AND
COMM >= :COMMI
C+
C/END-EXEC
ORDER BY PROJNO, EMPNO
C*
6500
6600
6700
6800
6900
7000
7100
7200
7300
7400
7500
7 C/EXEC SQL
C+ OPEN C1
C/END-EXEC
C*
C* Fetch and write the rows to QPRINT.
C*
8 C/EXEC SQL WHENEVER NOT FOUND GO TO DONE1
C/END-EXEC
C
C/EXEC SQL
SQLCOD DOUNE0
9 C+ FETCH C1 INTO :PROJNO, :EMPNO, :NAME, :SALARY
C/END-EXEC
C
C
C
C/EXEC SQL
10 C+ CLOSE C1
DONE1
EXCPTRECB
END
TAG
7600
7700
7800
7900
8000
8100
8200
8300
8400
8500
8600
8700
8800
8900
9000
C/END-EXEC
C*
C* For all project ending at a date later than the raise date
C* (that is, those projects potentially affected by the salary raises),
C* generate a report containing the project number, project name,
C* the count of employees participating in the project, and the
C* total salary cost of the project.
C*
C* Write out the header for report 2.
C*
C
11 C/EXEC SQL
EXCPTRECC
C+ DECLARE C2 CURSOR FOR
9900
10000
10100
10200
10300
10400
10500
9100
9200
9300
9400
9500
9600
9700
9800
C+
C+
C+
C+
C+
C+
C+
C+
SELECT EMPPROJACT.PROJNO, PROJNAME, COUNT(*),
SUM((DAYS(EMENDATE) - DAYS(EMSTDATE)) * EMPTIME *
DECIMAL((SALARY/:WRKDAY),8,2))
FROM CORPDATA/EMPPROJACT, CORPDATA/PROJECT, CORPDATA/EMPLOYEE
WHERE EMPPROJACT.PROJNO = PROJECT.PROJNO AND
EMPPROJACT.EMPNO = EMPLOYEE.EMPNO AND
PRENDATE > :RDATE
GROUP BY EMPPROJACT.PROJNO, PROJNAME
C+ ORDER BY 1
C/END-EXEC
C*
C/EXEC SQL OPEN C2
C/END-EXEC
C*
C* Fetch and write the rows to QPRINT.
C*
C/EXEC SQL WHENEVER NOT FOUND GO TO DONE2
C/END-EXEC
11400
11500
11600
11700
11800
11900
12000
12100
12200
12300
10600
10700
10800
10900
11000
11100
11200
11300
174
IBM i: Embedded SQL programming
172
173
174
175
176
177
178
179
180
181
182
183
184
165
166
167
168
169
170
171
157
158
159
160
161
162
163
164
185
186
187
188
189
190
191
192
193
194
195
196
150
151
152
153
154
155
156
142
143
144
145
146
147
148
149 xxxxST1 VxRxMx yymmdd
125 C
126 C/EXEC SQL
127
128
129
130
12 C+
C
C
Create SQL RPG Program
SQLCOD DOUNE0
FETCH C2 INTO :RPT2
C/END-EXEC
EXCPTRECD
END
131
132
133
134
135
136
137
138
139
140
141
C DONE2
C/EXEC SQL CLOSE C2
C/END-EXEC
C
TAG
RPGEX
RETRN
C*
C* Error occurred while updating table.
Inform user and roll back
C* changes.
C*
C
C
UPDERR TAG
EXCPTRECE
13 C/EXEC SQL WHENEVER SQLERROR CONTINUE
08/06/07 12:55:22 Page 4
12400
12500
12600
12700
12800
12900
13000
13100
13200
13300
13400
13500
13600
13700
13800
13900
14000
C/END-EXEC
C*
14 C/EXEC SQL
C+ ROLLBACK
C*
C
C
C*
C/END-EXEC
C RETRN
C*
C* Error occurred while generating reports.
Inform user and exit.
RPTERR
C* All done.
C*
C FINISH
TAG
EXCPTRECF
TAG
14100
14200
14300
14400
14500
14600
14700
14800
14900
15000
15100
15200
15300
15400
15500
O
O
O
O
O
O
O
O
O
O
O
O
O
O
O
O
O
O
O
O
O
O
O
O
O
O
OQPRINT E 0201
O
E 01
E 01
O
O
O
O
O
O
O
O
O
O
O
O
E 22
E 01
E 02
E 01
E 01
E 01
RECA
45 ’REPORT OF PROJECTS AFFEC’
64 ’TED BY EMPLOYEE RAISES’
RECA
7 ’PROJECT’
17 ’EMPLOYEE’
32 ’EMPLOYEE NAME’
60 ’SALARY’
RECB
PROJNO
EMPNO
NAME
6
15
50
SALARYL 61
RECC
42 ’ACCUMULATED STATISTIC’
54 ’S BY PROJECT’
RECC
7 ’PROJECT’
56 ’NUMBER OF’
67 ’TOTAL’
RECC
6 ’NUMBER’
21 ’PROJECT NAME’
56 ’EMPLOYEES’
66 ’COST’
RECD
PRJNUM
PNAME
EMPCNTL 54
PRCOSTL 70
RECE
6
45
28 ’*** ERROR Occurred while’
52 ’ updating table. SQLCODE’
53 ’=’
SQLCODL 62
RECF
28 ’*** ERROR Occurred while’
52 ’ generating reports. SQL’
57 ’CODE=’
SQLCODL 67
* * * * * E N D O F S O U R C E * * * * *
17200
17300
17400
17500
17600
17700
17800
17900
18000
18100
18200
18300
18400
15700
15800
15900
16000
16100
16200
16300
16400
16500
16600
16700
16800
16900
17000
17100
18500
18600
18700
18800
18900
19000
19100
19200
19300
19400
19500
19600
Embedded SQL programming
175
EMPPROJACT
EMPTIME
EMPTIME
EMSTDATE
EMSTDATE
FINISH
FIRSTNME
FIRSTNME
HIREDATE
JOB
LASTNAME
LASTNAME
MAJPRJ
MAJPROJ
MIDINIT
NAME
PERCNT
PHONENO
PNAME
PRCOST
PREND
PRENDATE
EDLEVEL
EMENDATE
EMENDATE
EMPCNT
EMPLOYEE
EMPLOYEE
EMPNO
EMPNO
EMPNO
EMPNO
EMPNO
EMPPROJACT xxxxST1 VxRxMx yymmdd
CROSS REFERENCE
Data Names
ACTNO
BIRTHDATE
BONUS
COMM
COMM
COMMI
CORPDATA
C1
C2
DEPTNO
DEPTNO
DONE1
DONE2
Create SQL RPG Program
Define
68
48
48
****
48
31
****
68
105
8
105
91
131
48
68
****
26
****
****
17
48
****
****
68
****
****
68
****
68
****
156
48
****
48
48
48
****
8
105
48
18
33
48
25
27
8
****
Reference
RPGEX 08/06/07 12:55:22 Page 5
SMALL INTEGER PRECISION(4,0) COLUMN (NOT NULL) IN CORPDATA.EMPPROJACT
DATE(10) COLUMN IN CORPDATA.EMPLOYEE
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
COLUMN
48 68
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
DECIMAL(7,2)
48 68
SCHEMA
48 68 68 105 105 105
CURSOR
77 86 92
CURSOR
118 126 132
CHARACTER(3) IN RPT1
CHARACTER(3) COLUMN (NOT NULL) IN CORPDATA.PROJECT
LABEL
83
LABEL
123
SMALL INTEGER PRECISION(4,0) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
DATE(10) COLUMN IN CORPDATA.EMPPROJACT
COLUMN
105
SMALL INTEGER PRECISION(4,0) IN RPT2
TABLE IN CORPDATA
48 68 105
TABLE
68 105
CHARACTER(6)
86
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
COLUMN IN EMPPROJACT
68 68 68 105
COLUMN IN EMPLOYEE
68 105
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPPROJACT
TABLE
68 68 105 105 105 105
TABLE IN CORPDATA
68 105
DECIMAL(5,2) COLUMN IN CORPDATA.EMPPROJACT
COLUMN
105
DATE(10) COLUMN IN CORPDATA.EMPPROJACT
COLUMN
105
LABEL
VARCHAR(12) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
COLUMN
68
DATE(10) COLUMN IN CORPDATA.EMPLOYEE
CHARACTER(8) COLUMN IN CORPDATA.EMPLOYEE
VARCHAR(15) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
COLUMN
68
CHARACTER(6) IN RPT1
CHARACTER(6) COLUMN IN CORPDATA.PROJECT
CHARACTER(1) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
CHARACTER(30)
86
DECIMAL(7,2)
48
CHARACTER(4) COLUMN IN CORPDATA.EMPLOYEE
CHARACTER(36) IN RPT2
DECIMAL(9,2) IN RPT2
DATE(10) IN RPT1
COLUMN
105
176
IBM i: Embedded SQL programming
xxxxST1 VxRxMx yymmdd
PRENDATE
PRJNUM
CROSS REFERENCE
PROJECT
Create SQL RPG Program
105
24
DATE(10) COLUMN IN CORPDATA.PROJECT
CHARACTER(6) IN RPT2
RPGEX 08/06/07 12:55:22
PROJECT
PROJNAME
PROJNAME
PROJNM
PROJNO
PROJNO
PROJNO
PROJNO
PROJNO
PROJNO
PRSTAFF
PRSTD
PRSTDATE
RDATE
RESEM
RESPEMP
RPTERR
RPT1
RPT2
SALARY
SALARY
SALARY
SEX
STAFF
UPDERR
WORKDEPT
WRKDAY
****
****
****
105
8
8
****
68
****
****
105
105
8
105
32
8
105
151
8
23
19
****
48
48
8
139
48
30
TABLE IN CORPDATA
105
TABLE
105
COLUMN
105 105
VARCHAR(24) COLUMN (NOT NULL) IN CORPDATA.PROJECT
VARCHAR(24) IN RPT1
CHARACTER(6) IN RPT1
86
COLUMN
68 68
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPPROJACT
COLUMN IN EMPPROJACT
105 105 105
COLUMN IN PROJECT
105
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.PROJECT
DECIMAL(5,2) COLUMN IN CORPDATA.PROJECT
DATE(10) IN RPT1
DATE(10) COLUMN IN CORPDATA.PROJECT
CHARACTER(10)
105
CHARACTER(6) IN RPT1
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.PROJECT
LABEL
59
STRUCTURE
STRUCTURE
126
DECIMAL(9,2)
86
COLUMN
48 48 68 105
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
CHARACTER(1) COLUMN IN CORPDATA.EMPLOYEE
DECIMAL(5,2) IN RPT1
LABEL
45
CHARACTER(3) COLUMN IN CORPDATA.EMPLOYEE
SMALL INTEGER PRECISION(4,0)
105
No errors found in source
196 Source records processed
* * * * * E N D O F L I S T I N G * * * * *
Page 6
Related concepts
:
“Coding SQL statements in RPG/400 applications” on page 88
The RPG/400 licensed program supports both RPG II and RPG III programs.
Example: SQL statements in ILE RPG programs
This example program is written in the ILE RPG programming language.
Note:
Embedded SQL programming
177
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| xxxxST1 VxRxMx yymmdd
Source type...............RPG
Create SQL ILE RPG Object
Object name...............CORPDATA/RPGLEEX
Source file...............CORPDATA/SRC
Member....................*OBJ
To source file............QTEMP/QSQLTEMP1
Options...................*XREF
RPG preprocessor options..*NONE
Listing option............*PRINT
Target release............VxRxMx
INCLUDE file..............*SRCFILE
Commit....................*CHG
Allow copy of data........*OPTIMIZE
Close SQL cursor..........*ENDMOD
Allow blocking............*ALLREAD
Delay PREPARE.............*NO
Concurrent access resolution..............*DFT
Generation level..........10
Printer file..............*LIBL/QSYSPRT
Date format...............*JOB
Date separator............*JOB
Time format...............*HMS
Time separator ...........*JOB
Replace...................*YES
Relational database.......*LOCAL
User .....................*CURRENT
RDB connect method........*DUW
Default collection........*NONE
Dynamic default collection..............*NO
Package name..............*OBJLIB/*OBJ
Path......................*NAMING
SQL rules.................*DB2
Created object type.......*PGM
Debugging view............*NONE
Debugging encryption key..*NONE
User profile .............*NAMING
Dynamic user profile......*USER
Sort sequence.............*JOB
Language ID...............*JOB
IBM SQL flagging..........*NOFLAG
ANS flagging..............*NONE
Text......................*SRCMBRTXT
Source file CCSID.........37
Job CCSID.................37
Decimal result options:
Maximum precision.......31
Maximum scale...........31
Minimum divide scale....0
DECFLOAT rounding mode....*HALFEVEN
Compiler options..........*NONE
Figure 7. Sample ILE RPG program using SQL statements
RPGLEEX 11/11/13 11:23:30 Page 1
178
IBM i: Embedded SQL programming
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50
51
52
53
46
47
48
49
54
55
56
57
58
63
64
65
66
59
60
61
62
67
68
39
40
41
42
43
44
45
35
36
37
38
31
32
33
34
24
25
26
27
28
29
30
20
21
22
23
16
17
18
19
11
12
13
14
15
9
10
7
8
Source member changed on 11/11/13 11:20:02 xxxxST1 VxRxMx yymmdd Create SQL ILE RPG Object RPGLEEX 11/11/13 11:23:30
Record *...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 SEQNBR Last change
1
2
CTL-OPT;
// File declaration for QPRINT
000100
000200
5
6
3
4
//
DCL-F QPRINT PRINTER(132) USAGE(*OUTPUT);
//
// Structure for report 1.
000300
000400
000500
000600
1
//
DCL-DS RPT1 EXT EXTNAME(’CORPDATA/PROJECT’);
END-DS;
//
DCL-DS *N;
EMPNO CHAR(6);
NAME CHAR(30);
SALARY PACKED(9:2);
END-DS;
000700
000800
000900
001000
001100
001200
001300
001400
001500
//
// Structure for report 2.
//
DCL-DS RPT2;
PRJNUM CHAR(6);
PNAME CHAR(36);
EMPCNT BINDEC(4:0);
PRCOST PACKED(9:2);
END-DS;
//
DCL-DS *N;
WRKDAY BINDEC(4:0);
COMMI PACKED(7:2);
RDATE CHAR(10);
PERCNT PACKED(7:2);
END-DS;
//
2 WRKDAY = 253;
COMMI = 2000.00;
3
4
PERCNT = 1.04;
RDATE = ’1982-06-01’;
//
// Update the selected projects by the new percentage. If an
// error occurs during the update, roll back the changes.
//
EXEC SQL WHENEVER SQLERROR GOTO UPDERR;
//
EXEC SQL
UPDATE CORPDATA/EMPLOYEE
SET SALARY = SALARY * :PERCNT
001600
001700
001800
001900
002000
002100
002200
002300
002400
002500
002600
002700
002800
002900
003000
003100
003200
003300
003400
003500
003600
003700
003800
003900
004000
004100
004200
004300
004400
004500
5
WHERE COMM >= :COMMI;
//
// Commit changes.
//
EXEC SQL COMMIT;
//
EXEC SQL WHENEVER SQLERROR GO TO RPTERR;
//
// Report the updated statistics for each employee assigned to
// selected projects.
//
// Write out the header for report 1.
//
6
EXCEPT RECA;
EXEC SQL DECLARE C1 CURSOR FOR
SELECT DISTINCT PROJNO, EMPPROJACT.EMPNO,
LASTNAME||’, ’||FIRSTNME, SALARY
FROM CORPDATA/EMPPROJACT, CORPDATA/EMPLOYEE
WHERE EMPPROJACT.EMPNO = EMPLOYEE.EMPNO AND
COMM >= :COMMI
ORDER BY PROJNO, EMPNO;
//
7 EXEC SQL OPEN C1;
004600
004700
004800
004900
005000
005100
005200
005300
005400
005500
005600
005700
005800
005900
006000
006100
006200
006300
006400
006500
006600
006700
006800
Page
Comments
2
Embedded SQL programming
179
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
129
130
131
132
133
134
135
136
137
138
139
140
116
117
118
119
120
121
122
123
124
125
126
127
128
109
110
111
112
113
114
115
101
102
103
104
105
106
107
108
94
95
96
97
98
99
100
90
91
92
93
86
87
88
89 xxxxST1 VxRxMx yymmdd
69 //
70
Create SQL ILE RPG Object
// Fetch and write the rows to QPRINT.
71
72
73
74
8
9
//
EXEC SQL WHENEVER NOT FOUND GO TO DONE1;
DOU SQLCOD <> 0;
RPGLEEX
EXEC SQL FETCH C1 INTO :PROJNO, :EMPNO, :NAME, :SALARY;
79
80
81
82
75
76
77
78
83
84
85
10
C
EXCEPT RECB;
ENDDO;
DONE1 TAG
EXEC SQL CLOSE C1;
//
// For all project ending at a date later than the raise date
// (that is, those projects potentially affected by the salary raises),
// generate a report containing the project number, project name,
// the count of employees participating in the project, and the
// total salary cost of the project.
//
11
// Write out the header for report 2.
//
EXCEPT RECC;
EXEC SQL
DECLARE C2 CURSOR FOR
SELECT EMPPROJACT.PROJNO, PROJNAME, COUNT(*),
SUM((DAYS(EMENDATE) - DAYS(EMSTDATE)) * EMPTIME *
DECIMAL((SALARY/:WRKDAY),8,2))
FROM CORPDATA/EMPPROJACT, CORPDATA/PROJECT, CORPDATA/EMPLOYEE
WHERE EMPPROJACT.PROJNO = PROJECT.PROJNO AND
EMPPROJACT.EMPNO = EMPLOYEE.EMPNO AND
PRENDATE > :RDATE
GROUP BY EMPPROJACT.PROJNO, PROJNAME
ORDER BY 1;
//
EXEC SQL OPEN C2;
//
12
C
C
// Fetch and write the rows to QPRINT.
//
EXEC SQL WHENEVER NOT FOUND GO TO DONE2;
DOU SQLCOD <> 0;
EXEC SQL FETCH C2 INTO :RPT2;
EXCEPT RECD;
ENDDO;
DONE2
EXEC SQL CLOSE C2;
GOTO FINISH
//
// Error occured while updating table.
Inform user and rollback
// changes.
TAG
13
14
C
C
//
UPDERR TAG
EXCEPT RECE;
EXEC SQL WHENEVER SQLERROR CONTINUE;
//
EXEC SQL ROLLBACK;
GOTO
//
FINISH
O
O
O
O
O
O
C
// Error occured while generating reports.
Inform user and exit.
//
TAG RPTERR
EXCEPT RECF;
//
C
OQPRINT
O
// All done.
//
FINISH
*INLR = *ON;
E
TAG
RECA 0 2 01
45 ’REPORT OF PROJECTS AFFEC’
58 ’TED BY RAISES’
E RECA 0 1
7 ’PROJECT’
14 ’EMPID’
32 ’EMPLOYEE NAME’
59 ’SALARY’
011600
011700
011800
011900
012000
012100
012200
012300
012400
012500
012600
012700
012800
010100
010200
010300
010400
010500
010600
010700
010800
010900
011000
011100
011200
011300
011400
011500
012900
013000
013100
013200
013300
013400
013500
013600
013700
013800
013900
014000
008600
008700
008800
008900
009000
009100
009200
009300
009400
009500
009600
009700
009800
009900
010000
11/11/13 11:23:30
006900
007000
007100
007200
007300
007400
007500
007600
007700
007800
007900
008000
008100
008200
008300
008400
008500
180
IBM i: Embedded SQL programming
Page 3
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
161
162
163
164
165
166
167
168
154
155
156
157
158
159
160
169
170
171
172 xxxxST1 VxRxMx yymmdd
141
142
O
O
143
144
145
O
O
O
146
147
148
149
150
151
152
153
O
O
O
O
O
O
O
O
O
O
O
O
O
O
O
O
O
O
O
O
O
O
O
O
O
O
O
E
E
E
E
E
E
E
Create SQL ILE RPG Object
RECB
PROJNO
0 1
6
EMPNO
NAME
SALARY
RECC
L
2 2
15
49
61
RPGLEEX
42 ’ACCUMULATED STATISTIC’
54 ’S BY PROJECT’
RECC 0 1
7 ’PROJECT’
56 ’NUMBER OF’
67 ’TOTAL’
RECC 0 2
6 ’NUMBER’
21 ’PROJECT NAME’
56 ’EMPLOYEES’
66 ’COST’
RECD
PRJNUM
PNAME
EMPCNT
PRCOST
RECE
0 1
L
L
0 1
6
45
54
70
28 ’*** ERROR Occurred while’
52 ’ updating table. SQLCODE’
53 ’=’
62 SQLCOD
RECF
L
0 1
28 ’*** ERROR Occurred while’
52 ’ generating reports. SQL’
SQLCOD L
57 ’CODE=’
67
* * * * * E N D O F S O U R C E * * * * *
015400
015500
015600
015700
015800
015900
016000
016100
016200
016300
016400
016500
016600
016700
016800
016900
017000
017100
017200
11/11/13 11:23:30
014100
014200
014300
014400
014500
014600
014700
014800
014900
015000
015100
015200
015300
Page 4
Embedded SQL programming
181
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| xxxxST1 VxRxMx yymmdd
Data Names
ACTNO
BIRTHDATE
BONUS
COMM
COMM
COMMI
CORPDATA
C1
C2
DEPTNO
DEPTNO
DONE1
DONE2
EDLEVEL
EMENDATE
EMENDATE
EMPCNT
EMPLOYEE
EMPLOYEE
EMPNO
EMPNO
EMPNO
EMPNO
EMPNO
EMPPROJACT
EMPPROJACT
EMPTIME
EMPTIME
EMSTDATE
EMSTDATE
FINISH
FIRSTNME
FIRSTNME
HIREDATE
JOB
LASTNAME
LASTNAME
MAJPROJ
MAJPROJ
MIDINIT
NAME
PERCNT
PHONENO
PNAME
PRCOST
PRENDATE
PRENDATE
PRENDATE
PRJNUM
Create SQL ILE RPG Object
CROSS REFERENCE
Define Reference
63
63
63
****
RPGLEEX 11/11/13 11:23:30
SMALL INTEGER PRECISION(4,0) COLUMN (NOT NULL) IN CORPDATA.EMPPROJACT
DATE(10) COLUMN IN CORPDATA.EMPLOYEE
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
COLUMN
63
28
****
60
90
46 65
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
DECIMAL(7,2)
46 65
SCHEMA
44 63 63 94 94 94
CURSOR
68 74 78
CURSOR
101 107 111
CHARACTER(3) IN RPT1 8
94
77
110
63
63
****
CHARACTER(3) CCSID 37 COLUMN (NOT NULL) IN CORPDATA.PROJECT
LABEL
72
LABEL
105
SMALL INTEGER PRECISION(4,0) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
DATE(10) COLUMN IN CORPDATA.EMPPROJACT
COLUMN
22
****
****
12
****
****
63
63
****
92
SMALL INTEGER PRECISION(4,0) IN RPT2
TABLE IN CORPDATA
44 63 94
TABLE
64 96
CHARACTER(6)
74
COLUMN IN EMPPROJACT
64 66 96
COLUMN IN EMPLOYEE
64 96
CHARACTER(6) CCSID 37 COLUMN (NOT NULL) IN CORPDATA.EMPPROJACT
CHARACTER(6) CCSID 37 COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
TABLE IN CORPDATA
****
63
****
63
****
131
****
63
63
63
****
63
8
94
63
13
30
63
21
23
8
****
94
20
63 94
TABLE
64 95 96 98
DECIMAL(5,2) COLUMN IN CORPDATA.EMPPROJACT
CROSS REFERENCE
COLUMN
92
DATE(10) COLUMN IN CORPDATA.EMPPROJACT
COLUMN
92
LABEL
COLUMN
62
VARCHAR(12) CCSID 37 COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
DATE(10) COLUMN IN CORPDATA.EMPLOYEE
CHARACTER(8) CCSID 37 COLUMN IN CORPDATA.EMPLOYEE
COLUMN
62
VARCHAR(15) CCSID 37 COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
CHARACTER(6) IN RPT1
CHARACTER(6) CCSID 37 COLUMN IN CORPDATA.PROJECT
CHARACTER(1) CCSID 37 COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
CHARACTER(30)
74
DECIMAL(7,2)
45
CHARACTER(4) CCSID 37 COLUMN IN CORPDATA.EMPLOYEE
CHARACTER(36) IN RPT2
DECIMAL(9,2) IN RPT2
DATE(8) IN RPT1
COLUMN
97
DATE(10) COLUMN IN CORPDATA.PROJECT
CHARACTER(6) IN RPT2
182
IBM i: Embedded SQL programming
Page 5
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| xxxxST1 VxRxMx yymmdd
PROJECT
PROJECT
PROJNAME
PROJNAME
PROJNAME
PROJNO
PROJNO
PROJNO
PROJNO
PROJNO
PROJNO
PRSTAFF
PRSTAFF
PRSTDATE
PRSTDATE
RDATE
RESPEMP
RESPEMP
RPTERR
RPT1
RPT2
SALARY
SALARY
SALARY
SEX
UPDERR
WORKDEPT
WRKDAY
94
8
94
8
94
29
Create SQL ILE RPG Object
****
CROSS REFERENCE
TABLE IN CORPDATA
****
94
TABLE
95
8
****
94
8
****
RPGLEEX 11/11/13 11:23:30
VARCHAR(24) IN RPT1
COLUMN
91 98
VARCHAR(24) CCSID 37 COLUMN (NOT NULL) IN CORPDATA.PROJECT
CHARACTER(6) IN RPT1
74
COLUMN
61 66
63
****
****
8
94
126
CHARACTER(6) CCSID 37 COLUMN (NOT NULL) IN CORPDATA.EMPPROJACT
COLUMN IN EMPPROJACT
95 98
COLUMN IN PROJECT
95
CHARACTER(6) CCSID 37 COLUMN (NOT NULL) IN CORPDATA.PROJECT
DECIMAL(5,2) IN RPT1
DECIMAL(5,2) COLUMN IN CORPDATA.PROJECT
DATE(8) IN RPT1
DATE(10) COLUMN IN CORPDATA.PROJECT
CHARACTER(10)
97
CHARACTER(6) IN RPT1
CHARACTER(6) CCSID 37 COLUMN (NOT NULL) IN CORPDATA.PROJECT
LABEL
8
19
14
****
63
63
117
63
27
52
STRUCTURE
STRUCTURE
107
DECIMAL(9,2)
74
COLUMN
45 45 62 93
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
CHARACTER(1) CCSID 37 COLUMN IN CORPDATA.EMPLOYEE
LABEL
41
CHARACTER(3) CCSID 37 COLUMN IN CORPDATA.EMPLOYEE
SMALL INTEGER PRECISION(4,0)
93
No errors found in source
172 Source records processed
* * * * * E N D O F L I S T I N G * * * * *
Related concepts
:
“Coding SQL statements in ILE RPG applications” on page 98
You need to be aware of the unique application and coding requirements for embedding SQL statements in an ILE RPG program. In this topic, the coding requirements for host variables are defined.
Example: SQL statements in REXX programs
This example program is written in the REXX programming language.
Note:
Page 6
Embedded SQL programming
183
41
42
43
44
45
46
47
48
49
50
51
37
38
39
40
33
34
35
36
26
27
28
29
30
31
32
22
23
24
25
18
19
20
21
11
12
13
14
9
10
7
8
15
16
17
Record *...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
1 /*********************************************************************/
2 /* A sample program which updates the salaries for those employees */
5
6
3
4
/* whose current commission total is greater than or equal to the
/* value of COMMISSION. The salaries of those who qualify are
/* increased by the value of PERCENTAGE, retroactive to RAISE_DATE.
/* A report is generated and dumped to the display which shows the
*/
*/
*/
*/
/* projects which these employees have contributed to, ordered by
/* project number and employee ID. A second report shows each
/* project having an end date occurring after RAISE DATE (i.e. is
/* potentially affected by the retroactive raises) with its total
*/
*/
*/
*/
/* salary expenses and a count of employees who contributed to the */
/* project.
*/
/*********************************************************************/
/* Initialize RC variable */
RC = 0
/* Initialize HV for program usage */
COMMISSION = 2000.00;
PERCENTAGE = 1.04;
RAISE_DATE = ’1982-06-01’;
WORK_DAYS = 253;
/* Create the output file to dump the 2 reports. Perform an OVRDBF
/* to allow us to use the SAY REXX command to write to the output
/* file.
ADDRESS ’*COMMAND’,
’DLTF FILE(CORPDATA/REPORTFILE)’
ADDRESS ’*COMMAND’,
’CRTPF FILE(CORPDATA/REPORTFILE) RCDLEN(80)’
ADDRESS ’*COMMAND’,
*/
*/
*/
’OVRDBF FILE(STDOUT) TOFILE(CORPDATA/REPORTFILE) MBR(REPORTFILE)’
/* Update the selected employee’s salaries by the new percentage. */
/* If an error occurs during the update, ROLLBACK the changes.
3SIGNAL ON ERROR
ERRLOC = ’UPDATE_ERROR’
UPDATE_STMT = ’UPDATE CORPDATA/EMPLOYEE ’,
’SET SALARY = SALARY * ?
’,
EXECSQL,
4EXECSQL,
5EXECSQL,
’WHERE COMM >= ?
’PREPARE S1 FROM :UPDATE_STMT’
’EXECUTE S1 USING :PERCENTAGE,’,
’ :COMMISSION ’
/* Commit changes */
’COMMIT’
ERRLOC = ’REPORT_ERROR’
’
*/
Figure 8. Sample REXX Procedure Using SQL Statements
184
IBM i: Embedded SQL programming
99
100
101
102
103
104
105
106
92
93
94
95
96
97
98
107
108
109
88
89
90
91
84
85
86
87
77
78
79
80
81
82
83
73
74
75
76
69
70
71
72
62
63
64
65
58
59
60
61
66
67
68
Record *...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
52 /* Report the updated statistics for each project supported by one */
53 /* of the selected employees.
*/
54
55
56
57
/* Write out the header for Report 1 */
SAY ’ ’
SAY ’ ’
SAY ’ ’
SAY ’ REPORT OF PROJECTS AFFECTED BY EMPLOYEE RAISES’
SAY ’ ’
SAY ’PROJECT EMPID
SAY ’-------
SAY ’ ’
-----
EMPLOYEE NAME
-------------
SALARY’
------’
SELECT_STMT = ’SELECT DISTINCT PROJNO, EMPPROJACT.EMPNO, ’,
’ LASTNAME||’’, ’’||FIRSTNME, SALARY ’,
’FROM CORPDATA/EMPPROJACT, CORPDATA/EMPLOYEE ’,
’WHERE EMPPROJACT.EMPNO = EMPLOYEE.EMPNO AND ’,
’ COMM >= ?
’ORDER BY PROJNO, EMPNO
EXECSQL,
’PREPARE S2 FROM :SELECT_STMT’
6EXECSQL,
’DECLARE C1 CURSOR FOR S2’
7EXECSQL,
’OPEN C1 USING :COMMISSION’
’,
’
/* Handle the FETCH errors and warnings inline */
SIGNAL OFF ERROR
/* Fetch all of the rows */
DO UNTIL (SQLCODE <> 0)
9EXECSQL,
’FETCH C1 INTO :RPT1.PROJNO, :RPT1.EMPNO,’,
’ :RPT1.NAME, :RPT1.SALARY
’
/* Process any errors that may have occurred. Continue so that
/* we close the cursor for any warnings.
IF SQLCODE < 0 THEN
SIGNAL ERROR
*/
*/
/* Stop the loop when we hit the EOF. Don’t try to print out the */
/* fetched values.
*/
8IF SQLCODE = 100 THEN
LEAVE
/* Print out the fetched row */
SAY RPT1.PROJNO ’
END;
10EXECSQL,
’CLOSE C1’
’ RPT1.EMPNO ’ ’ RPT1.NAME ’ ’ RPT1.SALARY
/* For all projects ending at a date later than ’raise_date’
/* (that is, those projects potentially affected by the salary raises)
/* generate a report containing the project number, project name,
/* the count of employees participating in the project, and the
/* total salary cost of the project.
*/
*/
*/
*/
*/
Embedded SQL programming
185
157
158
159
160
161
162
163
164
150
151
152
153
154
155
156
165
166
167
142
143
144
145
146
147
148
149
127
128
129
130
131
132
133
134
116
117
118
119
120
121
122
123
124
125
126
Record *...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
110 /* Write out the header for Report 2 */
111 SAY ’ ’
112
113
114
115
SAY ’
SAY ’
SAY ’
SAY ’
’
’
’
ACCUMULATED STATISTICS BY PROJECT’
SAY ’PROJECT PROJECT NAME
SAY ’NUMBER
SAY ’------------------
SAY ’ ’
NUMBER OF
EMPLOYEES
---------
TOTAL’
COST’
-----’
/* Go to the common error handler */
SIGNAL ON ERROR
SELECT_STMT = ’SELECT EMPPROJACT.PROJNO, PROJNAME, COUNT(*),
’ SUM( (DAYS(EMENDATE) - DAYS(EMSTDATE)) * EMPTIME * ’,
’,
’ DECIMAL(( SALARY / ? ),8,2) ) ’,
’FROM CORPDATA/EMPPROJACT, CORPDATA/PROJECT, CORPDATA/EMPLOYEE’,
’WHERE EMPPROJACT.PROJNO = PROJECT.PROJNO
’ EMPPROJACT.EMPNO = EMPLOYEE.EMPNO
’ PRENDATE > ?
’GROUP BY EMPPROJACT.PROJNO, PROJNAME
’ORDER BY 1
EXECSQL,
’PREPARE S3 FROM :SELECT_STMT’
11EXECSQL,
AND
AND
’,
’
’,
’,
’,
135
136
137
138
139
140
141
’DECLARE C2 CURSOR FOR S3’
EXECSQL,
’OPEN C2 USING :WORK_DAYS, :RAISE_DATE’
/* Handle the FETCH errors and warnings inline */
SIGNAL OFF ERROR
/* Fetch all of the rows */
DO UNTIL (SQLCODE <> 0)
12EXECSQL,
’FETCH C2 INTO :RPT2.PROJNO, :RPT2.PROJNAME,
’
’,
:RPT2.EMPCOUNT, :RPT2.TOTAL_COST ’
/* Process any errors that may have occurred. Continue so that */
/* we close the cursor for any warnings.
*/
IF SQLCODE < 0 THEN
SIGNAL ERROR
/* Stop the loop when we hit the EOF. Don’t try to print out the */
/* fetched values.
IF SQLCODE = 100 THEN
LEAVE
/* Print out the fetched row */
SAY RPT2.PROJNO ’ ’ RPT2.PROJNAME ’ ’ ,
END;
RPT2.EMPCOUNT ’
EXECSQL,
’CLOSE C2’
’ RPT2.TOTAL_COST
*/
186
IBM i: Embedded SQL programming
195
196
197
198
199
200
201
186
187
188
190
191
192
193
194
202
203
204
205
206
207
208
209
210
211
175
176
177
178
179
180
181
182
183
184
185
168
169
170
171
172
173
174
/* Delete the OVRDBF so that we will continue writing to the output */
/* display.
*/
ADDRESS ’*COMMAND’,
’DLTOVR FILE(STDOUT)’
/* Leave procedure with a successful or warning RC */
EXIT RC
/* Error occurred while updating the table or generating the
/* reports. If the error occurred on the UPDATE, rollback all of
/* the changes. If it occurred on the report generation, display the */
/* REXX RC variable and the SQLCODE and exit the procedure.
*/
ERROR:
*/
*/
13SIGNAL OFF ERROR
/* Determine the error location */
SELECT
/* When the error occurred on the UPDATE statement */
WHEN ERRLOC = ’UPDATE_ERROR’ THEN
DO
SAY ’*** ERROR Occurred while updating table.’,
’SQLCODE = ’ SQLCODE
14EXECSQL,
’ROLLBACK’
END
/* When the error occurred during the report generation */
WHEN ERRLOC = ’REPORT_ERROR’ THEN
SAY ’*** ERROR Occurred while generating reports. ’,
’SQLCODE = ’ SQLCODE
OTHERWISE
SAY ’*** Application procedure logic error occurred ’
END
/* Delete the OVRDBF so that we will continue writing to the
/* output display.
ADDRESS ’*COMMAND’,
’DLTOVR FILE(STDOUT)’
/* Return the error RC received from SQL. */
EXIT RC
* * * * * E N D O F S O U R C E * * * * *
*/
*/
Related concepts
:
“Coding SQL statements in REXX applications” on page 128
REXX procedures do not have to be preprocessed. At run time, the REXX interpreter passes statements that it does not understand to the current active command environment for processing.
Report produced by example programs that use SQL
This report is produced by each of the example programs.
REPORT OF PROJECTS AFFECTED BY RAISES
PROJECT EMPID
AD3100 000010
AD3110 000070
AD3111 000240
AD3113 000270
IF1000 000030
IF1000 000140
IF2000 000030
IF2000 000140
MA2100 000010
MA2100 000110
MA2110 000010
MA2111 000200
MA2111 000220
MA2112 000150
EMPLOYEE NAME
HAAS, CHRISTINE
PULASKI, EVA
MARINO, SALVATORE
PEREZ, MARIA
KWAN, SALLY
NICHOLLS, HEATHER
KWAN, SALLY
NICHOLLS, HEATHER
HAAS, CHRISTINE
LUCCHESSI, VICENZO
HAAS, CHRISTINE
BROWN, DAVID
LUTZ, JENNIFER
ADAMSON, BRUCE
SALARY
54860.00
37616.80
29910.40
28475.20
39780.00
29556.80
39780.00
29556.80
54860.00
48360.00
54860.00
28849.60
31033.60
26291.20
Embedded SQL programming
187
OP1000 000050
OP1010 000090
OP1010 000280
OP2010 000050
OP2010 000100
OP2012 000330
PL2100 000020
GEYER, JOHN
HENDERSON, EILEEN
SCHNEIDER, ETHEL
GEYER, JOHN
SPENSER, THEODORE
LEE, WING
THOMPSON, MICHAEL
41782.00
30940.00
27300.00
41782.00
27196.00
26384.80
42900.00
PROJECT
NUMBER PROJECT NAME
ACCUMULATED STATISTICS BY PROJECT
NUMBER OF
EMPLOYEES
AD3100 ADMIN SERVICES
AD3110 GENERAL ADMIN SYSTEMS
AD3111 PAYROLL PROGRAMMING
AD3112 PERSONNEL PROGRAMMING
AD3113 ACCOUNT PROGRAMMING
IF1000 QUERY SERVICES
IF2000 USER EDUCATION
MA2100 WELD LINE AUTOMATION
MA2110 W L PROGRAMMING
MA2111 W L PROGRAM DESIGN
MA2112 W L ROBOT DESIGN
MA2113 W L PROD CONT PROGS
OP1000 OPERATION SUPPORT
OP1010 OPERATION
OP2010 SYSTEMS SUPPORT
OP2011 SCP SYSTEMS SUPPORT
OP2012 APPLICATIONS SUPPORT
OP2013 DB/DC SUPPORT
PL2100 WELD LINE PLANNING
14
4
5
2
7
9
1
1
6
5
1
1
3
2
2
5
2
2
1
TOTAL
COST
19623.11
58877.28
66407.56
28845.70
72114.52
35178.99
55212.61
114001.52
85864.68
93729.24
166945.84
71509.11
16348.86
167828.76
91612.62
31224.60
41294.88
37311.12
43576.92
CL command descriptions for host language precompilers
The IBM DB2 Query Manager and SQL Development Kit for i licensed program provides commands for precompiling programs coded in these programming languages.
Related concepts
:
“Non-ILE SQL precompiler commands” on page 143
The IBM DB2 Query Manager and SQL Development Kit for i licensed program includes non-ILE precompiler commands for the following host languages: CRTSQLCBL (for OPM COBOL), CRTSQLPLI (for
PL/I PRPQ), and CRTSQLRPG (for RPG III, which is part of RPG/400).
Related reference
:
“ILE SQL precompiler commands” on page 144
In the IBM DB2 Query Manager and SQL Development Kit for i licensed program, these ILE precompiler commands exist: CRTSQLCI, CRTSQLCPPI, CRTSQLCBLI, and CRTSQLRPGI.
Create SQL COBOL Program command
The Create SQL COBOL Program (CRTSQLCBL) command calls the SQL precompiler.
It precompiles COBOL source containing SQL statements, produces a temporary source member, and then optionally calls the COBOL compiler to compile the program.
Related reference
:
Create SQL COBOL Program (CRTSQLCBL) command
188
IBM i: Embedded SQL programming
Create SQL ILE COBOL Object command
The Create SQL ILE COBOL Object (CRTSQLCBLI) command calls the SQL precompiler, which precompiles
COBOL source containing SQL statements, produces a temporary source member, and then optionally calls the ILE COBOL compiler to create a module, a program, or a service program.
Related reference
:
Create SQL ILE COBOL Object (CRTSQLCBLI) command
Create SQL ILE C Object command
The Create SQL ILE C Object (CRTSQLCI) command calls the SQL precompiler, which precompiles C source containing SQL statements, produces a temporary source member, and then optionally calls the
ILE C compiler to create a module, create a program, or create a service program.
Related reference
:
Create SQL ILE C Object (CRTSQLCI) command
Create SQL ILE C++ Object command
The Create SQL ILE C++ Object (CRTSQLCPPI) command calls the SQL precompiler, which precompiles
C++ source containing SQL statements, produces a temporary source member, and then optionally calls the C++ compiler to create a module.
Related reference
:
Create SQL C++ Object (CRTSQLCPPI) command
Create SQL PL/I Program command
The Create SQL PL/I Program (CRTSQLPLI) command calls a SQL precompiler, which precompiles PL/I source containing SQL statements, produces a temporary source member, and optionally calls the PL/I compiler to compile the program.
Related reference
:
Create SQL PL/I Program (CRTSQLPLI) command
Create SQL RPG Program command
The Create SQL RPG Program (CRTSQLRPG) command calls the SQL precompiler, which precompiles the
RPG source containing the SQL statements, produces a temporary source member, and then optionally calls the RPG compiler to compile the program.
Related reference
:
Create SQL RPG Program (CRTSQLRPG) command
Create SQL ILE RPG Object command
The Create SQL ILE RPG Object (CRTSQLRPGI) command calls the SQL precompiler, which precompiles
RPG source containing SQL statements, produces a temporary source member, and then optionally calls the ILE RPG compiler to create a module, create a program, or create a service program.
Related reference
:
Create SQL ILE RPG Object (CRTSQLRPGI) command
Related information for Embedded SQL programming
Product manuals and other information center topic collections contain information that relates to the
Embedded SQL programming topic collection. You can view or print any of the PDF files.
Embedded SQL programming
189
Manuals
v
ILE RPG Programmer's Guide v ILE RPG Reference v ILE COBOL Programmer's Guide v ILE COBOL Reference v REXX/400 Programmer's Guide v REXX/400 Reference v DB2 for i SQL reference
The following manuals are not included in the IBM i Information Center. However, these manuals might be a useful reference to you. Each of the manuals is available from the IBM Publications Center as a printed hardcopy that you can order, in an online format that you can download at no charge, or both.
v
COBOL/400 User's Guide (about 5,980 KB) v COBOL/400 Reference (about 2,150 KB) v RPG/400 User's Guide (about 2,090 KB) v RPG/400 Reference (about 2,520 KB)
Other information
You can view or download these related topics: v Database performance and query optimization v SQL call level interface v SQL messages and codes v
SQL programming
Code license and disclaimer information
IBM grants you a nonexclusive copyright license to use all programming code examples from which you can generate similar function tailored to your own specific needs.
SUBJECT TO ANY STATUTORY WARRANTIES WHICH CANNOT BE EXCLUDED, IBM, ITS
PROGRAM DEVELOPERS AND SUPPLIERS MAKE NO WARRANTIES OR CONDITIONS EITHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OR
CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
NON-INFRINGEMENT, REGARDING THE PROGRAM OR TECHNICAL SUPPORT, IF ANY.
UNDER NO CIRCUMSTANCES IS IBM, ITS PROGRAM DEVELOPERS OR SUPPLIERS LIABLE FOR
ANY OF THE FOLLOWING, EVEN IF INFORMED OF THEIR POSSIBILITY:
1.
LOSS OF, OR DAMAGE TO, DATA;
2.
DIRECT, SPECIAL, INCIDENTAL, OR INDIRECT DAMAGES, OR FOR ANY ECONOMIC
CONSEQUENTIAL DAMAGES; OR
3.
LOST PROFITS, BUSINESS, REVENUE, GOODWILL, OR ANTICIPATED SAVINGS.
SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF DIRECT,
INCIDENTAL, OR CONSEQUENTIAL DAMAGES, SO SOME OR ALL OF THE ABOVE LIMITATIONS
OR EXCLUSIONS MAY NOT APPLY TO YOU.
190
IBM i: Embedded SQL programming
Notices
This information was developed for products and services offered in the U.S.A.
IBM may not offer the products, services, or features discussed in this document in other countries.
Consult your local IBM representative for information on the products and services currently available in your area. Any reference to an IBM product, program, or service is not intended to state or imply that only that IBM product, program, or service may be used. Any functionally equivalent product, program, or service that does not infringe any IBM intellectual property right may be used instead. However, it is the user's responsibility to evaluate and verify the operation of any non-IBM product, program, or service.
IBM may have patents or pending patent applications covering subject matter described in this document. The furnishing of this document does not grant you any license to these patents. You can send license inquiries, in writing, to:
IBM Director of Licensing
IBM Corporation
North Castle Drive
Armonk, NY 10504-1785
U.S.A.
For license inquiries regarding double-byte (DBCS) information, contact the IBM Intellectual Property
Department in your country or send inquiries, in writing, to:
Intellectual Property Licensing
Legal and Intellectual Property Law
IBM Japan Ltd.
1623-14, Shimotsuruma, Yamato-shi
Kanagawa 242-8502 Japan
The following paragraph does not apply to the United Kingdom or any other country where such provisions are inconsistent with local law: INTERNATIONAL BUSINESS MACHINES CORPORATION
PROVIDES THIS PUBLICATION "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR
IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Some states do not allow disclaimer of express or implied warranties in certain transactions, therefore, this statement may not apply to you.
This information could include technical inaccuracies or typographical errors. Changes are periodically made to the information herein; these changes will be incorporated in new editions of the publication.
IBM may make improvements and/or changes in the product(s) and/or the program(s) described in this publication at any time without notice.
Any references in this information to non-IBM Web sites are provided for convenience only and do not in any manner serve as an endorsement of those Web sites. The materials at those Web sites are not part of the materials for this IBM product and use of those Web sites is at your own risk.
IBM may use or distribute any of the information you supply in any way it believes appropriate without incurring any obligation to you.
© Copyright IBM Corp. 1998, 2013
191
Licensees of this program who wish to have information about it for the purpose of enabling: (i) the exchange of information between independently created programs and other programs (including this one) and (ii) the mutual use of the information which has been exchanged, should contact:
IBM Corporation
Software Interoperability Coordinator, Department YBWA
3605 Highway 52 N
Rochester, MN 55901
U.S.A.
Such information may be available, subject to appropriate terms and conditions, including in some cases, payment of a fee.
The licensed program described in this document and all licensed material available for it are provided by IBM under terms of the IBM Customer Agreement, IBM International Program License Agreement or any equivalent agreement between us.
Any performance data contained herein was determined in a controlled environment. Therefore, the results obtained in other operating environments may vary significantly. Some measurements may have been made on development-level systems and there is no guarantee that these measurements will be the same on generally available systems. Furthermore, some measurements may have been estimated through extrapolation. Actual results may vary. Users of this document should verify the applicable data for their specific environment.
Information concerning non-IBM products was obtained from the suppliers of those products, their published announcements or other publicly available sources. IBM has not tested those products and cannot confirm the accuracy of performance, compatibility or any other claims related to non-IBM products. Questions on the capabilities of non-IBM products should be addressed to the suppliers of those products.
All statements regarding IBM's future direction or intent are subject to change or withdrawal without notice, and represent goals and objectives only.
This information is for planning purposes only. The information herein is subject to change before the products described become available.
This information contains examples of data and reports used in daily business operations. To illustrate them as completely as possible, the examples include the names of individuals, companies, brands, and products. All of these names are fictitious and any similarity to the names and addresses used by an actual business enterprise is entirely coincidental.
COPYRIGHT LICENSE:
This information contains sample application programs in source language, which illustrate programming techniques on various operating platforms. You may copy, modify, and distribute these sample programs in any form without payment to IBM, for the purposes of developing, using, marketing or distributing application programs conforming to the application programming interface for the operating platform for which the sample programs are written. These examples have not been thoroughly tested under all conditions. IBM, therefore, cannot guarantee or imply reliability, serviceability, or function of these programs. The sample programs are provided "AS IS", without warranty of any kind. IBM shall not be liable for any damages arising out of your use of the sample programs.
Each copy or any portion of these sample programs or any derivative work, must include a copyright notice as follows:
© (your company name) (year). Portions of this code are derived from IBM Corp. Sample Programs.
192
IBM i: Embedded SQL programming
© Copyright IBM Corp. _enter the year or years_.
Programming interface information
This Embedded SQL programming publication documents intended Programming Interfaces that allow the customer to write programs to obtain the services of IBM i.
Trademarks
IBM, the IBM logo, and ibm.com are trademarks or registered trademarks of International Business
Machines Corp., registered in many jurisdictions worldwide. Other product and service names might be trademarks of IBM or other companies. A current list of IBM trademarks is available on the Web at
“Copyright and trademark information” at www.ibm.com/legal/copytrade.shtml.
Adobe, the Adobe logo, PostScript, and the PostScript logo are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States, and/or other countries.
Other product and service names might be trademarks of IBM or other companies.
Terms and conditions
Permissions for the use of these publications is granted subject to the following terms and conditions.
Personal Use:
You may reproduce these publications for your personal, noncommercial use provided that all proprietary notices are preserved. You may not distribute, display or make derivative works of these publications, or any portion thereof, without the express consent of IBM.
Commercial Use:
You may reproduce, distribute and display these publications solely within your enterprise provided that all proprietary notices are preserved. You may not make derivative works of these publications, or reproduce, distribute or display these publications or any portion thereof outside your enterprise, without the express consent of IBM.
Except as expressly granted in this permission, no other permissions, licenses or rights are granted, either express or implied, to the publications or any information, data, software or other intellectual property contained therein.
IBM reserves the right to withdraw the permissions granted herein whenever, in its discretion, the use of the publications is detrimental to its interest or, as determined by IBM, the above instructions are not being properly followed.
You may not download, export or re-export this information except in full compliance with all applicable laws and regulations, including all United States export laws and regulations.
IBM MAKES NO GUARANTEE ABOUT THE CONTENT OF THESE PUBLICATIONS. THE
PUBLICATIONS ARE PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF
MERCHANTABILITY, NON-INFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
Notices
193
194
IBM i: Embedded SQL programming
IBM®
Product Number: 5770-SS1
Printed in USA
Download
Annonce