Programacion SQL Ibm I
Programacion SQL Ibm I
Version 7.3
Database
Embedded SQL programming
IBM
IBM i
Version 7.3
Database
Embedded SQL programming
IBM
Note
Before using this information and the product it supports, read the information in “Notices” on page 191.
This edition applies to IBM i 7.3 (product number 5770-SS1) and to all subsequent releases and modifications until
otherwise indicated in new editions. This version does not run on all reduced instruction set computer (RISC)
models nor does it run on CISC models.
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, 2015.
US Government Users Restricted Rights – Use, duplication or disclosure restricted by GSA ADP Schedule Contract
with IBM Corp.
Contents
Embedded SQL programming . . . . . 1 Declaring host variables in C and C++
| What's new for IBM i 7.3 . . . . . . . . . . 1 applications that use SQL. . . . . . . . 17
PDF file for Embedded SQL programming . . . . 1 Numeric host variables in C and C++
Common concepts and rules for using embedded applications that use SQL. . . . . . . 17
SQL . . . . . . . . . . . . . . . . . 2 Character host variables in C and C++
Writing applications that use SQL . . . . . . 2 applications that use SQL. . . . . . . 18
Using host variables in SQL statements . . . . 2 Graphic host variables in C and C++
Assignment rules for host variables in SQL applications that use SQL. . . . . . . 21
statements . . . . . . . . . . . . . 4 Binary host variables in C and C++
Indicator variables in applications that use SQL 4 applications that use SQL. . . . . . . 23
Indicator variables used with host structures 5 LOB host variables in C and C++
Indicator variables used to assign special applications that use SQL. . . . . . . 24
values . . . . . . . . . . . . . 5 XML host variables in C and C++
Handling SQL error return codes using the applications that use SQL. . . . . . . 27
SQLCA . . . . . . . . . . . . . . . 6 ROWID host variables in C and C++
Using the SQL diagnostics area . . . . . . . 7 applications that use SQL. . . . . . . 29
Updating applications to use the SQL Result set locator host variables in C and
diagnostics area . . . . . . . . . . . 8 C++ applications that use SQL . . . . . 30
IBM i programming model . . . . . . . 8 Using host structures in C and C++ applications
Additional notes on using the SQL diagnostics that use SQL . . . . . . . . . . . . . 30
area . . . . . . . . . . . . . . . 8 Host structure declarations in C and C++
Example: SQL routine exception . . . . . . 8 applications that use SQL. . . . . . . . 31
Example: Logging items from the SQL Host structure indicator array in C and C++
diagnostics area . . . . . . . . . . . 9 applications that use SQL. . . . . . . . 34
Handling exception conditions with the Using arrays of host structures in C and C++
WHENEVER statement . . . . . . . . . 10 applications that use SQL. . . . . . . . . 34
Coding SQL statements in C and C++ applications 11 Host structure array in C and C++
Defining the SQL communication area in C and applications that use SQL. . . . . . . . 35
C++ applications that use SQL . . . . . . . 11 Host structure array indicator structure in C
Defining SQL descriptor areas in C and C++ and C++ applications that use SQL . . . . 38
applications that use SQL. . . . . . . . . 13 Using pointer data types in C and C++
Embedding SQL statements in C and C++ applications that use SQL. . . . . . . . . 38
applications that use SQL. . . . . . . . . 15 Using typedef in C and C++ applications that
Comments in C and C++ applications that use use SQL . . . . . . . . . . . . . . 39
SQL . . . . . . . . . . . . . . . 15 Using ILE C compiler external file descriptions in
Continuation for SQL statements in C and C and C++ applications that use SQL. . . . . 40
C++ applications that use SQL . . . . . . 15 Determining equivalent SQL and C or C++ data
Including code in C and C++ applications that types . . . . . . . . . . . . . . . 40
use SQL . . . . . . . . . . . . . 15 Notes on C and C++ variable declaration and
Margins in C and C++ applications that use usage . . . . . . . . . . . . . . 43
SQL . . . . . . . . . . . . . . . 16 Using indicator variables in C and C++
Names in C and C++ applications that use applications that use SQL. . . . . . . . . 43
SQL . . . . . . . . . . . . . . . 16 Coding SQL statements in COBOL applications . . 44
NULLs and NULs in C and C++ applications Defining the SQL communication area in COBOL
that use SQL . . . . . . . . . . . . 16 applications that use SQL. . . . . . . . . 44
Statement labels in C and C++ applications Defining SQL descriptor areas in COBOL
that use SQL . . . . . . . . . . . . 16 applications that use SQL. . . . . . . . . 45
Preprocessor sequence for C and C++ Embedding SQL statements in COBOL
applications that use SQL. . . . . . . . 16 applications that use SQL. . . . . . . . . 47
Trigraphs in C and C++ applications that use Comments in COBOL applications that use
SQL . . . . . . . . . . . . . . . 16 SQL . . . . . . . . . . . . . . . 47
WHENEVER statement in C and C++ Continuation for SQL statements in COBOL
applications that use SQL. . . . . . . . 17 applications that use SQL. . . . . . . . 47
Using host variables in C and C++ applications Including code in COBOL applications that
that use SQL . . . . . . . . . . . . . 17 use SQL . . . . . . . . . . . . . 48
Margins in COBOL applications that use SQL 48
Contents v
Using indicator variables in REXX applications Running a program with embedded SQL:
that use SQL . . . . . . . . . . . . 136 SQL return codes . . . . . . . . . . 149
Preparing and running a program with SQL Example programs: Using DB2 for i statements . . 149
statements . . . . . . . . . . . . . . 136 Example: SQL statements in ILE C and C++
Basic processes of the SQL precompiler. . . . 136 programs . . . . . . . . . . . . . . 151
Input to the SQL precompiler . . . . . . 137 Example: SQL statements in COBOL and ILE
Source file CCSIDs in the SQL precompiler 138 COBOL programs . . . . . . . . . . . 157
Output from the SQL precompiler . . . . 138 Example: SQL statements in PL/I programs . . 166
Listing. . . . . . . . . . . . . 138 Example: SQL statements in RPG/400 programs 171
Temporary source file members created by Example: SQL statements in ILE RPG programs 177
the SQL precompiler . . . . . . . . 139 Example: SQL statements in REXX programs 183
Sample SQL precompiler output . . . . 139 Report produced by example programs that use
Non-ILE SQL precompiler commands . . . . 143 SQL . . . . . . . . . . . . . . . 187
Compiling a non-ILE application program CL command descriptions for host language
that uses SQL . . . . . . . . . . . 144 precompilers . . . . . . . . . . . . . 188
ILE SQL precompiler commands . . . . . . 144 Create SQL COBOL Program command . . . 188
Compiling an ILE application program that Create SQL ILE COBOL Object command . . . 189
uses SQL . . . . . . . . . . . . . 145 Create SQL ILE C Object command . . . . . 189
Setting compiler options using the precompiler Create SQL ILE C++ Object command . . . . 189
commands . . . . . . . . . . . . . 146 Create SQL PL/I Program command . . . . 189
Interpreting compile errors in applications that Create SQL RPG Program command . . . . 189
use SQL . . . . . . . . . . . . . . 146 Create SQL ILE RPG Object command . . . . 189
Binding an application that uses SQL . . . . 147 Related information for Embedded SQL
Program references in applications that use programming . . . . . . . . . . . . . 189
SQL . . . . . . . . . . . . . . 147
Displaying SQL precompiler options . . . . 148 Notices . . . . . . . . . . . . . . 191
Running a program with embedded SQL . . . 148 Programming interface information . . . . . . 193
Running a program with embedded SQL: Trademarks . . . . . . . . . . . . . . 193
DDM considerations . . . . . . . . . 148 Terms and conditions. . . . . . . . . . . 193
Running a program with embedded SQL:
Override considerations . . . . . . . . 148
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 190.
| 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.
To view or download the PDF version of this document, select Embedded SQL programming.
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.
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
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.
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.
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).
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
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.
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.
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.
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.
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.
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
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
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
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.
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 */
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;
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.
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 */
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
{
}
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];
(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;
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.
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.
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.
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.
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 190.
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.
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
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 sqlcode;
short 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
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.
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:
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;
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
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 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>’;
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.
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.
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.
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.
The following trigraph sequences are supported within host variable declarations:
v ??( left bracket
v ??) right bracket
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.
This figure shows the syntax for valid numeric host variable declarations.
Numeric
► ▼ 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.
In addition, an SQL VARCHAR declare can be used to define a varchar host variable.
Single-character form
►► char ►
auto const unsigned
extern volatile signed
static
► ▼ variable-name ; ►◄
[ 1 ] = expression
►► char ►
auto const unsigned
extern volatile signed
static
► ▼ 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'
int
► short var-1 ; char var-2 [ length ] ; } ►
signed unsigned
signed
► ▼ 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;
struct VARCHAR {
short len;
char s[10];
} vstring;
Example
Single-graphic form
►► wchar_t ▼ variable-name ; ►◄
auto const = expression
extern volatile
static
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'
►► struct { ►
auto const _Packed tag
extern volatile
static
int
► short var-1 ; wchar_t var-2 [ length ] ; } ►
signed
► ▼ 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;
struct VARGRAPH {
short len;
wchar_t s[10];
} vstring;
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
► ; ►◄
VARBINARY
► ▼ 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
VARBINARY example
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.
► ▼ 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
DBCLOB example
BLOB example
LOB 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.
► ▼ 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.
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
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.
► ▼ 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
XML 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.
► ▼ 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.
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)
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
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.
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,
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 { short int lastname_len;
char lastname_text[15];
} lastname;
char workdept[4];
} pemp1;
.....
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 structures
►► struct { ►
auto const _Packed tag
extern volatile
static
► ▼ float ▼ var-1 ; } ►
double
decimal ( precision )
, scale
_Decimal32
_Decimal64
_Decimal128
int
long long
signed long
short
sqlint32
sqlint64
varchar-structure
vargraphic-structure
binary
lob
xml
SQL-varchar
rowid
result-set-locator
,
char ▼ var-2 ;
signed [ length ]
unsigned
,
wchar_t ▼ var-5 ;
[ length ]
► ▼ variable-name ; ►◄
= expression
varchar-structure:
int
struct { short var-3 ; ►
tag signed signed
unsigned
int
struct { short var-6 ; wchar_t var-7 [ length ] ; }
tag signed
lob:
xml:
SQL-varchar:
rowid:
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.
Host structure indicator array in C and C++ applications that use SQL
This figure shows the valid syntax for host structure indicator array declarations.
int
►► short ►
auto const signed
extern volatile
static
► ▼ variable-name [ dimension ] ; ►◄
= expression
In this C example,
struct {
_Packed struct{
char c1_var[20];
short c2_var;
} b_array[10];
} a_struct;
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;
...
►► _Packed struct { ►
auto const tag
extern volatile
static
► ▼ float ▼ var-1 ; } ►
double
decimal ( precision )
, scale
_Decimal32
_Decimal64
_Decimal128
int
long long
signed long
short
sqlint32
sqlint64
varchar-structure
vargraphic-structure
binary
lob
xml
SQL-varchar
rowid
result-set-locator
,
char ▼ var-2 ;
signed [ length ]
unsigned
,
wchar_t ▼ var-5 ;
[ length ]
► ▼ variable-name [ dimension ] ; ►◄
= expression
varchar-structure:
int
_Packed struct { short var-3 ; ►
tag signed signed
unsigned
vargraphic-structure:
int
_Packed struct { short var-6 ; ►
tag signed
binary:
lob:
xml:
SQL-varchar:
rowid:
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.
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.
►► struct { ►
auto const _Packed tag
extern volatile
static
int
► short var-1 [ dimension-1 ] ; } ►
signed
► ▼ 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; /* Ptr to an integer */
long **mynumptr; /* Ptr to a ptr to a long integer */
char *mychar; /* Ptr to a single character */
char(*mychara)[20]; /* Ptr to a char array of 20 bytes */
struct { /* Ptr to a variable char array of 30 */
short mylen; /* bytes. */
char mydata[30];
} *myvarchar;
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]; /* pointer to a null-terminated char array */
char *a[10]; /* 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:
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.
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
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.
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 Notes
SMALLINT short int
INTEGER long int
BIGINT long long int
DECIMAL(p,s) decimal(p,s) p is a positive integer from 1 to 63,
and s is a positive integer from 0 to
63.
NUMERIC(p,s) or nonzero scale No exact equivalent Use DECIMAL (p,s).
binary
DECFLOAT(16) _Decimal64 Only supported in C.
DECFLOAT(34) _Decimal128 Only supported in C.
FLOAT (single precision) float
FLOAT (double precision) double
CHAR(1) single-character form
CHAR(n) No exact equivalent If n>1, use NUL-terminated character
form.
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.
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
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: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 190.
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.
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.
When you use the INCLUDE statement, the SQL COBOL precompiler includes COBOL source statements
for the SQLCA:
01 SQLCA.
05 SQLCAID PIC X(8). VALUE X"0000000000000000".
05 SQLCABC PIC S9(9) BINARY.
05 SQLCODE PIC S9(9) BINARY.
05 SQLERRM.
49 SQLERRML PIC S9(4) BINARY.
49 SQLERRMC PIC X(70).
05 SQLERRP PIC X(8).
05 SQLERRD OCCURS 6 TIMES
PIC S9(9) BINARY.
05 SQLWARN.
10 SQLWARN0 PIC X.
10 SQLWARN1 PIC X.
10 SQLWARN2 PIC X.
10 SQLWARN3 PIC X.
10 SQLWARN4 PIC X.
10 SQLWARN5 PIC X.
10 SQLWARN6 PIC X.
10 SQLWARN7 PIC X.
10 SQLWARN8 PIC X.
10 SQLWARN9 PIC X.
10 SQLWARNA PIC X.
05 SQLSTATE 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
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.
1 SQLDA.
05 SQLDAID PIC X(8).
05 SQLDABC PIC S9(9) BINARY.
05 SQLN PIC S9(4) BINARY.
05 SQLD 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).
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
DECLARE VARIABLE
DECLARE STATEMENT
WORKING-STORAGE SECTION or LINKAGE SECTION
INCLUDE SQLCA
INCLUDE SQLDA
INCLUDE member-name DATA DIVISION or PROCEDURE DIVISION
Other 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
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.
COBOL COPY statements cannot be used to include SQL statements or declarations of COBOL host
variables that are referenced in SQL statements.
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.
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.
All host variables within an SQL statement must be preceded by a colon (:).
To accommodate using dashes within a COBOL host variable name, blanks must precede and follow a
minus sign.
This figure shows the syntax for valid integer host variable declarations.
IS
IS USAGE
►► 01 variable-name PICTURE picture-string ►
77 PIC
level-1
► BINARY . ►◄
COMPUTATIONAL-4 IS
COMP-4 VALUE numeric-constant
COMPUTATIONAL-5
COMP-5
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 variable-name PICTURE picture-string ►
77 PIC
level-1
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 variable-name PICTURE picture-string ►
77 PIC
level-1
► . ►◄
IS IS
USAGE VALUE numeric-constant
DISPLAY
display clause
display clause:
DISPLAY IS CHARACTER
SIGN LEADING SEPARATE
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.
This figure shows the syntax for valid floating-point host variable declarations. Floating-point host
variables are only supported for ILE COBOL.
IS
USAGE
►► 01 variable-name COMPUTATIONAL-1 ►
77 COMP-1
level-1 COMPUTATIONAL-2
COMP-2
► . ►◄
IS
VALUE numeric-constant
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.
There are two valid forms of character host variables: fixed-length strings and varying-length strings.
IS
►► 01 variable-name PICTURE picture-string ►
77 PIC IS
level-1 USAGE
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.
IS
►► 01 variable-name . 49 var-1 PICTURE picture-string-1 ►
level-1 PIC
IS
► 49 var-2 PICTURE picture-string-2 ►
PIC IS
USAGE
DISPLAY
► . ►◄
IS
VALUE 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.
IS
►► 01 variable-name PICTURE picture-string ►
77 PIC
level-1
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.
IS
►► 01 variable-name . 49 var-1 PICTURE picture-string-1 ►
level-1 PIC
IS
USAGE
► BINARY . ►
COMPUTATIONAL-4 IS
COMP-4 VALUE numeric-constant
COMPUTATIONAL-5
COMP-5
IS
IS USAGE
► 49 var-2 PICTURE picture-string-2 DISPLAY-1 ►
PIC NATIONAL
► . ►◄
IS
VALUE 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
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.
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.
IS
USAGE
►► 01 variable-name SQL TYPE IS BINARY ( length ) . ►◄
VARBINARY
BINARY VARYING
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
VARBINARY Example
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.
IS
USAGE
►► 01 variable-name SQL TYPE IS CLOB ( lob-length ) . ►◄
DBCLOB K
BLOB M
CLOB example
DBCLOB example
BLOB example
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.
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.
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
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.
IS
USAGE
►► 01 variable-name SQL TYPE IS XML AS CLOB ( lob-length ) ►
DBCLOB K
BLOB M
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
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.
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.
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)
This figure shows the syntax for valid date, time, and timestamp host variable declarations. Datetime host
variables are supported only for ILE COBOL.
OF IS
►► 01 variable-name FORMAT DATE format-options ►◄
77 TIME
level-1 TIMESTAMP
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 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
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.
IS
USAGE
►► 01 variable-name SQL TYPE IS RESULT_SET_LOCATOR . ►◄
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:
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 PIC X(6).
10 FIRSTNME.
49 FIRSTNME-LEN PIC S9(4) USAGE BINARY.
49 FIRSTNME-TEXT PIC X(12).
10 MIDINIT PIC X(1).
10 LASTNAME.
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.
►► level-1 variable-name . ►
IS
► ▼ level-2 var-1 PICTURE picture-string usage-clause . ►◄
PIC
floating-point .
. varchar-string .
. vargraphic-string .
binary .
lob .
xml .
datetime .
rowid .
result-set-locator .
usage-clause:
display-clause:
DISPLAY IS CHARACTER
SIGN LEADING SEPARATE
floating-point:
IS IS
USAGE VALUE constant
COMPUTATIONAL-1
COMP-1
COMPUTATIONAL-2
COMP-2
varchar-string:
IS
49 var-2 PICTURE picture-string-1 ►
PIC
IS
USAGE
► BINARY . ►
COMPUTATIONAL-4 IS
COMP-4 VALUE numeric-constant
COMPUTATIONAL-5
COMP-5
IS
► 49 var-3 PICTURE picture-string-2 ►
PIC
vargraphic-string:
IS
IS USAGE
49 var-2 PICTURE picture-string-1 BINARY ►
PIC COMPUTATIONAL-4
COMP-4
COMPUTATIONAL-5
COMP-5
► . ►
IS
VALUE numeric-constant
IS
IS USAGE
► 49 var-3 PICTURE picture-string-2 DISPLAY-1 ►
PIC NATIONAL
►
IS
VALUE constant
binary:
IS
USAGE
SQL TYPE IS BINARY ( length )
VARBINARY
BINARY VARYING
lob:
IS
USAGE
SQL TYPE IS CLOB ( lob-length )
DBCLOB K
BLOB M
CLOB-LOCATOR
DBCLOB-LOCATOR
BLOB-LOCATOR
CLOB-FILE
DBCLOB-FILE
BLOB-FILE
IS
USAGE
SQL TYPE IS XML AS CLOB ( lob-length )
DBCLOB K
BLOB M
XML-LOCATOR
XML AS CLOB-FILE
DBCLOB-FILE
BLOB-FILE
datetime:
OF IS
variable-name FORMAT DATE format-options
TIME
TIMESTAMP
IS IS
SIZE integer
rowid:
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.
IS
IS USAGE
►► level-1 variable-name PICTURE picture-string ►
PIC
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.
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.
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.
TIMES
►► level-1 variable-name OCCURS dimension . ►
IS
► ▼ level-2 var-1 PICTURE picture-string-1 usage-clause . ►◄
PIC
floating-point .
. varchar-string .
. vargraphic-string .
binary .
lob .
xml .
datetime .
rowid .
result-set-locator .
usage-clause:
IS IS
USAGE VALUE constant
BINARY
COMPUTATIONAL-4
COMP-4
COMPUTATIONAL-5
COMP-5
PACKED-DECIMAL
COMPUTATIONAL-3
COMP-3
COMPUTATIONAL
COMP
DISPLAY
display-clause
DISPLAY-1
NATIONAL
display-clause:
DISPLAY IS CHARACTER
SIGN LEADING SEPARATE
floating-point:
varchar-string:
IS
IS USAGE
49 var-2 PICTURE picture-string-2 BINARY ►
PIC COMPUTATIONAL-4
COMP-4
COMPUTATIONAL-5
COMP-5
► . ►
IS
VALUE numeric-constant
IS
► 49 var-3 PICTURE picture-string-3 ►
PIC IS
USAGE
DISPLAY
►
IS
VALUE constant
vargraphic-string:
IS
IS USAGE
49 var-2 PICTURE picture-string-2 BINARY ►
PIC COMPUTATIONAL-4
COMP-4
COMPUTATIONAL-5
COMP-5
► . ►
IS
VALUE numeric-constant
►
IS
VALUE constant
binary:
IS
USAGE
SQL TYPE IS BINARY ( length )
VARBINARY
BINARY VARYING
lob:
IS
USAGE
SQL TYPE IS CLOB ( lob-length )
DBCLOB K
BLOB M
CLOB-LOCATOR
DBCLOB-LOCATOR
BLOB-LOCATOR
CLOB-FILE
DBCLOB-FILE
BLOB-FILE
xml:
IS
USAGE
SQL TYPE IS XML AS CLOB ( lob-length )
DBCLOB K
BLOB M
XML-LOCATOR
XML AS CLOB-FILE
DBCLOB-FILE
BLOB-FILE
datetime:
OF IS
variable-name FORMAT DATE format-options
TIME
TIMESTAMP
IS IS
SIZE integer
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.
TIMES
►► level-1 variable-name OCCURS dimension . ►
IS
IS USAGE
► level-2 var-1 PICTURE picture-string BINARY ►
PIC COMPUTATIONAL-4
COMP-4
COMPUTATIONAL-5
COMP-5
► . ►◄
IS
VALUE 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.
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.
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.
...
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.
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 COBOL data type Notes
SMALLINT S9(m) COMP-4 or S9(m) COMP-5 m is from 1 to 4
INTEGER S9(m) COMP-4 or S9(m) COMP-5 m is from 5 to 9
BIGINT S9(m) COMP-4 or S9(m) COMP-5 for ILE m is from 10 to 18
COBOL.
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.
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
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 190.
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.
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.
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
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 ;
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
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.
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>’;
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.
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.
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.
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.
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.
This figure shows the syntax for valid scalar numeric-host variable declarations.
Numeric
►► DECLARE variable-name ►
DCL ,
( ▼ variable-name )
► BINARY FIXED ►
BIN ( precision )
FLOAT
( precision )
DECIMAL FIXED
DEC ( precision )
,scale
FLOAT
( precision )
PICTURE picture-string
► ; ►◄
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.
This figure shows the syntax for valid scalar character-host variables.
Character
► ; ►◄
Alignment and/or Scope and/or Storage
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.
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.
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
VARBINARY example
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
( ▼ variable-name )
Notes:
1. For BLOB and CLOB, 1 ≤ lob-length ≤ 32,766
2. SQL TYPE IS, BLOB, CLOB can be in mixed case.
CLOB example
BLOB example
The following figure shows the syntax for valid LOB locators.
LOB locator
Note: SQL TYPE IS, BLOB_LOCATOR, CLOB_LOCATOR, DBCLOB_LOCATOR can be in mixed case.
The following figure shows the syntax for valid LOB file reference variables.
Note: SQL TYPE IS, BLOB_FILE, CLOB_FILE, and DBCLOB_FILE can be in mixed case.
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
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
( ▼ variable-name )
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
►► DECLARE 1 variable-name , ►
DCL Scope and/or storage
level-1 variable-name ,
( ▼ var-2 )
data-types:
BINARY FIXED
BIN FLOAT ( precision ) UNALIGNED
DECIMAL FIXED
DEC ( precision )
, scale
FLOAT
( precision ) UNALIGNED
PICTURE picture-string
CHARACTER
CHAR ( length ) VARYING
VAR ALIGNED
SQL TYPE IS CLOB ( lob-length )
BLOB K
CLOB_LOCATOR
DBCLOB_LOCATOR
BLOB_LOCATOR
CLOB_FILE
DBCLOB_FILE
BLOB_FILE
SQL TYPE IS ROWID
SQL TYPE IS BINARY ( length )
VARBINARY
BINARY VARYING
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.
( ▼ variable-name ( dimension ) )
► ; ►◄
( precision ) Alignment and/or scope and/or storage
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;
( ▼ var-2 )
data-types:
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.
This figure shows the syntax diagram for the declaration of a valid host structure array indicator.
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.
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);
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.
If a host variable appears with an indicator variable, the SQLTYPE is the base SQLTYPE plus one.
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 PL/I equivalent Notes
SMALLINT BIN FIXED(p) p is a positive integer from 1 to 15.
INTEGER BIN FIXED(p) p is a positive integer from 16 to 31.
BIGINT No exact equivalent Use DEC FIXED(18).
DECIMAL(p,s) or NUMERIC(p,s) DEC FIXED(p) or DEC FIXED(p,s) or s (the scale factor) and p (the
PICTURE picture-string precision) are positive integers. p is a
positive integer from 1 to 31. s is a
positive integer from 0 to p.
DECFLOAT Not supported Not supported.
FLOAT (single precision) BIN FLOAT(p) or DEC FLOAT(m) p is a positive integer from 1 to 24.
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;
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
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: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 190.
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.
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 DS SQL
I* SQL COMMUNICATION AREA SQL
I I X’0000000000000000’ 1 8 SQLAID SQL
I B 9 120SQLABC 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
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
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
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.
To embed an RPG/400 comment within the SQL statement, place an asterisk (*) in position 7.
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
The /COPY statement can be used to include SQL statements or RPG/400 specifications.
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.
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.
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 (:).
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
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.
*...1....+....2....+....3....+....4....+....5....+....6....+....7. ..*
IPEMPL DS
I 01 06 EMPNO
I 07 18 FIRSTN
I 19 19 MIDINT
I 20 34 LASTNA
I 35 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.
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.
*...1....+....2....+....3....+....4....+....5....+....6....+....7....*
FTDEPT IP E DISK
F TDEPT KRENAMEDEPTREC
IDEPTREC
I DEPTNAME DEPTN
I ADMRDEPT 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.
*...1....+....2....+....3....+....4....+....5....+....6....+....7....*
ITDEPT E DSDEPARTMENT
I DEPTNAME DEPTN
I ADMRDEPT 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.
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.
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.
*...1....+....2....+....3....+....4....+....5....+....6....*
ITDEPT E DSDEPARTMENT 10
I DEPARTMENT DEPTN
I ADMRDEPT ADMRD
...
C/EXEC SQL
C+ DECLARE C1 CURSOR FOR
C+ SELECT *
C+ FROM CORPDATA.DEPARTMENT
C/END-EXEC
...
C/EXEC SQL
C+ FETCH C1 FOR 10 ROWS INTO :TDEPT
C/END-EXEC
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 RPG/400 data type Notes
SMALLINT Subfield of a data structure. B in position 43,
length must be 2 and 0 in position 52 of the
subfield specification.
INTEGER Subfield of a data structure. B in position 43,
length must be 4 and 0 in position 52 of the
subfield specification.
OR
OR
OR
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.
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.
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
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.
| 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.
For more information about programming using ILE RPG, see the ILE RPG Programmer's Guide
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);
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.
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 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
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.
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.
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;
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>'.
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.
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.
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.
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.
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
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 *NULL, *ALL, *INPUT, *OUTPUT, or *KEY.
The precompiler supports LIKEREC(intrecname), but does not support the optional second parameter.
| 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:
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.
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 DS
D MYCLOB_LEN 10U
D MYCLOB_DATA 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)
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 DS
D MYBLOB_LEN 10U
D MYBLOB_DATA 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.
BLOB, CLOB, and DBCLOB locators have similar syntax. Here is an example of a BLOB locator.
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.
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.
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
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.
Here are some examples of XML host variables in ILE RPG applications.
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.
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
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)
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:
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.
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.
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 DS
D EMPNO 01 06A
D FIRSTN 07 18A
D MIDINT 19 19A
D LASTNA 20 34A
D DEPTNO 35 37A
...
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, 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 DS
D sub1 4B 0
D sub2 9B 0
D sub3 20I 0
D sub4 9B 0
Dsecstruct DS QUALIFIED
D sub1 4A
D sub2 12A
D sub3 20I 0
D myvar 5A
D sub5 20A
D myvar S 10I 0
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;
EXEC SQL
SELECT * INTO :CustomerInfo.Name, :Buyer.Name FROM MYTABLE;
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.
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 DS OCCURS(10)
D DEPTNO 01 03A
D DEPTNM 04 32A
D MGRNO 33 38A
D ADMRD 39 41A
DIND_ARRAY DS OCCURS(10)
D INDS 5I 0 DIM(4)
...
C/EXEC SQL
C+ DECLARE C1 CURSOR FOR
C+ SELECT *
C+ FROM CORPDATA.DEPARTMENT
C/END-EXEC
...
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. Data structures with the DIM keyword cannot have a name that starts with 'TAB'. If the
| data structure name starts with 'TAB', the data structure is considered a table instead of an array and is
| not supported by SQL. A host variable reference with a subscript like MyStructure(index).Mysubfield is not
supported by SQL.
Example
Dfststruct DS DIM(10) QUALIFIED
D sub1 4B 0
D sub2 9B 0
D sub3 20I 0
D sub4 9B 0
C/EXEC SQL
C+ FETCH C1 FOR 10 ROWS INTO :fststruct
C/END-EXEC
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.
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 E DS EXTNAME(DEPARTMENT)
D DEPTN E EXTFLD(DEPTNAME)
D ADMRD E 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+ SELECT *
C+ FROM CORPDATA.DEPARTMENT
C/END-EXEC
...
C/EXEC SQL
C+ FETCH C1 FOR 10 ROWS
C+ INTO :DEPARTMENT
C/END-EXEC
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
4-byte binary with Free-form: 496 4 INTEGER
zero decimal v BINDEC(digits)
positions
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.
2-byte integer Free-form: 500 2 SMALLINT
v INT(5)
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.
Fixed-form:
v Data type = A or blank,
decimal positions blank,
length between 1 and
32766.
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
varying graphic Free-form: 464 m VARGRAPHIC(m) where
v VARGRAPH(n) m = n or m = (b-2)/2
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.
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 RPG data type Notes
SMALLINT Free-form:
v INT(5)
v BINDEC(n) where 1 <= n <= 4
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.
INTEGER 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.
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.
NUMERIC Free-form: Maximum length of 63 (precision 63)
v ZONED(p:s) and maximum scale of 63.
Fixed-form:
v Definition specification. S in
position 40 or blank in position 40
for a subfield, 0 through 63 in
position 41,42.
DECFLOAT Not supported Not supported
FLOAT (single precision) Free-form:
v FLOAT(4)
Fixed-form:
v Definition specification. F in
position 40, length must be 4.
FLOAT (double precision) Free-form:
v FLOAT(8)
Fixed-form:
v Definition specification. F in
position 40, length must be 8.
CHAR(n) Free-form: n can be from 1 to 32766.
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.
Fixed-form:
v A character field
v Definition specification with a T in
position 40.
v Input field defined with T in
position 36.
TIMESTAMP(n) Free-form: For a character field, the length must
v TIMESTAMP(n) be at least 19; to include fractional
seconds, the length can be 21 to 32. If
Fixed-form: less than 32, some fractional seconds
v A character field will be truncated.
v Definition specification with a Z in
position 40.
v Input field defined with Z in
position 36.
XML Not supported Use SQLTYPE keyword to declare an
XML.
DATALINK Not supported
ROWID Not supported Use SQLTYPE keyword to declare a
ROWID.
Result set locator Not supported Use SQLTYPE keyword to declare a
result set locator.
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.
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.
DIND_ARRAY DS OCCURS(10)
D INDS 5I 0 DIM(4)
...
C* setup number of sqlda entries and length of the sqlda
C eval sqld = 4
C eval sqln = 4
C eval sqldabc = 336
C*
C* setup the first entry in the sqlda
C*
C eval sqltype = 453
C eval sqllen = 3
C eval sql_var(1) = sqlvar
C*
C* setup the second entry in the sqlda
C*
C eval sqltype = 453
C eval sqllen = 29
C eval sql_var(2) = sqlvar
...
C*
C* setup the forth entry in the sqlda
C*
C eval sqltype = 453
C eval sqllen = 3
C eval sql_var(4) = sqlvar
...
C/EXEC SQL
C+ DECLARE C1 FOR
C+ SELECT *
C+ FROM CORPDATA.DEPARTMENT
C/EXEC SQL
C+ FETCH C1 FOR 10 ROWS
C+ USING DESCRIPTOR :SQLDA
C+ INTO :DEPARTMENT:IND_ARRAY
C/END-EXEC
...
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 *
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
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 190.
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.
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.
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
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 following SQL statements are not supported by the SQL/REXX interface:
Variable names should not begin with the characters 'SQL', 'RDI', 'DSN', 'RXSQL', or 'QRW'.
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.
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.
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’
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 SQL type description
code
A number with neither decimal point nor Signed integers 496/497 INTEGER
exponent. It can have a leading plus or minus
sign.
A number that includes a decimal point, but no Packed decimal 484/485 DECIMAL(m,n)
exponent,
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).
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.
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.
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.
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:
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
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
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
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.
Listing:
The output listing is sent to the printer file that is specified by the PRTFILE parameter of the CRTSQLxxx
command.
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.
The precompiler output can provide information about your program source.
xxxxST1 VxRxMx yymmdd Create SQL COBOL Program CBLTEST1 08/06/07 11:14:21 Page 1
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
1 A list of the options you specified when the SQL precompiler was called.
2 The date the source member was last changed.
1 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.
2 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.
3 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.
The CRTxxxPGM command is run specifying the program name, source file name, precompiler created
source member name, text, and USRPRF.
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.
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
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.
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.
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 ’’)’;
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.
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.
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.
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:
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.
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
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
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
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:
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.
2 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.
3 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.
Note: The program was precompiled using COMMIT(*CHG). (For REXX, *CHG is the default.)
6 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.
7 This SQL OPEN statement opens cursor C1 so that the rows can be fetched.
8 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.
9 This SQL FETCH statement returns all columns for cursor C1 and places the returned values into
the corresponding elements of the host structure.
10 After all rows are fetched, control is passed to this label. The SQL CLOSE statement closes cursor
C1.
11 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.
12 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.
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: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 190.
CROSS REFERENCE
Data Names Define Reference
commission 19 FLOAT(24)
54 75
done1 **** LABEL
81
done2 **** LABEL
126
employee_count 40 SMALL INTEGER PRECISION(4,0) IN rpt2
empno 31 VARCHAR(7) IN rpt1
85
name 32 VARCHAR(30) IN rpt1
86
percentage 20 FLOAT(24)
53
project_name 39 VARCHAR(37) IN rpt2
projno 38 VARCHAR(7) IN rpt2
raise_date 21 VARCHAR(12)
119
report_error **** LABEL
59
rpt1 34
rpt2 42 STRUCTURE
130
salary 33 FLOAT(24) IN rpt1
86
total_proj_cost 41 FLOAT(53) IN rpt2
update_error **** LABEL
50
work_days 18 SMALL INTEGER PRECISION(4,0)
115
ACTNO 74 SMALL INTEGER PRECISION(4,0) COLUMN (NOT NULL) IN CORPDATA.EMPPROJACT
BIRTHDATE 74 DATE(10) COLUMN IN CORPDATA.EMPLOYEE
BONUS 74 DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
COMM **** COLUMN
54 75
COMM 74 DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
CORPDATA **** SCHEMA
52 74 74 116 116 116
C1 71 CURSOR
78 85 95
C2 112 CURSOR
123 130 139
DEPTNO 27 VARCHAR(3) IN Proj_struct
DEPTNO 116 CHARACTER(3) COLUMN (NOT NULL) IN CORPDATA.PROJECT
EDLEVEL 74 SMALL INTEGER PRECISION(4,0) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
EMENDATE 74 DATE(10) COLUMN IN CORPDATA.EMPPROJACT
EMENDATE **** COLUMN
114
EMPLOYEE **** TABLE IN CORPDATA
52 74 116
EMPLOYEE **** TABLE
75 118
EMPNO **** COLUMN IN EMPPROJACT
72 75 76 118
EMPNO **** COLUMN IN EMPLOYEE
75 118
EMPNO 74 CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPPROJACT
EMPNO 74 CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
EMPPROJACT **** TABLE
72 75 113 117 118 120
EMPPROJACT **** TABLE IN CORPDATA
74 116
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.
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 190.
Related concepts:
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 190.
xxxxST1 VxRxMx yymmdd Create SQL PL/I Program PLIEX 08/06/07 12:53:36 Page 1
Source type...............PLI
Program name..............CORPDATA/PLIEX
Source file...............CORPDATA/SRC
Member....................PLIEX
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
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
1 /* A sample program that updates the salaries for those employees */ 100
2 /* whose current commission total is greater than or equal to the */ 200
3 /* value of COMMISSION. The salaries of those who qualify are */ 300
4 /* increased by the value of PERCENTAGE, retroactive to RAISE_DATE. */ 400
5 /* A report is generated showing the projects that these employees */ 500
6 /* have contributed to, ordered by project number and employee ID. */ 600
7 /* A second report shows each project having an end date occurring */ 700
8 /* after RAISE_DATE (that is, those projects potentially affected */ 800
9 /* by the retroactive raises) with its total salary expenses and a */ 900
10 /* count of employees who contributed to the project. */ 1000
11 /*********************************************************************/ 1100
12 1200
13 1300
14 PLIEX: PROC; 1400
15 1500
16 DCL RAISE_DATE CHAR(10); 1600
17 DCL WORK_DAYS FIXED BIN(15); 1700
18 DCL COMMISSION FIXED DECIMAL(8,2); 1800
19 DCL PERCENTAGE FIXED DECIMAL(5,2); 1900
20 2000
21 /* File declaration for sysprint */ 2100
22 DCL SYSPRINT FILE EXTERNAL OUTPUT STREAM PRINT; 2200
23 2300
24 /* Structure for report 1 */ 2400
25 DCL 1 RPT1, 2500
26 1%INCLUDE PROJECT (PROJECT, RECORD,,COMMA); 2600
27 15 EMPNO CHAR(6), 2700
28 15 NAME CHAR(30), 2800
29 15 SALARY FIXED DECIMAL(8,2); 2900
30 3000
31 /* Structure for report 2 */ 3100
32 DCL 1 RPT2, 3200
33 15 PROJNO CHAR(6), 3300
34 15 PROJECT_NAME CHAR(36), 3400
35 15 EMPLOYEE_COUNT FIXED BIN(15), 3500
36 15 TOTL_PROJ_COST FIXED DECIMAL(10,2); 3600
37 3700
38 2 EXEC SQL INCLUDE SQLCA; 3800
39 3900
40 COMMISSION = 2000.00; 4000
41 PERCENTAGE = 1.04; 4100
42 RAISE_DATE = ’1982-06-01’; 4200
43 WORK_DAYS = 253; 4300
44 OPEN FILE(SYSPRINT); 4400
45 4500
46 /* Update the selected employees’ salaries by the new percentage. */ 4600
47 /* If an error occurs during the update, roll back the changes. */ 4700
48 3 EXEC SQL WHENEVER SQLERROR GO TO UPDATE_ERROR; 4800
49 4 EXEC SQL 4900
50 UPDATE CORPDATA/EMPLOYEE 5000
51 SET SALARY = SALARY * :PERCENTAGE 5100
52 WHERE COMM >= :COMMISSION ; 5200
53 5300
54 /* Commit changes */ 5400
55 5 EXEC SQL 5500
56 COMMIT; 5600
57 EXEC SQL WHENEVER SQLERROR GO TO REPORT_ERROR; 5700
58 5800
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.
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 190.
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.
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 190.
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.
Note: By using the code examples, you agree to the terms of the “Code license and disclaimer
information” on page 190.
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.
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
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
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:
For license inquiries regarding double-byte (DBCS) information, contact the IBM Intellectual Property
Department in your country or send inquiries, in writing, to:
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.
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.
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.
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.
Notices 193
194 IBM i: Embedded SQL programming
IBM®
Printed in USA