Академический Документы
Профессиональный Документы
Культура Документы
IBM
SC41-5611-02
AS/400e series
IBM
SC41-5611-02
Note
Before using this information and the product it supports, be sure to read the information in Notices on page 679.
Contents
About DB2 for AS/400 SQL
Programming (SC41-5611) . . . . . .
Who should read this book. . . . . . . . .
Assumptions Relating to Examples of SQL
Statements . . . . . . . . . . . . .
How to Interpret Syntax Diagrams in this Guide
AS/400 Operations Navigator . . . . . . . .
Installing Operations Navigator subcomponents
Accessing AS/400 Operations Navigator . . .
How this book has changed . . . . . . . .
Prerequisite and related information. . . . . .
How to send your comments . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
xi
xi
xii
xiii
xiv
xiv
xv
xv
xv
1
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
13
13
14
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
14
15
16
17
20
23
25
27
28
28
29
xi
1
3
4
5
5
6
7
7
7
8
8
8
9
9
10
10
11
11
11
12
13
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
31
31
33
34
35
36
38
38
40
42
43
45
45
46
47
47
47
48
49
49
49
.
.
.
.
.
.
.
.
49
50
51
52
.
.
.
.
53
53
.
.
.
.
.
.
55
55
55
56
58
59
.
.
.
.
.
.
59
60
61
61
62
62
63
.
.
64
68
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
69
iii
69
70
70
71
72
72
75
75
77
77
78
79
79
80
82
83
84
84
85
87
87
87
90
90
91
91
93
95
95
95
96
102
105
106
106
107
109
109
. . . . 115
iv
97
97
98
100
100
101
. 115
. 116
. 121
. 122
. 122
. 123
. 124
. 125
. 129
. 131
. 132
. 133
143
. 145
. 145
. 146
. 146
.
.
.
.
.
147
147
148
149
150
. 153
. 157
. 158
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
161
162
165
167
. 168
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
171
172
173
174
174
174
175
175
175
175
175
175
176
176
176
182
183
185
185
. 186
. 188
. 188
189
. 190
. 193
. 193
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
195
196
197
197
197
198
198
198
198
198
199
199
199
199
199
205
206
207
208
209
211
212
. 213
. 213
.
.
. 215
. 216
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
217
218
218
219
219
219
219
219
219
220
220
220
220
222
222
223
. .
. .
. .
Types
. .
.
. 224
. 225
. 226
227
. 229
. 229
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
231
232
232
233
233
233
233
233
234
234
234
234
234
235
235
236
. 237
. 237
. 240
. 240
. 240
. 241
. 241
243
244
245
245
245
245
246
246
246
246
246
246
247
248
248
249
250
250
Declaration
. . . .
. . . .
. . . .
a Multiple
. . . .
and
. . 254
. . 255
. . 255
.
. 255
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
Variables
. . . .
. . . .
. . . .
257
257
259
260
260
260
260
260
260
261
261
261
261
263
263
263
265
266
266
267
272
272
273
273
274
275
275
276
277
277
278
278
278
278
vi
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
Interactive
. . . .
.
.
.
.
.
.
.
.
.
279
280
281
281
284
286
288
288
288
. 289
. 292
.
.
. 292
. 292
. 293
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
Pool (ASP)
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
295
296
296
296
297
297
299
299
303
304
305
305
306
307
307
.
.
.
.
.
309
309
310
310
311
. 311
. 312
. 318
. 322
. 322
322
. 322
. 323
. 323
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
325
325
326
343
345
348
348
350
350
350
363
365
366
368
368
368
369
373
375
376
378
379
379
380
380
381
381
382
383
384
384
385
386
387
387
388
389
389
390
390
391
391
392
.
.
.
.
.
.
. 395
. 395
. 395
. . .
a Table
. . .
. . .
. . .
.
.
.
.
.
.
.
.
.
.
396
396
397
398
398
399
400
401
402
402
405
405
405
406
407
407
409
409
410
410
411
414
415
416
417
418
418
420
421
421
423
. 424
. 424
.
.
.
.
.
.
425
426
428
428
429
430
.
.
.
.
.
.
Contents
. 433
. 433
. 434
vii
489
491
492
504
Purpose . . . . . . . . . . . . .
Parameters . . . . . . . . . . . .
Example . . . . . . . . . . . . .
PRTSQLINF (Print Structured Query Language
Information) Command . . . . . . . . .
Purpose . . . . . . . . . . . . .
Parameters . . . . . . . . . . . .
Example . . . . . . . . . . . . .
RUNSQLSTM (Run Structured Query Language
Statement) Command . . . . . . . . .
Purpose . . . . . . . . . . . . .
Parameters . . . . . . . . . . . .
Parameters for SQL procedures . . . . .
Example . . . . . . . . . . . . .
STRSQL (Start Structured Query Language)
Command . . . . . . . . . . . . .
Purpose . . . . . . . . . . . . .
Parameters . . . . . . . . . . . .
Example . . . . . . . . . . . . .
504
507
507
519
450
457
465
472
478
484
487
viii
519
522
522
535
535
538
538
550
551
554
554
566
566
569
569
581
581
584
584
596
597
598
598
600
601
603
604
615
615
. 615
. 616
. 616
.
.
.
.
617
617
617
618
.
.
.
.
.
618
620
620
626
628
.
.
.
.
628
630
630
635
637
637
637
637
638
653
653
.
.
.
.
.
.
.
.
.
.
.
.
.
.
669
670
671
671
671
671
672
672
672
672
673
673
673
673
. 674
. 676
. 676
Bibliography . . . . . . . . . . . . 677
Notices . . . . . . . . . . . . . . 679
Programming Interface Information .
. 680
Trademarks.
. 680
Index . . . . . . . . . . . . . . . 683
Contents
ix
v They are shown in the interactive SQL environment or they are written in ILE C
or in COBOL. EXEC SQL and END-EXEC are used to delimit an SQL statement
in a COBOL program. A description of how to use SQL statements in a COBOL
program is provided in Coding SQL Statements in COBOL Applications. A
description of how to use SQL statements in an ILE C program is provided in
Coding SQL Statements in C Applications.
v Each SQL example is shown on several lines, with each clause of the statement
on a separate line.
v SQL keywords are highlighted.
v Table names provided in Appendix A, DB2 for AS/400 Sample Tables, use the
collection CORPDATA. Table names that are not found in Appendix A, DB2 for
AS/400 Sample Tables, should use collections you create.
v Calculated columns are enclosed in parentheses, (), and brackets, [].
v The SQL naming convention is used.
v The APOST and APOSTSQL precompiler options are assumed although they are
not the default options in COBOL. Character string literals within SQL and host
language statements are delimited by apostrophes ().
v A sort sequence of *HEX is used, unless otherwise noted.
v The complete syntax of the SQL statement is usually not shown in any one
example. For the complete description and syntax of any of the statements
described in this guide, see the DB2 for AS/400 SQL Reference, SC41-5612
Copyright IBM Corp. 1997, 1998
xi
required_item
required_item
optional_item
If an optional item appears above the main path, that item has no effect on the
execution of the statement and is used only for readability.
optional_item
required_item
v If you can choose from two or more items, they appear vertically, in a stack.
If you must choose one of the items, one item of the stack appears on the main
path.
required_item
required_choice1
required_choice2
If choosing one of the items is optional, the entire stack appears below the main
path.
required_item
optional_choice1
optional_choice2
If one of the items is the default, it will appear above the main path and the
remaining choices will be shown below.
xii
default_choice
required_item
optional_choice
optional_choice
v An arrow returning to the left, above the main line, indicates an item that can be
repeated.
required_item
repeatable_item
If the repeat arrow contains a comma, you must separate repeated items with a
comma.
,
required_item
repeatable_item
A repeat arrow above a stack indicates that you can repeat the items in the
stack.
v Keywords appear in uppercase (for example, FROM). They must be spelled exactly
as shown. Variables appear in all lowercase letters (for example, column-name).
They represent user-supplied names or values.
v If punctuation marks, parentheses, arithmetic operators, or other such symbols
are shown, you must enter them as part of the syntax.
xiii
IBM recommends that you use this new interface. It has online help to guide you.
While we develop this interface, you will still need to use either of the following to
do some of your tasks:
v Graphical Access (which provides a graphical interface to AS/400 screens).
Graphical Access is part of the base Client Access.
v A traditional emulator such as PC5250.
xiv
v If
xv
xvi
SQL Concepts
DB2 for AS/400 SQL consists of the following main parts:
v SQL run-time support
SQL run-time parses SQL statements and runs any SQL statements. This support
is that part of the Operating System/400* (OS/400) licensed program which
allows applications that contain SQL statements to be run on systems where the
DB2 Query Manager and SQL Development Kit licensed program is not
installed.
|
|
|
|
|
|
|
|
v SQL precompilers
SQL precompilers support precompiling embedded SQL statements in host
languages. The following languages are supported:
SQL interactive interface allows you to create and run SQL statements. For more
information on interactive SQL, see Chapter 17. Using Interactive SQL.
Interactive SQL is part of the DB2 Query Manager and SQL Development Kit
licensed program.
v Run SQL Statements CL command
RUNSQLSTM allows you to run a series of SQL statements, which are stored in
a source file. The RUNSQLSTM command is part of the DB2 Query Manager
and SQL Development Kit licensed program. See Chapter 18. Using the SQL
Statement Processor for more information on the Run SQL Statements command.
v DB2 Query Manager for AS/400
DB2 Query Manager for AS/400 provides a prompt-driven interactive interface
that allows you to create data, add data, maintain data, and run reports on the
databases. Query Manager is part of the DB2 Query Manager and SQL
Development Kit licensed program. For more information, refer to the DB2 for
AS/400 Query Manager Use book.
v SQL REXX Interface
The SQL REXX interface allows you to run SQL statements in a REXX
procedure. This interface is part of the DB2 Query Manager and SQL
Development Kit licensed program. For more information on using SQL
statements in REXX procedures, see Chapter 15. Coding SQL Statements in
REXX Applications.
v SQL Call Level Interface
DB2 for AS/400 supports the SQL Call Level Interface. This allows users of any
of the ILE languages to access SQL functions directly through procedure calls to
a service program provided by the system. Using the SQL Call Level Interface,
one can perform all the SQL functions without the need for a precompile. This is
a standard set of procedure calls to prepare SQL statements, execute SQL
statements, fetch rows of data, and even do advanced functions such as
accessing the catalogs and binding program variables to output columns.
For a complete description of all the available functions, and their syntax, see
the DB2 for AS/400 SQL Call Level Interface (ODBC) book.
v QSQPRCED API
This Application Program Interface (API) provides an extended dynamic SQL
capability. SQL statements can be prepared into an SQL package and then
executed using this API. Statements prepared into a package by this API persist
until the package or statement is explicitly dropped. QSQPRCED is part of the
OS/400 licensed program. For more information on the QSQPRCED API, see the
System API Reference book.
v QSQCHKS API
This API syntax checks SQL statements. QSQCHKS is part of the OS/400
licensed program. For more information on the QSQCHKS API, see the System
API Reference book.
v DB2 Multisystem
This feature of the operating system allows your data to be distributed across
multiple AS/400 systems. For more information on DB2 Multisystem, see the
DB2 Multisystem for AS/400 book.
v DB2 Symmetric Multiprocessing
This feature of the operating system provides the query optimizer with
additional methods for retrieving data that include parallel processing.
Symmetric multiprocessing (SMP) is a form of parallelism achieved on a single
system where multiple processors (CPU and I/O processors) that share memory
and disk resource work simultaneously towards achieving a single end result.
This parallel processing means that the database manager can have more than
one (or all) of the system processors working on a single query simultaneously.
See Controlling Parallel Processing on page 391 for information on how to
control parallel processing.
SQL Terminology
There are two naming conventions that can be used in DB2 for AS/400
programming: system (*SYS) and SQL (*SQL). The naming convention used affects
the method for qualifying file and table names and the terms used on the
interactive SQL displays. The naming convention used is selected by a parameter
on the SQL commands or, for REXX, selected through the SET OPTION statement.
System naming (*SYS): In the system naming convention, files are qualified by
library name in the form:
library/file
If the table name is not explicitly qualified and a default collection name is
specified for the default relational database collection (DFTRDBCOL) parameter of
the CRTSQLxxx 1 or the CRTSQLPKG commands, the default collection name is
used. If the table name is not explicitly qualified and the default collection name is
not specified, the qualification rules are:
v The following CREATE statements resolve to unqualified objects as follows:
CREATE TABLE The table is created in the current library (*CURLIB).
1. The xxx in this command refers to the host language indicators: CI for the ILE C for AS/400 language, CPPI for the ILE C++ for
AS/400 language, CBL for the COBOL for AS/400 language, CBLI for the ILE COBOL for AS/400 language, PLI for the AS/400
PL/I language, RPG for the RPG for AS/400 language, and RPGI for the ILE RPG for AS/400 language. The CVTSQLCPP
command is considered part of this group of commands even though it does not start with CRT.
Chapter 1. Introduction to DB2 for AS/400 Structured Query Language
CREATE VIEW The view is created in the first library referenced in the
subselect.
CREATE INDEX The index is created into the collection or library that
contains the table on which the index is being built.
CREATE ALIAS The alias is created into the collection or library that
contains the table for which you defined the alias. If the table is not qualified
or is not found, the alias is created in the current library (*CURLIB).
CREATE PROCEDURE The procedure is created in the current library
(*CURLIB).
v All other SQL statements cause SQL to search the library list (*LIBL) for the
unqualified table.
|
|
If the table name is not explicitly qualified and the default collection name is
specified in the default relational database collection (DFTRDBCOL) parameter of
the CRTSQLxxx command, the default collection name is used. If the table name is
not explicitly qualified and the default collection name is not specified, the rules
are:
v For static SQL, the default qualifier is the user profile of the program owner.
v For dynamic SQL or interactive SQL, the default qualifier is the user profile of
the job running the statement.
|
|
|
|
|
|
Miscellaneous Statements
BEGIN DECLARE SECTION
CALL
CONNECT
DECLARE PROCEDURE
DECLARE STATEMENT
DECLARE VARIABLE
DESCRIBE TABLE
DISCONNECT
END DECLARE SECTION
INCLUDE
RELEASE
SET CONNECTION
SET OPTION
SET RESULT SETS
SET TRANSACTION
WHENEVER
SQL Objects
|
|
SQL objects used on the AS/400 system are collections, tables, aliases, views, SQL
packages, indexes, and catalogs. SQL creates and maintains these objects as AS/400
database objects. A brief description of these objects follows.
Collections
A collection provides a logical grouping of SQL objects. A collection consists of a
library, a journal, a journal receiver, a catalog, and optionally, a data dictionary.
Tables, views, and system objects (such as programs) can be created, moved, or
restored into any AS/400 library. All AS/400 files can be created or moved into an
SQL collection if the SQL collection does not contain a data dictionary. If the SQL
collection contains a data dictionary then:
v AS/400 source physical files or nonsource physical files with one member can be
created, moved, or restored into an SQL collection.
v AS/400 logical files cannot be placed in an SQL collection because they cannot
be described in the data dictionary.
You can create and own many collections.
Data Dictionary
A collection contains a data dictionary if it was created prior to Version 3 Release 1
or if the WITH DATA DICTIONARY clause was specified on the CREATE
COLLECTION or the CREATE SCHEMA statements. A data dictionary is a set of
tables containing object definitions. If SQL created the dictionary, then it is
automatically maintained by the system. You can work with data dictionaries by
using the interactive data definition utility (IDDU), which is part of the OS/400
program. For more information on IDDU, see the IDDU Use book.
Catalogs
An SQL catalog consists of a set of tables and views which describe tables, views,
indexes, packages, procedures, files, and constraints. This information is contained
in a set of cross-reference tables in libraries QSYS and QSYS2. Library QSYS2 also
contains a set of catalog views built over the QSYS catalog tables which describe
information about all the tables, views, indexes, packages, procedures, files, and
constraints on the system. In each SQL collection there is a set of views built over
the catalog tables which contains information about the tables, views, indexes,
packages, files, and constraints in the collection.
A catalog is automatically created when you create a collection. You cannot drop or
explicitly change the catalog.
For more information about SQL catalogs, see the DB2 for AS/400 SQL Reference
book.
Rows
DEPTNO
DEPTMGR
PRSTAFF
MFG AUTOMATION
D11
000060
12
MA2110
MFG PROGRAMMING
E21
000100
MA2112
ROBOT DESIGN
E01
000050
MA2113
D11
000060
...
...
...
PROJNO
PROJNAME
MA2100
...
...
RV2W573-0
Aliases
An alias is an alternate name for a table or view. You can use an alias to refer to a
table or view in those cases where an existing table or view can be referred to. For
more information on aliases, see the DB2 for AS/400 SQL Reference book.
|
|
Views
A view appears like a table to an application program; however, a view contains
no data. It is created over one or more tables. A view can contain all the columns
of given tables or some subset of them, and can contain all the rows of given tables
or some subset of them. The columns can be arranged differently in a view than
they are in the tables from which they are taken. A view in SQL is a special form
of a nonkeyed logical file.
The following figure shows a view created from the preceding example of an SQL
table. Notice that the view is created only over the PROJNO and PROJNAME
columns of the table and for rows MA2110 and MA2100.
Columns
Rows
PROJNO
PROJNAME
MA2100
MFG AUTOMATION
MA2110
MFG PROGRAMMING
RV2W574-0
Indexes
An SQL index is a subset of the data in the columns of a table that are logically
arranged in either ascending or descending order. Each index contains a separate
arrangement. These arrangements are used for ordering (ORDER BY clause),
grouping (GROUP BY clause), and joining. An SQL index is a keyed logical file.
The index is used by the system for faster data retrieval. Creating an index is
optional. You can create any number of indexes. You can create or drop an index at
Chapter 1. Introduction to DB2 for AS/400 Structured Query Language
any time. The index is automatically maintained by the system. However, because
the indexes are maintained by the system, a large number of indexes can adversely
affect the performance of applications that change the table.
Constraints
Constraints are rules enforced by the database manager. DB2 for AS/400 supports
the following constraints:
v Unique constraints
A unique constraint is the rule that the values of the key are valid only if they
are unique. Unique constraints can be created using the CREATE TABLE and
ALTER TABLE statements. 2
Unique constraints are enforced during the execution of INSERT and UPDATE
statements. A PRIMARY KEY constraint is a form of UNIQUE constraint. The
difference is that a PRIMARY KEY cannot contain any nullable columns.
v Referential constraints
A referential constraint is the rule that the values of the foreign key are valid
only if:
They appear as values of a parent key, or
Some component of the foreign key is null.
Referential constraints are enforced during the execution of INSERT, UPDATE,
and DELETE statements.
v Check constraints
A check constraint is a rule that limits the values allowed in a column or group
of columns. Check constraints can be added using the CREATE TABLE and
ALTER TABLE statements. Check constraints are enforced during the execution
of INSERT and UPDATE statements. To satisfy the constraint, each row of data
inserted or updated in the table must make the specified condition either TRUE
or unknown (due to a null value).
For more information on constraints, see Chapter 6. Data Integrity.
Triggers
A trigger is a set of actions that are executed automatically whenever a specified
event occurs to a specified base table. An event can be an insert, update, or delete
operation. The trigger can be run either before or after the event. For more
information on triggers, see Chapter 6. Data Integrity in this book or see the DB2
for AS/400 Database Programming book.
Stored Procedures
A stored procedure is a program that can be called using the SQL CALL statement.
DB2 for AS/400 supports external stored procedures and SQL procedures. External
stored procedures can be any AS/400 program or REXX procedure. They cannot be
System/36 programs or procedures. An SQL procedure is defined entirely in SQL
and can contain SQL statements including SQL control statements. For more
information on stored procedures, see Chapter 7. Stored Procedures.
2. Although CREATE INDEX can create a unique index that also guarantees uniqueness, such an index is not a constraint.
Packages
An SQL package is an object that contains the control structure produced when the
SQL statements in an application program are bound to a remote relational
database management system (DBMS). The DBMS uses the control structure to
process SQL statements encountered while running the application program.
SQL packages are created when a relational database name (RDB parameter) is
specified on a Create SQL (CRTSQLxxx) command and a program object is created.
Packages can also be created using the CRTSQLPKG command. For more
information about packages and distributed relational database function, see
Chapter 24. Distributed Relational Database Function
SQL packages can also be created using the QSQPRCED API. For more information
on QSQPRCED, see the System API Reference book.
Precompile
Temporary
Source
File
Member
Processed
SQL
Statements
Compile
Program
Access
Plan
RV2W565-1
With a nondistributed ILE DB2 for AS/400 program, you may need to manage the
original source, the modules, and the resulting program or service program. The
following shows the objects involved and steps that happen during the precompile
and compile processes for a nondistributed ILE DB2 for AS/400 program when
OBJTYPE(*PGM) is specified on the precompile command:
User
Source Precompile
File
Member
Temporary
Source
File
Member
Compile
Processed
SQL
Statements
Bind
Module
Processed
SQL
Statements
Program
Access
Plan
RV2W569-0
With a distributed non-ILE DB2 for AS/400 program, you must manage the
original source, the resulting program, and the resulting package. The following
shows the objects and steps that occur during the precompile and compile
processes for a distributed non-ILE DB2 for AS/400 program:
User
Source
File
Member
Precompile
Temporary
Source
File
Member
Create
Compile
Program
SQL
Package
Processed
SQL
Statements
Access
Plan
SQL
Package
Access
Plan
RV2W566-2
With a distributed ILE DB2 for AS/400 program, you must manage the original
source, module objects, the resulting program or service program, and the resulting
packages. An SQL package can be created for each distributed module in a
distributed ILE program or service program. The following shows the objects and
steps that occur during the precompile and compile processes for a distributed ILE
DB2 for AS/400 program:
User
Source
File
Member
Precompile
Temporary
Source
File
Member
Compile
Processed
SQL
Statements
Module
Processed
SQL
Statements
Bind
Program
Access
Plan
Create
SQL
Package
SQL
Package
Access
Plan
RV2W570-1
Note: The access plans associated with the DB2 for AS/400 distributed program
object are not created until the program is run locally.
|
|
|
|
10
|
|
|
job completes. You can specify the output source file as a permanent file name on
the precompile commands. A member with the same name as the program name is
added to the output source file. This member contains the following items:
|
|
v Calls to the SQL run-time support, which have replaced embedded SQL
statements
v Parsed and syntax-checked SQL statements
|
|
|
By default, the precompiler calls the host language compiler. For more information
on precompilers, see Chapter 16. Preparing and Running a Program with SQL
Statements.
Program
A program is the object which you can run that is created as a result of the
compile process for non-ILE compiles or as a result of the bind process for ILE
compiles.
An access plan is a set of internal structures and information that tells SQL how to
run an embedded SQL statement most effectively. It is created only when the
program has successfully created. Access plans are not created during program
creation for SQL statements if the statements:
v Refer to a table or view that cannot be found
v Refer to a table or view to which you are not authorized
The access plans for such statements are created when the program is run. If, at
that time, the table or view still cannot be found or you are still not authorized, a
negative SQLCODE is returned. Access plans are stored and maintained in the
program object for nondistributed SQL programs and in the SQL package for
distributed SQL programs.
Package
An SQL package contains the access plans for a distributed SQL program.
An SQL package is an object that is created when:
v A distributed SQL program is successfully created using the RDB parameter on
CRTSQLxxx commands.
v When the Create SQL Package (CRTSQLPKG) command is run.
When a distributed SQL program is created, the name of the SQL package and an
internal consistency token are saved in the program. These are used at run time to
find the SQL package and to verify that the SQL package is correct for this
program. Because the name of the SQL package is critical for running distributed
SQL programs, an SQL package cannot be:
v Moved
v Renamed
v Duplicated
v Restored to a different library
Module
|
|
11
CRTBNDxxx commands where xxx is C, CBL, CPP, or RPG). You can run a module
only if you use the Create Program (CRTPGM) command to bind it into a
program. You usually bind several modules together, but you can bind a module
by itself. Modules contain information about the SQL statements; however, the SQL
access plans are not created until the modules are bound into either a program or
service program.
|
|
|
|
|
Service Program
A service program is an Integrated Language Environment (ILE) object that
provides a means of packaging externally supported callable routines (functions or
procedures) into a separate object. Bound programs and other service programs
can access these routines by resolving their imports to the exports provided by a
service program. The connections to these services are made when the calling
programs are created. This improves call performance to these routines without
including the code in the calling program.
12
and press Enter. When the Enter SQL Statements display appears, you are ready to
start typing SQL Statements. For more information on interactive SQL and the
STRSQL command, see Chapter 17. Using Interactive SQL.
|
|
If you are reusing an existing interactive SQL session, make sure that you set the
naming mode to SQL naming. You can specify this on the F13 (Services) panel,
option 1 (Change session attributes).
Note: Running this statement causes several objects to be created and takes several
seconds.
After you have successfully created a collection, you can create tables, views, and
indexes in it. Tables, views, and indexes can also be created in libraries instead of
collections.
13
INVENTORY_LIST______
SAMPLECOLL__
Name
Name, F4 for list
Column
ITEM_NUMBER_______
ITEM_NAME_________
UNIT_COST_________
QUANTITY_ON_HAND__
LAST_ORDER_DATE___
ORDER_QUANTITY____
__________________
FOR Column
____________
____________
____________
____________
____________
____________
____________
Type
Length Scale
CHAR____________ 6____
__
VARCHAR_________
20___
__
DECIMAL_________
8____
2_
SMALLINT________
_____
__
DATE____________
_____
__
SMALLINT________
_____
__
________________
_____
__
Table CONSTRAINT . . . . . . . . . . . . .
Distributed Table . . . . . . . . . . . .
F3=Exit
F4=Prompt
F11=Display more attributes
F5=Refresh
F12=Cancel
N
N
Y=Yes, N=No
Y=Yes, N=No
F6=Insert line
F14=Delete line
Nulls
2
3
3
1
1
1
3
Bottom
F10=Copy line
F24=More keys
Type the table name and collection name of the table you are creating,
INVENTORY_LIST in SAMPLECOLL, for the Table and Collection prompts. Each
column you want to define for the table is represented by an entry in the list on
the lower part of the display. For each column, type the name of the column, the
data type of the column, its length and scale, and the null attribute.
Press F11 to see more attributes that can be specified for the columns. This is
where a default value may be specified.
14
INVENTORY_LIST______
SAMPLECOLL__
Name
Name, F4 for list
Column
ITEM NUMBER_______
ITEM NAME_________
UNIT_COST_________
QUANTITY_ON_HAND__
LAST_ORDER_DATE___
ORDER_QUANTITY____
__________________
Data
_
_
_
_
_
_
_
Allocate
_____
_____
_____
_____
_____
_____
_____
Table CONSTRAINT . . . . . . . . . . . . .
Distributed Table . . . . . . . . . . . .
F3=Exit
F4=Prompt
F11=Display more attributes
F5=Refresh
F12=Cancel
N
N
Y=Yes, N=No
Y=Yes, N=No
F6=Insert line
F14=Delete line
F10=Copy line
F24=More keys
15
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1=Table or view
2=Column
3=Package
4=Alias
Table or view
Collection . .
INVENTORY_LIST______
SAMPLECOLL__
Option . . . . .
1=Column heading
2=Text
F3=Exit
F4=Prompt
F5=Refresh
F21=Display statement
F12=Cancel
Type in the name of the table and collection containing the columns for which you
want to add labels and press Enter. The following display will be shown,
prompting you for each of the columns in the table.
16
F3=Exit
F14=Delete line
Column Heading
....+....1....+....2....+....3....+....4....+....5....
'ITEM
NUMBER'___________________________
'ITEM
NAME'_____________________________
'UNIT
COST'_____________________________
'QUANTITY
ON
HAND'_________
'LAST
ORDER
DATE'_________
'NUMBER
ORDERED'__________________________
Bottom
F5=Refresh
F6=Insert line
F10=Copy line
F12=Cancel
F19=Display system column names
F24=More keys
Type the column headings for each of the columns. Column headings are defined
in 20 character sections. Each section will be displayed on a different line when
showing the output of a SELECT statement. The ruler across the top of the column
heading entry area can be used to easily space the headings correctly. When the
headings are typed, press Enter.
The following message indicates that the LABEL ON statement was successful.
LABEL ON for INVEN00001 in SAMPLECOLL completed.
The table name in the message is the system table name for this table, not the
name that was actually specified in the statement. DB2 for AS/400 maintains two
names for tables with names longer than ten characters. For more information on
system table names, see the CREATE TABLE statement in the DB2 for AS/400 SQL
Reference book.
The LABEL ON statement can also be keyed in directly on the Enter SQL
statements display as follows:
LABEL ON SAMPLECOLL/INVENTORY_LIST
(ITEM_NUMBER
IS 'ITEM
ITEM_NAME
IS 'ITEM
UNIT_COST
IS 'UNIT
QUANTITY_ON_HAND IS 'QUANTITY
LAST_ORDER_DATE IS 'LAST
ORDER_QUANTITY
IS 'NUMBER
NUMBER',
NAME',
COST',
ON
ORDER
ORDERED')
HAND',
DATE',
17
INVENTORY_LIST______
SAMPLECOLL__
Y
1
Y=Yes, N=No
1=Input VALUES
2=Subselect
. .
F3=Exit
F4=Prompt F5=Refresh
F21=Display statement
F12=Cancel
Type the table name and collection name in the input fields as shown. Change the
Select columns to insert INTO prompt to Yes. Press Enter to see the display where
the columns you want to insert values into can be selected.
Specify INSERT Statement
Type sequence numbers (1-999) to make selections, press Enter.
Seq
1__
2__
3__
4__
___
___
Column
ITEM_NUMBER
ITEM_NAME
UNIT_COST
QUANTITY_ON_HAND
LAST_ORDER_DATE
ORDER_QUANTITY
F3=Exit
F5=Refresh
F20=Display entire name
Type
CHARACTER
VARCHAR
DECIMAL
SMALLINT
DATE
SMALLINT
Digits
8 2
4
Length
6
20
F12=Cancel
F19=Display system column names
F21=Display statement
Bottom
In this example, we only want to insert into four of the columns. We will let the
other columns have their default value inserted. The sequence numbers on this
display indicate the order that the columns and values will be listed in the INSERT
statement. Press Enter to show the display where values for the selected columns
can be typed.
18
F3=Exit
F12=Cancel
Value
'153047'_____________________________________________
'Pencils, red'_______________________________________
10.00________________________________________________
25___________________________________________________
Bottom
F5=Refresh
F6=Insert line
F10=Copy line
F11=Display type
F14=Delete line
F15=Split line
F24=More keys
Note: To see the data type and length for each of the columns in the insert list,
press F11 (Display type). This will show a different view of the insert values
display, providing information about the column definition.
Type the values to be inserted for all of the columns and press Enter. A row
containing these values will be added to the table. The values for the columns that
were not specified will have a default value inserted. For LAST_ORDER_DATE it
will be the null value since no default was provided and the column allows the
null value. For ORDER_QUANTITY it will be 20, the value specified as the default
value on the CREATE TABLE statement.
This INSERT statement can be keyed directly on the Enter SQL Statements display
as:
INSERT INTO SAMPLECOLL.INVENTORY_LIST
(ITEM_NUMBER,
ITEM_NAME,
UNIT_COST,
QUANTITY_ON_HAND)
VALUES('153047',
'Pencils, red',
10.00,
25)
To add the next row to the table, press F9 (Retrieve) on the Enter SQL Statements
display. This will copy the previous INSERT statement to the typing area. You can
either type over the values from the previous INSERT statement or press F4
(Prompt) to use the Interactive SQL displays to enter data.
Continue using the INSERT statement to add the following rows to the table.
Values not shown in the chart below should not be inserted so that the default will
be used. In the INSERT statement column list, specify only the column names for
which you want to insert a value. For example, to insert the third row, you would
specify only ITEM_NUMBER and UNIT_COST for the column names and only the
two values for these columns in the VALUES list.
ITEM_NUMBER
ITEM_NAME
UNIT_COST
QUANTITY_ON_HAND
153047
Pencils, red
10.00
25
Chapter 2. Getting Started with SQL
19
ITEM_NUMBER
ITEM_NAME
UNIT_COST
QUANTITY_ON_HAND
229740
Lined tablets
1.50
120
544931
5.00
303476
Paper clips
2.00
100
559343
Envelopes, legal
3.00
500
291124
Envelopes, standard
775298
Chairs, secretary
225.00
073956
Pens, black
20.00
25
ITEM_NUMBER
SUPPLIER_COST
1234
153047
10.00
1234
229740
1.00
1234
303476
3.00
9988
153047
8.00
9988
559343
3.00
2424
153047
9.00
2424
303476
2.50
5546
775298
225.00
3366
303476
1.50
3366
073956
17.00
The sample collection now contains two tables with several rows of data in each.
20
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
SAMPLECOLL.INVENTORY_LIST____________________
*____________________________________________
_____________________________________________
_____________________________________________
_____________________________________________
_____________________________________________
_____________________________________________
Bottom
F3=Exit
F10=Copy line
N
N
N
Y=Yes, N=No
Y=Yes, N=No
Y=Yes, N=No
F4=Prompt
F5=Refresh
F6=Insert line
F9=Specify subquery
F12=Cancel
F14=Delete line
F15=Split line
F24=More keys
Type the table name in the FROM tables field on the display. To select all columns
from the table, type * for the SELECT columns field on the display. Press Enter and
the statement will run to select all of the data for all of the columns in the table.
The following output will be shown:
Display Data
Data width . . . . . . :
Position to line . . . . .
Shift to column . . . . . .
....+....1....+....2....+....3....+....4....+....5....+....6....+....7.
ITEM
ITEM
UNIT
QUANTITY LAST
NUMBER
NUMBER NAME
COST
ON
ORDER
ORDERED
HAND
DATE
153047 Pencils, red
10.00
25
20
229740 Lined tablets
1.50
120
20
544931 ***UNKNOWN***
5.00
- 20
303476 Paper clips
2.00
100
20
559343 Envelopes, legal
3.00
500
20
291124 Envelopes, standard
.00
- 20
775298 Chairs, secretary
225.00
6
20
073956 Pens, black
20.00
25
20
******** End of data ********
F3=Exit
F12=Cancel
F19=Left
F20=Right
71
F21=Split
The column headings that were defined using the LABEL ON statement are
shown. The ITEM_NAME for the third entry has the default value that was
specified in the CREATE TABLE statement. The QUANTITY_ON_HAND column
has a null value for the rows where no value was inserted. The
LAST_ORDER_DATE column contains all null values since that column is not in
any of the INSERT statements and the column was not defined to have a default
value. Similarly, the ORDER_QUANTITY column contains the default value for all
rows.
This statement could be entered on the Enter SQL Statements display as:
SELECT *
FROM SAMPLECOLL.INVENTORY_LIST
To limit the number of columns returned by the SELECT statement, the columns
you want to see must be specified. To restrict the number of output rows returned,
the WHERE clause is used. To see only the items that cost more than 10 dollars,
Chapter 2. Getting Started with SQL
21
and only have the values for the columns ITEM_NUMBER, UNIT_COST, and
ITEM_NAME returned, type SELECT and press F4 (Prompt). The Specify SELECT
Statement display will be shown.
Specify SELECT Statement
Type SELECT statement information.
FROM tables . . . . .
SELECT columns . . . .
WHERE conditions . . .
GROUP BY columns . . .
HAVING conditions . .
ORDER BY columns . . .
FOR UPDATE OF columns
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
SAMPLECOLL.INVENTORY_LIST____________________
ITEM_NUMBER, UNIT_COST, ITEM_NAME____________
UNIT_COST > 10.00____________________________
_____________________________________________
_____________________________________________
_____________________________________________
_____________________________________________
Bottom
F3=Exit
F10=Copy line
N
N
N
Y=Yes, N=No
Y=Yes, N=No
Y=Yes, N=No
F4=Prompt
F5=Refresh
F6=Insert line
F9=Specify subquery
F12=Cancel
F14=Delete line
F15=Split line
F24=More keys
Although only one line is initially shown for each prompt on the Specify SELECT
Statement display, F6 (Insert line) can be used to add more lines to any of the
input areas in the top part of the display. This could be used if more columns were
to be entered in the SELECT columns list, or a longer, more complex WHERE
condition were needed.
Fill in the display as shown above. When Enter is pressed, the SELECT statement
is run. The following output will be seen:
Display Data
Data width . . . . . . :
Position to line . . . . .
Shift to column . . . . . .
....+....1....+....2....+....3....+....4.
ITEM
UNIT ITEM
NUMBER
COST
NAME
775298
225.00 Chairs, secretary
073956
20.00 Pens, black
******** End of data ********
F3=Exit
F12=Cancel
F19=Left
F20=Right
41
F21=Split
The only rows returned are those whose data values compare with the condition
specified in the WHERE clause. Furthermore, the only data values returned are
from the columns you explicitly specified in the SELECT clause. Data values of
columns other than those explicitly identified are not returned.
This statement could have been entered on the Enter SQL Statements display as:
SELECT ITEM_NUMBER, UNIT_COST, ITEM_NAME
FROM SAMPLECOLL.INVENTORY_LIST
WHERE UNIT_COST > 10.00
22
23
Display Data
Data width . . . . . . :
Position to line . . . . .
Shift to column . . . . . .
....+....1....+....2....+....3....+....4....+
SUPPLIER_NUMBER ITEM
ITEM
NUMBER NAME
1234
153047 Pencils, red
9988
153047 Pencils, red
2424
153047 Pencils, red
1234
229740 Lined tablets
1234
303476 Paper clips
2424
303476 Paper clips
3366
303476 Paper clips
9988
559343 Envelopes, legal
5546
775298 Chairs, secretary
3366
073956 Pens, black
******** End of data ********
F3=Exit
F12=Cancel
F19=Left
F20=Right
45
F21=Split
The data values in the result table represent a composite of the data values
contained in the two tables INVENTORY_LIST and SUPPLIERS. This result table
contains the supplier number from the SUPPLIER table and the item number and
item name from the INVENTORY_LIST table. Any item numbers that do not
appear in the SUPPLIER table are not shown in this result table. The results are not
guaranteed to be in any order unless the ORDER BY clause is specified for the
SELECT statement. Since we did not change any column headings for the
SUPPLIER table, the SUPPLIER_NUMBER column name is used as the column
heading.
The following is an example of using ORDER BY to guarantee the order of the
rows. The statement will first order the result table by the SUPPLIER_NUMBER
column. Rows with the same value for SUPPLIER_NUMBER will be ordered by
their ITEM_NUMBER.
SELECT SUPPLIER_NUMBER, Y.ITEM_NUMBER, ITEM_NAME
FROM SAMPLECOLL.SUPPLIERS X, SAMPLECOLL.INVENTORY_LIST Y
WHERE X.ITEM_NUMBER = Y.ITEM_NUMBER
ORDER BY SUPPLIER_NUMBER, Y.ITEM_NUMBER
24
Display Data
Data width . . . . . . :
Position to line . . . . .
Shift to column . . . . . .
....+....1....+....2....+....3....+....4....+
SUPPLIER_NUMBER ITEM
ITEM
NUMBER NAME
1234
153047 Pencils, red
1234
229740 Lined tablets
1234
303476 Paper clips
2424
153047 Pencils, red
2424
303476 Paper clips
3366
073956 Pens, black
3366
303476 Paper clips
5546
775298 Chairs, secretary
9988
153047 Pencils, red
9988
559343 Envelopes, legal
******** End of data ********
F3=Exit
F12=Cancel
F19=Left
F20=Right
45
F21=Split
INVENTORY_LIST______
SAMPLECOLL__
Correlation . . . . .
____________________
Name
F3=Exit
F4=Prompt
F5=Refresh
F21=Display statement
F12=Cancel
After typing the table name and collection name, press Enter. The display will be
shown again with the list of columns in the table.
25
INVENTORY_LIST______
SAMPLECOLL__
Correlation . . . . .
____________________
Name
Value
_____________________________________________________
_____________________________________________________
_____________________________________________________
_____________________________________________________
CURRENT DATE_________________________________________
50___________________________________________________
F3=Exit
F4=Prompt
F11=Display type
F5=Refresh
F12=Cancel
F6=Insert line
F14=Delete line
F10=Copy line
F24=More keys
Bottom
Specifying CURRENT DATE for a value will change the date in all the selected
rows to be todays date.
After typing the values to be updated for the table, press Enter to see the display
on which the WHERE condition can be specified. If a WHERE condition is not
specified, all the rows in the table will be updated using the values from the
previous display.
Specify UPDATE Statement
Type WHERE conditions, press Enter. Press F4 for a list.
ITEM_NUMBER = '303476'________________________________________________
______________________________________________________________________
Bottom
F3=Exit
F10=Copy line
F4=Prompt
F5=Refresh
F6=Insert line
F9=Specify subquery
F12=Cancel
F14=Delete line
F15=Split line
F24=More keys
After typing the condition, press Enter to perform the update on the table. A
message will indicate that the function is complete.
This statement could have been typed on the Enter SQL Statements display as:
UPDATE SAMPLECOLL.INVENTORY_LIST
SET LAST_ORDER_DATE = CURRENT DATE,
ORDER_QUANTITY = 50
WHERE ITEM_NUMBER = '303476'
26
Running a SELECT statement to get all the rows from the table (SELECT * FROM
SAMPLECOLL.INVENTORY_LIST), returns the following result:
Display Data
Data width . . . . . . :
71
Position to line . . . . .
Shift to column . . . . . .
....+....1....+....2....+....3....+....4....+....5....+....6....+....7.
ITEM
ITEM
UNIT
QUANTITY LAST
NUMBER
NUMBER NAME
COST
ON
ORDER
ORDERED
HAND
DATE
153047 Pencils, red
10.00
25
20
229740 Lined tablets
1.50
120
20
544931 ***UNKNOWN***
5.00
- 20
303476 Paper clips
2.00
100
05/30/94
50
559343 Envelopes, legal
3.00
500
20
291124 Envelopes, standard
.00
- 20
775298 Chairs, secretary
225.00
6
20
073956 Pens, black
20.00
25
20
******** End of data ********
Bottom
F3=Exit
F12=Cancel
F19=Left
F20=Right
F21=Split
Only the entry for Paper clips was changed. The LAST_ORDER_DATE was changed
to be the current date. This date is always the date the update is run. The
NUMBER_ORDERED shows its updated value.
To check a column for the null value, the IS NULL comparison is used. Running
another SELECT statement after the delete has completed will return the following
result table:
Display Data
Data width . . . . . . :
Position to line . . . . .
Shift to column . . . . . .
....+....1....+....2....+....3....+....4....+....5....+....6....+....7.
ITEM
ITEM
UNIT
QUANTITY LAST
NUMBER
NUMBER NAME
COST
ON
ORDER
ORDERED
HAND
DATE
153047 Pencils, red
10.00
25
20
229740 Lined tablets
1.50
120
20
303476 Paper clips
2.00
100
05/30/94
50
559343 Envelopes, legal
3.00
500
20
775298 Chairs, secretary
225.00
6
20
073956 Pens, black
20.00
25
20
******** End of data ********
F3=Exit
F12=Cancel
F19=Left
F20=Right
F21=Split
71
Bottom
27
|
|
|
|
|
|
|
|
|
|
|
In the example above, the columns in the view have the same name as the
columns in the table because no column list follows the view name. The collection
that the view is created into does not need to be the same collection as the table it
is built over. Any collection or library could be used. The following display is the
result of running the SQL statement:
SELECT * FROM SAMPLECOLL.RECENT_ORDERS
28
Display Data
Data width . . . . . . :
Shift to column . . . . . .
Position to line . . . . .
....+....1....+....2....+.
ITEM
LAST
QUANTITY
NUMBER ORDER
ON
DATE
HAND
303476 05/30/94
100
******** End of data ********
F3=Exit
F12=Cancel
F19=Left
F20=Right
F21=Split
26
Bottom
The only row selected by the view is the row that we updated to have the current
date. All other dates in our table still have the null value so they are not returned.
Data width . . . . . . :
Position to line . . . . .
Shift to column . . . . . .
....+....1....+....2....+....3....+....4....+....5.
SUPPLIER_NUMBER ITEM
UNIT
SUPPLIER_COST
NUMBER
COST
9988
153047
10.00
8.00
2424
153047
10.00
9.00
1234
229740
1.50
1.00
3366
303476
2.00
1.50
3366
073956
20.00
17.00
******** End of data ********
F3=Exit
F12=Cancel
F19=Left
F20=Right
F21=Split
51
Bottom
The rows that can be seen through this view are only those rows that have a
supplier cost that is less than the unit cost.
29
30
WHERE ADMRDEPT='A00'
31
Note: Because views are built on tables and actually contain no data, working with
views can be confusing. See Creating and Using Views on page 93 for
more information on inserting data by using a view.
|
|
|
For every row you insert, you must supply a value for each column defined with
the NOT NULL attribute if that column does not have a default value. The INSERT
statement for adding a row to a table or view may look like this:
INSERT INTO table-name
(column1, column2, ... )
VALUES (value-for-column1, value-for-column2, ... )
The INTO clause names the columns for which you specify values. The VALUES
clause specifies a value for each column named in the INTO clause.
You must provide a value in the VALUES clause for each column named in an
INSERT statements column list. The column name list can be omitted if all
columns in the table have a value provided in the VALUES clause. If a column has
a default value, the keyword DEFAULT may be used as a value on the VALUES
clause.
It is a good idea to name all columns into which you are inserting values because:
v Your INSERT statement is more descriptive.
v You can verify that you are giving the values in the proper order based on the
column names.
v You have better data independence. The order in which the columns are defined
in the table does not affect your INSERT statement.
If the column is defined to allow null values or to have a default, you do not need
to name it in the column name list or specify a value for it. The default value is
used. If the column is defined to have a default value, the default value is placed
in the column. If DEFAULT was specified for the column definition without an
explicit default value, SQL places the default value for that data type in the
column. If the column does not have a default value defined for it, but is defined
to allow the null value (NOT NULL was not specified in the column definition),
SQL places the null value in the column.
v For numeric columns, the default value is 0.
v For fixed length character or graphic columns, the default is blanks.
v For varying length character or graphic columns, the default is a zero length
string.
v For date, time, and timestamp columns, the default value is the current date,
time, or timestamp. When inserting a block of records, the default date/time
value is extracted from the system when the block is written. This means that
the column will be assigned the same default value for each row in the block.
When your program attempts to insert a row that duplicates another row already
in the table, an error might occur. Multiple null values may or may not be
considered duplicate values, depending on the option used when the index was
created.
v If the table has a primary key, unique key, or unique index, the row is not
inserted. Instead, SQL returns an SQLCODE of 803.
v If the table does not have a primary key, unique key, or unique index, the row
can be inserted without error.
32
If SQL finds an error while running the INSERT statement, it stops inserting data.
If you specify COMMIT(*ALL), COMMIT(*CS), COMMIT(*CHG), or
COMMIT(*RR), no rows are inserted. Rows already inserted by this statement, in
the case of INSERT with a select-statement or blocked insert, are deleted. If you
specify COMMIT(*NONE), any rows already inserted are not deleted.
A table created by SQL is created with the Reuse Deleted Records parameter of
*YES. This allows the database manager to reuse any rows in the table that were
marked as deleted. The CHGPF command can be used to change the attribute to
*NO. This causes INSERT to always add rows to the end of the table.
The order in which rows are inserted does not guarantee the order in which they
will be retrieved.
If the row is inserted without error, the SQLERRD(3) field of the SQLCA has a
value of 1.
Note: For blocked INSERT or for INSERT with select-statement, more than one
row can be inserted. The number of rows inserted is reflected in
SQLERRD(3).
For example, suppose an employee was relocated. To update several items of the
employees data in the CORPDATA.EMPLOYEE table to reflect the move, you can
specify:
UPDATE CORPDATA.EMPLOYEE
SET JOB = :PGM-CODE,
PHONENO = :PGM-PHONE
WHERE EMPNO = :PGM-SERIAL
Use the SET clause to specify a new value for each column you want to update.
The SET clause names the columns you want updated and provides the values you
want them changed to. The value you specify can be:
A column name. Replace the columns current value with the contents of
another column in the same row.
A constant. Replace the columns current value with the value provided in the
SET clause.
A null value. Replace the columns current value with the null value, using the
keyword NULL. The column must be defined as capable of containing a null
value when the table was created, or an error occurs.
A host variable. Replace the columns current value with the contents of a host
variable.
33
A special register. Replace the columns current value with a special register
value; for example, USER.
An expression. Replace the columns current value with the value that results
from an expression. The expression can contain any of the values in this list.
A scalar subselect. Replace the columns current value with the value that the
subquery returns.
The DEFAULT keyword. Replace the columns current value with the default
value of the column. The column must have a default value defined for it or
allow the NULL value, or an error occurs.
The following is an example of a statement that uses many different values:
UPDATE WORKTABLE
SET COL1 = 'ASC',
COL2 = NULL,
COL3 = :FIELD3,
COL4 = CURRENT TIME,
COL5 = AMT - 6.00,
COL6 = COL7
WHERE EMPNO = :PGM-SERIAL
For example, suppose department D11 was moved to another place. You want to
delete each row in the CORPDATA.EMPLOYEE table with a WORKDEPT value of
D11 as follows:
34
The WHERE clause tells SQL which rows you want to delete from the table. SQL
deletes all the rows that satisfy the search condition from the base table. You can
omit the WHERE clause, but it is best to include one, because a DELETE statement
without a WHERE clause deletes all the rows from the table or view. To delete a
table definition as well as the table contents, issue the DROP statement (described
in the DB2 for AS/400 SQL Reference book).
If SQL finds an error while running your DELETE statement, it stops deleting data
and returns a negative SQLCODE. If you specify COMMIT(*ALL), COMMIT(*CS),
COMMIT(*CHG), or COMMIT(*RR), no rows in the table are deleted (rows already
deleted by this statement, if any, are restored to their previous values). If
COMMIT(*NONE) is specified, any rows already deleted are not restored to their
previous values.
If SQL cannot find any rows that satisfy the search condition, an SQLCODE of
+100 is returned.
Note: DELETE with WHERE clause may have deleted more than one row. The
number of rows deleted is reflected in SQLERRD(3).
The SELECT, INTO, and FROM clauses must be specified. The other clauses are
optional.
The INTO clause names the host variables (variables in your program used to
contain retrieved column values). The value of the first column specified in the
SELECT clause is put into the first host variable named in the INTO clause; the
second value is put into the second host variable, and so on.
Chapter 3. Basic Concepts and Techniques
35
The result table for a SELECT INTO should contain just one row. For example,
each row in the CORPDATA.EMPLOYEE table has a unique EMPNO (employee
number) column. The result of a SELECT INTO statement for this table if the
WHERE clause contains an equal comparison on the EMPNO column, would be
exactly one row (or no rows). Finding more than one row is an error, but one row
is still returned. You can control which row will be returned in this error condition
by specifying the ORDER BY clause. If you use the ORDER BY clause, the first row
in the result table is returned.
If you want more than one row to be the result of a select-statement, use a
DECLARE CURSOR statement to select the rows, followed by a FETCH statement
to move the column values into host variables one or many rows at a time. Using
cursors is described in Chapter 4. Using a Cursor on page 55.
The FROM clause names the table (or view) that contains the data you are
interested in.
For example, assume that each department listed in the
CORPDATA.DEPARTMENT table has a unique department number. You want to
retrieve the department name and manager number from the
CORPDATA.DEPARTMENT table for department C01. To do this, your program
can set PGM-DEPT to the value C01 and issue:
SELECT DEPTNAME, MGRNO
INTO :PGM-DEPTNAME, :PGM-MGRNO
FROM CORPDATA.DEPARTMENT
WHERE DEPTNO = :PGM-DEPT
PGMMGRNO
INFORMATION CENTER
000030
36
If SQL finds a data mapping error while running a statement, one of two things
occurs:
v If the error occurs on an expression in the SELECT list and an indicator variable
is provided for the expression in error:
SQL returns a 2 for the indicator variable corresponding to the expression in
error.
SQL returns all valid data for that row.
SQL returns a positive SQLCODE.
v If an indicator variable is not provided, SQL returns the corresponding negative
SQLCODE in the SQLCA.
Data mapping errors include:
v +138 - Argument of the substringing function is not valid.
v +180 - Syntax for a string representation of a date, time, or timestamp is not
valid.
v +181 - String representation of a date, time, or timestamp is not a valid value.
v +183 - Invalid result from a date/time expression. The resulting date or
timestamp is not within the valid range of dates or timestamps.
v +191 - MIXED data is not properly formed.
v +304 - Numeric conversion error (for example, overflow, underflow, or division
by zero).
v +331 - Characters cannot be converted.
v +420 - Character in the CAST argument is not valid.
v +802 - Data conversion or data mapping error.
For data mapping errors, the SQLCA reports only the last error detected. The
indicator variable corresponding to each result column having an error is set to 2.
If the full-select contains DISTINCT in the select list and a column in the select list
contains numeric data that is not valid, the data is considered equal to a null value
if the query is completed as a sort. If an existing index is used, the data is not
considered equal to a null.
The impact of data mapping errors on the ORDER BY clause depends on the
situation:
v If the data mapping error occurs while data is being assigned to a host variable
in a SELECT INTO or FETCH statement, and that same expression is used in the
ORDER BY clause, the result record is ordered based on the value of the
expression. It is not ordered as if it were a null (higher than all other values).
This is because the expression was evaluated before the assignment to the host
variable is attempted.
v If the data mapping error occurs while an expression in the select-list is being
evaluated and the same expression is used in the ORDER BY clause, the result
column is normally ordered as if it were a null value (higher than all other
values). If the ORDER BY clause is implemented by using a sort, the result
column is ordered as if it were a null value. If the ORDER BY clause is
implemented by using an existing index, in the following cases, the result
column is ordered based on the actual value of the expression in the index:
The expression is a date column with a date format of *MDY, *DMY, *YMD,
or *JUL, and a date conversion error occurs because the date is not within the
valid range for dates.
37
You can specify that only one column be retrieved, or as many as 8000 columns.
The value of each column you name is retrieved in the order specified in the
SELECT clause.
If you want to retrieve all columns (in the same order as they appear in the row),
use an asterisk (*) instead of naming the columns:
SELECT *
.
.
.
When using the select-statement in an application program, list the column names
to give your program more data independence. There are two reasons for this:
1. When you look at the source code statement, you can easily see the one-to-one
correspondence between the column names in the SELECT clause and the host
variables named in the INTO clause.
2. If a column is added to a table or view you access and you use SELECT * ...,
and you create the program again from source, the INTO clause does not have
a matching host variable named for the new column. The extra column causes
you to get a warning (not an error) in the SQLCA (SQLWARN4 will contain a
W).
In this case, the search condition consists of one predicate: WORKDEPT = 'C01'.
38
If the search condition contains character or UCS-2 graphic column predicates, the
sort sequence that is in effect when the query is run is applied to those predicates.
See Using Sort Sequence in SQL on page 49 for more information on sort
sequence and selection.
39
Comparison Operators
SQL supports the following comparison operators:
=
<> or =
<
>
<= or >
> = or <
Equal to
Not equal to
Less than
Greater than
Less than or equal to (or not greater than)
Greater than or equal to (or not less than)
40
GROUP BY clause to group the rows. The items you specify in the SELECT
statement are properties of each group of rows, not properties of individual rows
in a table or view.
For example, the CORPDATA.EMPLOYEE table has several sets of rows, and each
set consists of rows describing members of a specific department. To find the
average salary of people in each department, you could issue:
Results in:
fetch WORK-DEPT AVG-SALARY
1
A00
42833
B01
41250
...
...
...
RV2W551-1
Results in:
fetch SUM-PR
MAJ-PROJ
AD3100
AD3110
10
MA2100
...
...
...
RV2W552-3
41
The result is a list of the companys current major projects and the number of
people working on each project.
You can also specify that you want the rows grouped by more than one column.
For example, you could issue a select-statement to find the average salary for men
and women in each department, using the CORPDATA.EMPLOYEE table. To do
this, you could issue:
Results in:
fetch DEPT
SEX
AVG-WAGES
A00
52750
A00
37875
B01
41250
C01
30156
...
...
...
...
RV2W553-1
Because you did not include a WHERE clause in this example, SQL examines and
process all rows in the CORPDATA.EMPLOYEE table. The rows are grouped first
by department number and next (within each department) by sex before SQL
derives the average SALARY value for each group.
42
Results in:
fetch DEPT
AVG-WAGES
MIN-EDUC
A00
52750
18
C01
30156
16
D11
24476
17
RV2W554-3
You can use multiple predicates in a HAVING clause by connecting them with
AND and OR, and you can use NOT for any predicate of a search condition.
Note: If you intend to update a column or delete a row, you cannot include a
GROUP BY or HAVING clause in the SELECT statement within a DECLARE
CURSOR statement. (The DECLARE CURSOR statement is described in
Chapter 4. Using a Cursor on page 55.)
Predicates with arguments that are not column functions can be coded in either
WHERE or HAVING clauses. It is usually more efficient to code the selection
criteria in the WHERE clause. It is processed during the initial phase of the query
processing. The HAVING selection is performed in post processing of the result
table.
If the search condition contains predicates involving character or UCS-2 graphic
columns, the sort sequence in effect when the query is run is applied to those
predicates. See Using Sort Sequence in SQL on page 49 for more information on
sort sequence and selection.
43
Results in:
fetch PGM-NAME3
DEPT
HAAS
A00
KWAN
C01
QUINTANA
C01
NICHOLLS
C01
PIANKA
D11
SCOUTTEN
D11
LUTZ
D11
PULASKI
D21
JOHNSON
D21
10
PEREZ
D21
11
HENDERSON
E11
12
SCHNEIDER
E11
13
SETRIGHT
E11
RV2W555-3
Notes:
1. All columns named in the ORDER BY clause must also be named in the
SELECT list.
2. Null values are ordered as the highest value.
To order by an expression, a column function, or something other than a column
name, you can specify an AS clause in the select-list. The AS clause names the
result column. This name can be specified in the ORDER BY clause. To order by a
name specified in the AS clause:
v The name must be unique in the select-list.
v The name must not be qualified.
For example, to retrieve the full name of employees listed in alphabetic order, you
could use this select-statement:
SELECT LASTNAME CONCAT FIRSTNAME AS FULLNAME ...
ORDER BY FULLNAME
Instead of naming the columns to order the results, you can use a number. For
example, ORDER BY 3 specifies that you want the results ordered by the third
column of the results table, as specified by the select-statement. Use a number to
order the rows of the results table when the sequencing value is not a named
column.
You can also specify whether you want SQL to collate the rows in ascending (ASC)
or descending (DESC) sequence. An ascending collating sequence is the default. In
the above select-statement, SQL first returns the row with the lowest department
number (alphabetically and numerically), followed by rows with higher
department numbers. To order the rows in descending collating sequence based on
the department number, specify:
... ORDER BY WORKDEPT DESC
As with GROUP BY, you can specify a secondary ordering sequence (or several
levels of ordering sequences) as well as a primary one. In the example above, you
44
might want the rows ordered first by department number, and within each
department, ordered by employee name. To do this, specify:
... ORDER BY WORKDEPT, LASTNAME
If character columns or UCS-2 graphic columns are used in the ORDER BY clause,
ordering for these columns is based on the sort sequence in effect when the query
is run. See Using Sort Sequence in SQL on page 49 for more information on sort
sequence and its affect on ordering.
ADMRDEPT
D01
A00
DEVELOPMENT
CENTER
To get the rows that do not have a null value for the manager number, you could
change the WHERE clause like this:
WHERE MGRNO IS NOT NULL
For more information on the use of null values, see the DB2 for AS/400 SQL
Reference book.
Contents
CURRENT DATE
CURRENT_DATE
CURRENT TIME
CURRENT_TIME
CURRENT TIMESTAMP
CURRENT_TIMESTAMP
45
Special Registers
Contents
CURRENT TIMEZONE
CURRENT_TIMEZONE
CURRENT SERVER
CURRENT_SERVER
USER
If a single statement contains more than one reference to any of CURRENT DATE,
CURRENT TIME, or CURRENT TIMESTAMP special registers, or the CURDATE,
CURTIME, or NOW scalar functions, all values are based on a single clock reading.
For remotely run SQL statements, the special registers and their contents are shown
in the following table:
Special Registers
Contents
CURRENT DATE
CURRENT_DATE
CURRENT TIME
CURRENT_TIME
CURRENT TIMESTAMP
CURRENT_TIMESTAMP
CURRENT TIMEZONE
CURRENT_TIMEZONE
CURRENT SERVER
CURRENT_SERVER
USER
When a query over a distributed table references a special register, the contents of
the special register on the system that requests the query are used. For more
information on distributed tables, see DB2 Multisystem for AS/400 book.
46
Date/Time Arithmetic
|
|
|
Addition and subtraction are the only arithmetic operators applicable to date, time,
and timestamp values. You can increment and decrement a date, time, or
timestamp by a duration; or subtract a date from a date, a time from a time, or a
timestamp from a timestamp. For a detailed description of date and time
arithmetic, see Chapter 2 of the DB2 for AS/400 SQL Reference book.
|
|
|
|
|
|
Sometimes it is useful to have a second name for an existing table or view. To refer
to an AS/400 physical file that consists of multiple members without using an alias
name requires the use of file overrides. This override can be avoided by creating a
table alias that defines a name for the file, including the specific member name.
This alias name can then be used in an SQL statement as though it were a table
name. Unlike overrides, alias names are objects that exist until they are dropped.
|
|
|
|
|
47
|
|
|
Alias names can also be specified on DDL statements. Assume that alias
MYLIB.MYALIAS exists and is an alias for table MYLIB.MYTABLE. The following
DROP statement will drop table MYLIB.MYTABLE.
|
|
If you really want to drop the alias name instead, specify the ALIAS keyword on
the drop statement:
Using LABEL ON
Sometimes the table name, column name, view name, alias name, or SQL package
name does not clearly define data that is shown on an interactive display of the
table. By using the LABEL ON statement, you can create a more descriptive label
for the table name, column name, view name, alias name, or SQL package name.
These labels can be seen in the SQL catalog in the LABEL column.
|
|
|
|
After these statements are run, the table named DEPARTMENT displays the text
description as Department Structure Table and the column named ADMRDEPT
displays the heading Reports to Dept. The label for tables, views, SQL packages, and
column text cannot be more than 50 characters and the label for column headings
cannot be more than 60 characters (blanks included). The following are examples
of LABEL ON statements:
This LABEL ON statement provides column heading 1 and column heading 2.
*...+....1....+....2....+....3....+....4....+....5....+....6..*
LABEL ON COLUMN CORPDATA.EMPLOYEE.EMPNO IS
'Employee
Number'
This LABEL ON statement provides 3 levels of column headings for the SALARY
column.
*...+....1....+....2....+....3....+....4....+....5....+....6..*
LABEL ON COLUMN CORPDATA.EMPLOYEE.SALARY IS
'Yearly
Salary
(in dollars)'
This LABEL ON statement provides column text for the EDLEVEL column.
48
*...+....1....+....2....+....3....+....4....+....5....+....6..*
LABEL ON COLUMN CORPDATA.EMPLOYEE.EDLEVEL TEXT IS
'Number of years of formal education'
For more information about the LABEL ON statement, see the DB2 for AS/400 SQL
Reference book.
Using COMMENT ON
After you create an SQL object such as a table, view, index, package, procedure, or
parameter, you can supply information about it for future referral, such as the
purpose of the object, who uses it, and anything unusual or special about it. You
can also include similar information about each column of a table or view. Your
comment must not be more than 2000 bytes.
A comment is especially useful if your names do not clearly indicate the contents
of the columns or objects. In that case, use a comment to describe the specific
contents of the column or objects.
An example of using COMMENT ON follows:
COMMENT ON TABLE CORPDATA.EMPLOYEE IS
'Employee table. Each row in this table represents
one employee of the company.'
Getting Comments
After running a COMMENT ON statement, your comments are stored in the
REMARKS column of SYSTABLES or SYSCOLUMNS. (If the indicated row had
already contained a comment, the old comment is replaced by the new one.) The
following example gets the comments added by the COMMENT ON statement in
the previous example:
SELECT REMARKS
FROM CORPDATA.SYSTABLES
WHERE NAME = 'EMPLOYEE'
49
NAME
DEPT
JOB
YEARS
SALARY
COMM
10
Sanders
20
Mgr
18357.50
20
Pernal
20
Sales
18171.25
612.45
30
Merenghi
38
MGR
17506.75
40
OBrien
38
Sales
18006.00
846.55
50
Hanes
15
Mgr
10
20659.80
60
Quigley
38
SALES
16808.30
650.25
70
Rothman
15
Sales
16502.83
1152.00
80
James
20
Clerk
13504.60
128.20
90
Koonitz
42
sales
18001.75
1386.70
100
Plotz
42
mgr
18352.80
In the following examples, the results are shown for each statement using:
v *HEX sort sequence
v Shared-weight sort sequence using the language identifier ENU
v Unique-weight sort sequence using the language identifier ENU
Note: ENU is chosen as a language identifier by specifying either
SRTSEQ(*LANGIDUNQ), or SRTSEQ(*LANGIDSHR) and LANGID(ENU),
on the CRTSQLxxx, STRSQL, or RUNSQLSTM commands, or by using the
SET OPTION statement.
ORDER BY
The following SQL statement causes the result table to be sorted using the values
in the JOB column:
SELECT * FROM STAFF ORDER BY JOB
Table 3 shows the result table using a *HEX sort sequence. The rows are sorted
based on the EBCDIC value in the JOB column. In this case, all lowercase letters
sort before the uppercase letters.
Table 3. SELECT * FROM STAFF ORDER BY JOB Using the *HEX Sort Sequence.
50
ID
NAME
DEPT
JOB
YEARS
SALARY
COMM
100
Plotz
42
mgr
18352.80
90
Koonitz
42
sales
18001.75
1386.70
80
James
20
Clerk
13504.60
128.20
10
Sanders
20
Mgr
18357.50
50
Hanes
15
Mgr
10
20659.80
30
Merenghi
38
MGR
17506.75
20
Pernal
20
Sales
18171.25
612.45
40
OBrien
38
Sales
18006.00
846.55
70
Rothman
15
Sales
16502.83
1152.00
60
Quigley
38
SALES
16808.30
650.25
Table 4 shows how sorting is done for a unique-weight sort sequence. After the sort
sequence is applied to the values in the JOB column, the rows are sorted. Notice
that after the sort, lowercase letters are before the same uppercase letters, and the
values 'mgr', 'Mgr', and 'MGR' are adjacent to each other.
Table 4. SELECT * FROM STAFF ORDER BY JOB Using the Unique-Weight Sort
Sequence for the ENU Language Identifier.
ID
NAME
DEPT
JOB
YEARS
SALARY
COMM
80
James
20
Clerk
13504.60
128.20
100
Plotz
42
mgr
18352.80
10
Sanders
20
Mgr
18357.50
50
Hanes
15
Mgr
10
20659.80
30
Merenghi
38
MGR
17506.75
90
Koonitz
42
sales
18001.75
1386.70
20
Pernal
20
Sales
18171.25
612.45
40
OBrien
38
Sales
18006.00
846.55
70
Rothman
15
Sales
16502.83
1152.00
60
Quigley
38
SALES
16808.30
650.25
Table 5 shows how sorting is done for a shared-weight sort sequence. After the sort
sequence is applied to the values in the JOB column, the rows are sorted. For the
sort comparison, each lowercase letter is treated the same as the corresponding
uppercase letter. In Table 5, notice that all the values 'MGR', 'mgr' and 'Mgr' are
mixed together.
Table 5. SELECT * FROM STAFF ORDER BY JOB Using the Shared-Weight Sort
Sequence for the ENU Language Identifier.
ID
NAME
DEPT
JOB
YEARS
SALARY
COMM
80
James
20
Clerk
13504.60
128.20
10
Sanders
20
Mgr
18357.50
30
Merenghi
38
MGR
17506.75
50
Hanes
15
Mgr
10
20659.80
100
Plotz
42
mgr
18352.80
20
Pernal
20
Sales
18171.25
612.45
40
OBrien
38
Sales
18006.00
846.55
60
Quigley
38
SALES
16808.30
650.25
70
Rothman
15
Sales
16502.83
1152.00
90
Koonitz
42
sales
18001.75
1386.70
Record selection
The following SQL statement selects records with the value 'MGR' in the JOB
column:
SELECT * FROM STAFF WHERE JOB='MGR'
Table 6 on page 52 shows how record selection is done with a *HEX sort sequence.
In Table 6 on page 52, the rows that match the record selection criteria for the
Chapter 3. Basic Concepts and Techniques
51
column 'JOB' are selected exactly as specified in the select statement. Only the
uppercase 'MGR' is selected.
Table 6. SELECT * FROM STAFF WHERE JOB=MGR Using the *HEX Sort Sequence.
ID
NAME
DEPT
JOB
YEARS
SALARY
COMM
30
Merenghi
38
MGR
17506.75
Table 7 shows how record selection is done with a unique-weight sort sequence. In
Table 7, the lowercase and uppercase letters are treated as unique. The lowercase
'mgr' is not treated the same as uppercase 'MGR'. Therefore, the lower case 'mgr' is
not selected.
Table 7. SELECT * FROM STAFF WHERE JOB = MGR Using Unique-Weight Sort
Sequence for the ENU Language Identifier.
ID
NAME
DEPT
JOB
YEARS
SALARY
COMM
30
Merenghi
38
MGR
17506.75
Table 8 shows how record selection is done with a shared-weight sort sequence. In
Table 8, the rows that match the record selection criteria for the column 'JOB' are
selected by treating uppercase letters the same as lowercase letters. Notice that in
Table 8 all the values 'mgr', 'Mgr' and 'MGR' are selected.
Table 8. SELECT * FROM STAFF WHERE JOB = MGR Using the Shared-Weight Sort
Sequence for the ENU Language Identifier.
ID
NAME
DEPT
JOB
YEARS
SALARY
COMM
10
Sanders
20
Mgr
18357.50
30
Merenghi
38
MGR
17506.75
50
Hanes
15
Mgr
10
20659.80
100
Plotz
42
mgr
18352.80
52
NAME
DEPT
JOB
YEARS
SALARY
COMM
10
Sanders
20
Mgr
18357.50
30
Merenghi
38
MGR
17506.75
50
Hanes
15
Mgr
10
20659.80
Any queries run against view V1 are run against the result table shown in Table 9.
The query shown below is run with a sort sequence of SRTSEQ(*LANGIDUNQ)
and LANGID(ENU).
Table 10. SELECT * FROM V1 WHERE JOB = MGR Using the Unique-Weight Sort
Sequence for Language Identifier ENU
ID
NAME
DEPT
JOB
YEARS
SALARY
COMM
30
Merenghi
38
MGR
17506.75
53
54
Types of cursors
SQL supports serial and scrollable cursors. The type of cursor determines the
positioning methods which can be used with the cursor.
Serial cursor
A serial cursor is one defined without the SCROLL keyword.
For a serial cursor, each row of the result table can be fetched only once per OPEN
of the cursor. When the cursor is opened, it is positioned before the first row in the
result table. When a FETCH is issued, the cursor is moved to the next row in the
result table. That row is then the current row. If host variables are specified (with
the INTO clause on the FETCH statement), SQL moves the current rows contents
into your programs host variables.
This sequence is repeated each time a FETCH statement is issued until the
end-of-data (SQLCODE = 100) is reached. When you reach the end-of-data, close
the cursor. You cannot access any rows in the result table after you reach the
end-of-data. To use the cursor again, you must first close the cursor and then
re-issue the OPEN statement. You can never back up.
Scrollable cursor
For a scrollable cursor, the rows of the result table can be fetched many times. The
cursor is moved through the result table based on the position option specified on
the FETCH statement. When the cursor is opened, it is positioned before the first
row in the result table. When a FETCH is issued, the cursor is positioned to the
row in the result table that is specified by the position option. That row is then the
current row. If host variables are specified (with the INTO clause on the FETCH
Copyright IBM Corp. 1997, 1998
55
statement), SQL moves the current rows contents into your programs host
variables. Host variables cannot be specified for the BEFORE and AFTER position
options.
This sequence is repeated each time a FETCH statement is issued. The cursor does
not need to be closed when an end-of-data or beginning-of-data condition occurs.
The position options enable the program to continue fetching rows from the table.
The following scroll options are used to position the cursor when issuing a FETCH
statement. These positions are relative to the current cursor location in the result
table.
NEXT
PRIOR
FIRST
LAST
BEFORE
AFTER
CURRENT
RELATIVE n
56
Described in Section
EXEC SQL
DECLARE THISEMP CURSOR FOR
SELECT EMPNO, LASTNAME,
WORKDEPT, JOB
FROM CORPDATA.EMPLOYEE
FOR UPDATE OF JOB
END-EXEC.
EXEC SQL
OPEN THISEMP
END-EXEC.
EXEC SQL
WHENEVER NOT FOUND
GO TO CLOSE-THISEMP
END-EXEC.
Described in Section
EXEC SQL
FETCH THISEMP
INTO :EMP-NUM, :NAME2,
:DEPT, :JOB-CODE
END-EXEC.
EXEC SQL
UPDATE CORPDATA.EMPLOYEE
SET JOB = :NEW-CODE
WHERE CURRENT OF THISEMP
END-EXEC.
... then print the row.
... for other employees,
delete the row:
EXEC SQL
DELETE FROM CORPDATA.EMPLOYEE
WHERE CURRENT OF THISEMP
END-EXEC.
Branch back to fetch and process the next
row.
CLOSE-THISEMP.
EXEC SQL
CLOSE THISEMP
END-EXEC.
For the scrollable cursor example, the program uses the RELATIVE position option
to obtain a representative sample of salaries from department D11.
Table 12. Scrollable Cursor Example
Scrollable Cursor SQL Statement
Described in Section
EXEC SQL
Step 1: Define the Cursor on page 58.
DECLARE THISEMP DYNAMIC SCROLL CURSOR FOR
SELECT EMPNO, LASTNAME,
SALARY
FROM CORPDATA.EMPLOYEE
WHERE WORKDEPT = D11
END-EXEC.
EXEC SQL
OPEN THISEMP
END-EXEC.
EXEC SQL
WHENEVER NOT FOUND
GO TO CLOSE-THISEMP
END-EXEC.
57
Described in Section
For a scrollable cursor, the statement looks like this (the WHERE clause is
optional):
EXEC SQL
DECLARE cursor-name DYNAMIC SCROLL CURSOR FOR
SELECT column-1, column-2 ,...
FROM table-name ,...
WHERE column-1 = expression ...
END-EXEC.
The select-statements shown here are rather simple. However, you can code several
other types of clauses in a select-statement within a DECLARE CURSOR statement
for a serial and a scrollable cursor.
If you intend to update any columns in any or all of the rows of the identified
table (the table named in the FROM clause), include the FOR UPDATE OF clause.
It names each column you intend to update. If you do not specify the names of
columns, and you specify either the ORDER BY clause or FOR READ ONLY
clause, a negative SQLCODE is returned if an update is attempted. If you do not
58
specify the FOR UPDATE OF clause, the FOR READ ONLY clause, or the ORDER
BY clause, and the result table is not read-only, you can update any of the columns
of the specified table.
You can update a column of the identified table even though it is not part of the
result table. In this case, you do not need to name the column in the SELECT
statement. When the cursor retrieves a row (using FETCH) that contains a column
value you want to update, you can use UPDATE ... WHERE CURRENT OF to
update the row.
For example, assume that each row of the result table includes the EMPNO,
LASTNAME, and WORKDEPT columns from the CORPDATA.EMPLOYEE table. If
you want to update the JOB column (one of the columns in each row of the
CORPDATA.EMPLOYEE table), the DECLARE CURSOR statement should include
FOR UPDATE OF JOB ... even though JOB is omitted from the SELECT statement.
The result table and cursor are read-only if any of the following are true:
v The first FROM clause identifies more than one table or view.
v The first FROM clause identifies a read-only view.
v The first SELECT clause specifies the keyword DISTINCT.
v The outer subselect contains a GROUP BY clause.
v The outer subselect contains a HAVING clause.
v The first SELECT clause contains a column function.
v The select-statement contains a subquery such that the base object of the outer
subselect and of the subquery is the same table.
v The select-statement contains a UNION or UNION ALL operator.
v The select-statement contains an ORDER BY clause, and the FOR UPDATE OF
clause and DYNAMIC SCROLL are not specified.
v The select-statement includes a FOR READ ONLY clause.
v The SCROLL keyword is specified without DYNAMIC.
3. A result table can contain zero, one, or many rows, depending on the extent to which the search condition is satisfied.
Chapter 4. Using a Cursor
59
...
IF SQLCODE =100 GO TO DATA-NOT-FOUND.
or
IF SQLSTATE ='02000' GO TO DATA-NOT-FOUND.
60
EXEC SQL
FETCH RELATIVE integer
FROM cursor-name
INTO :host variable-1[, :host variable-2] ...
END-EXEC.
61
If you processed the rows of a result table and you do not want to use the cursor
again, you can let the system close the cursor. The system automatically closes the
cursor when:
v A COMMIT without HOLD statement is issued and the cursor is not declared
using the WITH HOLD clause.
v A ROLLBACK without HOLD statement is issued.
v The job ends.
v The activation group ends and CLOSQLCSR(*ENDACTGRP) was specified on
the precompile.
v The first SQL program in the call stack ends and neither CLOSQLCSR(*ENDJOB)
or CLOSQLCSR(*ENDACTGRP) was specified when the program was
precompiled.
v The connection to the application server is ended using the DISCONNECT
statement.
v The connection to the application server was released and a successful COMMIT
occurred.
v An *RUW CONNECT occurred.
Because an open cursor still holds locks on referred-to-tables or views, you
should explicitly close any open cursors as soon as they are no longer needed.
62
EXEC SQL
DECLARE D11 CURSOR FOR
SELECT EMPNO, LASTNAME, WORKDEPT, JOB
FROM CORPDATA.EMPLOYEE
WHERE WORKDEPT = "D11"
END-EXEC.
...
EXEC SQL
OPEN D11
Chapter 4. Using a Cursor
63
END-EXEC.
PERFORM FETCH-PARA UNTIL SQLCODE NOT EQUAL TO ZERO.
ALL-DONE.
EXEC SQL CLOSE D11 END-EXEC.
...
FETCH-PARA.
EXEC SQL WHENEVER NOT FOUND GO TO ALL-DONE END-EXEC.
EXEC SQL FETCH D11 FOR 10 ROWS INTO :DEPT :IND-ARRAY
END-EXEC.
...
64
An SQLDA that contains the SQLTYPE and SQLLEN for each returned column is
defined by the associated descriptor used on the row storage area form of the
multiple-row FETCH. The information provided in the descriptor determines the
data mapping from the database to the row storage area. To maximize
performance, the attribute information in the descriptor should match the
attributes of the columns retrieved.
See Appendix C of the DB2 for AS/400 SQL Reference book for a description of the
SQLDA.
Consider the following PL/I example:
65
*....+....1....+....2....+....3....+....4....+....5....+....6....+....7...*
EXEC SQL INCLUDE SQLCA;
EXEC SQL INCLUDE SQLDA;
...
DCL DEPTPTR PTR;
DCL 1 DEPT(10) BASED(DEPTPTR),
3 EMPNO CHAR(6),
3 LASTNAME CHAR(15) VARYING,
3 WORKDEPT CHAR(3),
3 JOB CHAR(8);
DCL I BIN(31) FIXED;
DEC J BIN(31) FIXED;
DCL ROWAREA CHAR(2000);
...
ALLOCATE SQLDA SET(SQLDAPTR);
EXEC SQL
DECLARE D11 CURSOR FOR
SELECT EMPNO, LASTNAME, WORKDEPT, JOB
FROM CORPDATA.EMPLOYEE
WHERE WORKDEPT = 'D11';
...
EXEC SQL
OPEN D11;
/* SET UP THE DESCRIPTOR FOR THE MULTIPLE-ROW FETCH */
/* 4 COLUMNS ARE BEING FETCHED
*/
SQLD = 4;
SQLN = 4;
SQLDABC = 366;
SQLTYPE(1) = 452; /* FIXED LENGTH CHARACTER - */
/* NOT NULLABLE
*/
SQLLEN(1) = 6;
SQLTYPE(2) = 456; /*VARYING LENGTH CHARACTER
*/
/* NOT NULLABLE
*/
SQLLEN(2) = 15;
SQLTYPE(3) = 452; /* FIXED LENGTH CHARACTER - */
SQLLEN(3) = 3;
SQLTYPE(4) = 452; /* FIXED LENGTH CHARACTER - */
/* NOT NULLABLE
*/
SQLLEN(4) = 8;
/*ISSUE THE MULTIPLE-ROW FETCH STATEMENT TO RETRIEVE*/
/*THE DATA INTO THE DEPT ROW STORAGE AREA
*/
/*USE A HOST VARIABLE TO CONTAIN THE COUNT OF */
/*ROWS TO BE RETURNED ON THE MULTIPLE-ROW FETCH
*/
J = 10;
...
66
EXEC SQL
WHENEVER NOT FOUND
GOTO FINISHED;
EXEC SQL
WHENEVER SQLERROR
GOTO FINISHED;
EXEC SQL
FETCH D11 FOR :J ROWS
USING DESCRIPTOR :SQLDA INTO :ROWAREA;
/* ADDRESS THE ROWS RETURNED
DEPTPTR = ADDR(ROWAREA);
/*PROCESS EACH ROW RETURNED IN THE ROW STORAGE
/*AREA BASED ON THE COUNT OF RECORDS RETURNED
/*IN SQLERRD3.
DO I = 1 TO SQLERRD(3);
IF EMPNO(I) = '000170' THEN
DO;
:
END;
END;
IF SQLERRD(5) = 100 THEN
DO;
/* PROCESS END OF FILE */
END;
FINISHED:
*/
*/
*/
*/
In this example, a cursor has been defined for the CORPDATA.EMPLOYEE table to
select all rows where the WORKDEPT column equal 'D11'. The sample EMPLOYEE
table in Appendix A. DB2 for AS/400 Sample Tables shows the result table contains
eight rows. The DECLARE CURSOR and OPEN statements do not have special
syntax when they are used with a multiple-row FETCH statement. Another FETCH
statement that returns a single row against the same cursor can be coded elsewhere
in the program. The multiple-row FETCH statement is used to retrieve all rows in
the result table. Following the FETCH, the cursor position remains on the eighth
record in the block.
The row area, ROWAREA, is defined as a character array. The data from the result
table is placed in the host variable. In this example, a pointer variable is assigned
to the address of ROWAREA. Each item in the rows that are returned is examined
and used with the based structure DEPT.
The attributes (type and length) of the items in the descriptor match the columns
that are retrieved. In this case, no indicator area is provided.
After the FETCH statement is completed, the ROWAREA contains eight rows. The
SQLCA that is returned to the application contains the following:
v SQLCODE contains 0
v
v
v
v
In this example, the application has taken advantage of the fact that SQLERRD5
contains an indication of the end of the file being reached. As a result, the
application does not need to call SQL again to attempt to retrieve more rows. If the
Chapter 4. Using a Cursor
67
cursor has immediate sensitivity to inserts, you should call SQL in case any records
were added. Cursors have immediate sensitivity when the commitment control
level is something other than *RR.
68
using
using
using
using
subqueries
views
indexes
the system catalog
69
DSTRUCT is a host structure array with five elements that is declared in the
program. The five elements correspond to EMPNO, FIRSTNME, MIDINIT,
LASTNAME, and WORKDEPT. DSTRUCT has a dimension of at least ten to
accommodate inserting ten rows. ISTRUCT is a host structure array that is declared
in the program. ISTRUCT has a dimension of at least ten small integer fields for
the indicators.
Blocked INSERT statements are supported for non-distributed SQL applications
and for distributed applications where both the application server and the
application requester are AS/400 systems.
|
|
|
|
|
|
70
|
|
|
|
|
UPDATE EMPLOYEE
SET WORKDEPT = 'D11',
PHONENO = '7213',
JOB = 'DESIGNER'
WHERE EMPNO = '000270'
|
|
The previous update can also be written by specifying all of the columns and then
all of the values:
|
|
|
|
UPDATE EMPLOYEE
SET (WORKDEPT, PHONENO, JOB)
= ('D11', '7213', 'DESIGNER')
WHERE EMPNO = '000270'
|
|
|
|
|
|
|
Another way to select a value (or multiple values) for an update is to use a
scalar-subselect. The scalar-subselect allows you to update one or more columns by
setting them to one or more values selected from another table. In the following
example, an employee moves to a different department but continues working on
the same projects. The employee table has already been updated to contain the
new department number. Now the project table needs to be updated to reflect the
new department number of this employee (employee number is 000030).
|
|
|
|
|
UPDATE PROJECT
SET DEPTNO =
(SELECT WORKDEPT FROM EMPLOYEE
WHERE PROJECT.RESPEMP = EMPLOYEE.EMPNO)
WHERE RESPEMP='000030'
|
|
This same technique could be used to update a list of columns with multiple
values returned from a single select.
|
|
It is also possible to update an entire row in one table with values from a row in
another table.
|
|
|
|
Suppose there is a master class schedule table that needs to be udpated with
changes that have been made in a copy of the table. The changes are made to the
work copy and merged into the master table every night. The two tables have
exactly the same columns and one column, CLASS_CODE, is a unique key column.
|
|
|
|
UPDATE CL_SCHED
SET ROW =
(SELECT * FROM MYCOPY
WHERE CL_SCHED.CLASS_CODE = MYCOPY.CLASS_CODE)
This update will update all of the rows in CL_SCHED with the values from
MYCOPY.
DISTINCT means you want to select only the unique rows. If a selected row
duplicates another row in the result table, the duplicate row is ignored (it is not
put into the result table). For example, suppose you want a list of employee job
Chapter 5. Advanced Coding Techniques
71
codes. You do not need to know which employee has what job code. Because it is
probable that several people in a department have the same job code, you can use
DISTINCT to ensure that the result table has only unique values.
The following example shows how to do this:
DECLARE XMP2 CURSOR FOR
SELECT DISTINCT JOB
FROM CORPDATA.EMPLOYEE
WHERE WORKDEPT = :JOB-DEPT
...
FETCH XMP2
INTO :JOB
The result is two rows (in this example, JOB-DEPT is set to D11).
fetch
JOB
Designer
RV2W557-2
If you do not include DISTINCT in a SELECT clause, you might find duplicate
rows in your result, because SQL retrieves the JOB columns value for each row
that satisfies the search condition. Null values are treated as duplicate rows for
DISTINCT.
If you include DISTINCT in a SELECT clause and you also include a
shared-weight sort sequence, fewer values are returned. The sort sequence causes
values that contain the same characters to be weighted the same. If 'MGR', 'Mgr',
and 'mgr' were all in the same table, only one of these values would be returned.
72
v IN says you are interested in rows in which the value of the specified expression
is among the values you listed. For example, to find the names of all employees
in departments A00, C01, and E21, you could specify:
... WHERE WORKDEPT IN ('A00', 'C01', 'E21')
v LIKE says you are interested in rows in which a column value is similar to the
value you supply. When you use LIKE, SQL searches for a character string
similar to the one you specify. The degree of similarity is determined by two
special characters used in the string that you include in the search condition:
_
Note: If you are operating on MIXED data, the following distinction applies: an
SBCS underline character refers to one SBCS character. No such restriction
applies to the percent sign; that is, a percent sign refers to any number of
SBCS or DBCS characters. See the DB2 for AS/400 SQL Reference book for
more information on the LIKE predicate and MIXED data.
Use the underline character or percent sign either when you do not know or do
not care about all the characters of the columns value. For example, to find out
which employees live in Minneapolis, you could specify:
... WHERE ADDRESS LIKE '%MINNEAPOLIS%'
In this case, you should be sure that MINNEAPOLIS was not part of a street
address or part of another city name. SQL returns any row with the string
MINNEAPOLIS in the ADDRESS column, no matter where the string occurs.
In another example, to list the towns whose names begin with 'SAN', you could
specify:
... WHERE TOWN LIKE 'SAN%'
If you want to search for a character string that contains either the underscore or
percent character, use the ESCAPE clause to specify an escape character. For
example, to see all businesses that have a percent in their name, you could
specify:
... WHERE BUSINESS_NAME LIKE '%@%%' ESCAPE '@'
The first and last percent characters are interpreted as usual. The combination
@% is taken as the actual percent character.
73
For example, if you did a search using the string pattern ABC%, these are some
of the values that could be returned:
'ABCD
'
'ABCDE'
'ABCxxx'
'ABC '
For example, if you did a search using the search pattern ABC% contained in a
host variable with a fixed length of 10, these are some the values that could be
returned assuming the column has a length of 12:
'ABCDE
' 'ABCD
' 'ABCxxx
' 'ABC
'
Note that all returned values start with ABC and end with at least six blanks.
This is because the last six characters in the host variable were not assigned a
specific value so blanks were used.
If you wanted to do a search on a fixed-length host variable where the last 7
characters could be anything, you would search for ABC%%%%%%%. These
are some values that could be returned:
'ABCDEFGHIJ'
'ABCXXXXXXX'
'ABCDE'
'ABCDD'
v OR says that, for a row to qualify, the row can satisfy the condition set by either
or both predicates of the search condition. For example, to find out which
employees are in either department C01 or D11, you could specify 4:
...
WHERE WORKDEPT = 'C01' OR WORKDEPT = 'D11'
v NOT says that, to qualify, a row must not meet the criteria set by the search
condition or predicate that follows the NOT. For example, to find all employees
in department E11 except those with a job code equal to analyst, you could
specify:
...
WHERE WORKDEPT = 'E11' AND NOT JOB = 'ANALYST'
When SQL evaluates search conditions that contain these connectors, it does so in a
specific order. SQL first evaluates the NOT clauses, next evaluates the AND
clauses, and then the OR clauses.
4. You could also use IN to specify this request: WHERE WORKDEPT IN ('C01', 'D11').
74
You can change the order of evaluation by using parentheses. The search
conditions enclosed in parentheses are evaluated first. For example, to select all
employees in departments E11 and E21 who have education levels greater than 12,
you could specify:
...
WHERE EDLEVEL > 12 AND
(WORKDEPT = 'E11' OR WORKDEPT = 'E21')
The parentheses determine the meaning of the search condition. In this example,
you want all rows that have a:
WORKDEPT value of E11 or E21, and
EDLEVEL value greater than 12
If you did not use parentheses:
...
WHERE EDLEVEL > 12 AND WORKDEPT = 'E11'
OR WORKDEPT = 'E21'
Your result is different. The selected rows are rows that have:
WORKDEPT = E11 and EDLEVEL > 12, or
WORKDEPT = E21, regardless of the EDLEVEL value
Inner Join
With an inner join, column values from one row of a table are combined with
column values from another row of another (or the same) table to form a single
row of data. SQL examines both tables specified for the join to retrieve data from
all the rows that meet the search condition for the join. There are two ways of
specifying an inner join: using the JOIN syntax, and using the WHERE clause.
75
Suppose you want to retrieve the employee numbers, names, and project numbers
for all employees that are responsible for a project. In other words, you want the
EMPNO and LASTNAME columns from the CORPDATA.EMPLOYEE table and the
PROJNO column from the CORPDATA.PROJECT table. Only employees with last
names starting with S or later should be considered. To find this information, you
need to join the two tables.
In this example, the join is done on the two tables using the EMPNO and
RESPEMP columns from the tables. Since only employees that have last names
starting with at least S are to be returned, this additional condition is provided in
the WHERE clause.
This query returns the following output:
EMPNO
LASTNAME
PROJNO
000020
THOMPSON
PL2100
000060
STERN
MA2110
000100
SPENSER
OP2010
000250
SMITH
AD3112
Note
Although the results from inner joins done using the JOIN syntax and the WHERE
clause are the same, the performance of the two methods may be different. Using
the JOIN syntax will influence the query optimizer to leave the tables in the listed
order when performing the join. When the WHERE clause method is used, the
query optimizer will evaluate the tables being joined and reorder them if it
determines that a different order would perform better.
76
The result of this query contains some employees that do not have a project
number. They are listed in the query, but have the null value returned for their
project number.
EMPNO
LASTNAME
PROJNO
000020
THOMPSON
PL2100
000060
STERN
MA2110
000100
SPENSER
OP2010
000170
YOSHIMURA
000180
SCOUTTEN
000190
WALKER
000250
SMITH
AD3112
000280
SCHNEIDER
000300
SMITH
000310
SETRIGHT
Notes
If multiple join conditions are used in the left outer join or in the exception join
ON condition, all comparison operators in the ON condition must be the equal
operator; only one condition can be specified if a comparison other than equal is
used. Additional conditions can be specified if they are moved to the WHERE
clause. There, they will be used as additional selection conditions and will not be
used in performing the join.
Using the RRN scalar function to return the relative record number for a column in
the table on the right in a left outer join or exception join will return a value of 0
for the unmatched rows.
Exception Join
An exception join returns only the records from the first table that do NOT have a
match in the second table. Using the same tables as before, return those employees
that are not responsible for any projects.
77
LASTNAME
PROJNO
000170
YOSHIMURA
000180
SCOUTTEN
000190
WALKER
000280
SCHNEIDER
000300
SMITH
000310
SETRIGHT
An exception join can also be written as a subquery using the NOT EXISTS
predicate. The previous query could be rewritten in the following way:
SELECT EMPNO, LASTNAME
FROM CORPDATA.EMPLOYEE
WHERE LASTNAME > 'S'
AND NOT EXISTS
(SELECT * FROM CORPDATA.PROJECT
WHERE EMPNO = RESPEMP)
The only difference in this query is that it cannot return values from the PROJECT
table.
Cross Join
A cross join (or Cartesian Product join) will return a result table where each row
from the first table is combined with each row from the second table. The number
of rows in the result table is the product of the number of rows in each table. If the
tables involved are large, this join can take a very long time.
A cross join can be specified in two ways: using the JOIN syntax or by listing the
tables in the FROM clause separated by commas without using a WHERE clause to
supply join criteria.
Suppose the following tables exist.
Table 13. Table A
T1COL1
T1COL2
A1
AA1
A2
AA2
A3
AA3
T2COL2
B1
BB1
B2
BB2
78
The result table for either of these select statements looks like this:
T1COL1
T1COL2
T2COL1
T2COL2
A1
AA1
B1
BB1
A1
AA1
B2
BB2
A2
AA2
B1
BB1
A2
AA2
B2
BB2
A3
AA3
B1
BB1
A3
AA3
B2
BB2
LASTNAME
DEPTNAME
PROJNO
000020
THOMPSON
PLANNING
PL2100
000060
STERN
MANUFACTURING SYSTEMS
MA2110
000100
SPENSER
SOFTWARE SUPPORT
OP2010
000170
YOSHIMURA
MANUFACTURING SYSTEMS
000180
SCOUTTEN
MANUFACTURING SYSTEMS
000190
WALKER
MANUFACTURING SYSTEMS
000250
SMITH
ADMINISTRATION SYSTEMS
AD3112
000280
SCHNEIDER
OPERATIONS
000300
SMITH
OPERATIONS
000310
SETRIGHT
OPERATIONS
Notes on Joins
When you join two or more tables:
v If there are common column names, you must qualify each common name with
the name of the table (or a correlation name). Column names that are unique do
not need to be qualified.
v If you do not list the column names you want, but instead use SELECT *, SQL
returns rows that consist of all the columns of the first table, followed by all the
columns of the second table, and so on.
79
v You must be authorized to select rows from each table or view specified in the
FROM clause.
v The sort sequence is applied to all character and UCS-2 graphic columns being
joined.
To better understand what results from these SQL statements, imagine that SQL
goes through the following process:
80
000060
000150
000160
000170
000180
...
...
RV3W186-0
If the result columns are unnamed, use numbers to order the result. The number
refers to the position of the expression in the list of expressions you include in
your subselects.
SELECT A + B ...
UNION SELECT X ... ORDER BY 1
81
To identify which subselect each row is from, you can include a constant at the end
of the select list of each subselect in the union. When SQL returns your results, the
last column contains the constant for the subselect that is the source of that row.
For example, you can specify:
SELECT A, B, 'A1' ... UNION SELECT X, Y, 'B2'
000060
000150
000150
000150
000160
000160
000170
000170
...
...
RV3W187-0
v When you include the UNION ALL in the same SQL statement as a UNION
operator, however, the result of the operation depends on the order of
82
Using Subqueries
In the WHERE and HAVING clauses you have seen so far, you specified a search
condition by using a literal value, a column name, an expression, or the registers.
In those search conditions, you know that you are searching for a specific value,
but sometimes you cannot supply that value until you have retrieved other data
from a table. For example, suppose you want a list of the employee numbers,
names, and job codes of all employees working on a particular project, say project
number MA2100. The first part of the statement is easy to write:
DECLARE XMP CURSOR FOR
SELECT EMPNO, LASTNAME, JOB
FROM CORPDATA.EMPLOYEE
WHERE EMPNO ...
But you cannot go further because the CORPDATA.EMPLOYEE table does not
include project number data. You do not know which employees are working on
project MA2100 without issuing another SELECT statement against the
CORPDATA.EMP_ACT table.
With SQL, you can nest one SELECT statement within another to solve this
problem. The inner SELECT statement is called a subquery. The SELECT statement
surrounding the subquery is called the outer-level SELECT. Using a subquery, you
could issue just one SQL statement to retrieve the employee numbers, names, and
job codes for employees who work on project MA2100:
DECLARE XMP CURSOR FOR
SELECT EMPNO, LASTNAME, JOB
FROM CORPDATA.EMPLOYEE
WHERE EMPNO IN
(SELECT EMPNO
FROM CORPDATA.EMP_ACT
WHERE PROJNO = 'MA2100')
To better understand what will result from this SQL statement, imagine that SQL
goes through the following process:
83
fetch
EMPNO
LASTNAME
JOB
000010
HAAS
PRES
000110
LUCCHESSI
SALESREP
RV2W559-2
Correlation
The purpose of a subquery is to supply information needed to qualify a row
(WHERE clause) or a group of rows (HAVING clause). This is done through the
result table that the subquery produces. Conceptually, the subquery is evaluated
whenever a new row or group of rows must be qualified. In fact, if the subquery is
the same for every row or group, it is evaluated only once. For example, the
previous subquery has the same content for every row of the table
CORPDATA.EMPLOYEE. Subqueries like this are said to be uncorrelated.
Some subqueries vary in content from row to row or group to group. The
mechanism that allows this is called correlation, and the subqueries are said to be
correlated. More information on correlated subqueries can be found in Correlated
Subqueries on page 87. Even so, what is said before that point applies equally to
correlated and uncorrelated subqueries.
84
Subqueries can also appear in the search conditions of other subqueries. Such
subqueries are said to be nested at some level of nesting. For example, a subquery
within a subquery within an outer-level SELECT is nested at a nesting level of two.
SQL allows nesting down to a nesting level of 32, but few queries require a nesting
level greater than 1.
Basic Comparisons
You can use a subquery immediately after any of the comparison operators. If you
do, the subquery can return at most one value. The value can be the result of a
column function or an arithmetic expression. SQL then compares the value that
results from the subquery with the value to the left of the comparison operator. For
example, suppose you want to find the employee numbers, names, and salaries for
employees whose education level is higher than the average education level
throughout the company.
DECLARE XMP CURSOR FOR
SELECT EMPNO, LASTNAME, SALARY
FROM CORPDATA.EMPLOYEE
WHERE EDLEVEL >
(SELECT AVG(EDLEVEL)
FROM CORPDATA.EMPLOYEE)
SQL first evaluates the subquery and then substitutes the result in the WHERE
clause of the SELECT statement. In this example, the result is (as it should be) the
company-wide average educational level. Besides returning a single value, a
subquery could return no value at all. If it does, the result of the compare is
unknown. Consider, for example, the first query shown in this section, and assume
that there are not any employees currently working on project MA2100. Then the
subquery would return no value, and the search condition would be unknown for
every row. In this case, then, the result produced by the query would be an empty
table.
To satisfy this WHERE clause, the value in the expression must be greater than
all the values (that is, greater than the highest value) returned by the subquery.
If the subquery returns an empty set (that is, no values were selected), the
condition is satisfied.
v Use ANY or SOME to indicate that the value you supplied must compare in the
indicated way to at least one of the values the subquery returns. For example,
suppose you use the greater-than comparison operator with ANY:
... WHERE expression > ANY (subquery)
85
To satisfy this WHERE clause, the value in the expression must be greater than
at least one of the values (that is, greater than the lowest value) returned by the
subquery. If what the subquery returns is empty, the condition is not satisfied.
Note: The results when a subquery returns one or more null values may surprise
you, unless you are familiar with formal logic. For applicable rules, read the
discussion of quantified predicates in the DB2 for AS/400 SQL Reference .
In the example, the search condition holds if any project represented in the
CORPDATA.PROJECT table has an estimated start date that is later than January 1,
1982. Please note that this example does not show the full power of EXISTS,
because the result is always the same for every row examined for the outer-level
SELECT. As a consequence, either every row appears in the results, or none
appear. In a more powerful example, the subquery itself would be correlated, and
would change from row to row. See Correlated Subqueries on page 87 for more
information on correlated subqueries.
As shown in the example, you do not need to specify column names in the
subquery of an EXISTS clause. Instead, you can code SELECT *.
You could also use the EXISTS keyword with the NOT keyword in order to select
rows when the data or condition you specify does not exist. That is, you could use:
... WHERE NOT EXISTS (SELECT ...)
For all general types of usage for subqueries but one (using a subquery with the
EXISTS keyword), the subquery must produce a one-column result table. This
means that the SELECT clause in a subquery must name a single column, or
contain a single expression. For example, both of the following SELECT clauses
would be allowed for all four usage types:
SELECT AVG(SALARY)
SELECT EMPNO
86
The result table produced by a subquery can have zero or more rows. For some
usages, no more than one row is allowed.
In the examples shown so far, you have seen subqueries within SELECT
statements. You can also use subqueries in the WHERE clause of the UPDATE or
DELETE statements or in the SET clause of an UPDATE. For the most part, this is
not very different from using subqueries with outer-level SELECTs.
Correlated Subqueries
In the subqueries previously discussed, SQL evaluates the subquery once,
substitutes the result of the subquery in the right side of the search condition, and
evaluates the outer-level SELECT based on the value of the search condition. You
can also write a subquery that SQL may have to re-evaluate as it examines each
new row (WHERE clause) or group of rows (HAVING clause) in the outer-level
SELECT. This is called a correlated subquery.
87
this information, SQL must search the CORPDATA.EMPLOYEE table. For each
employee in the table, SQL needs to compare the employees education level to the
average education level for the employees department. In the subquery, you tell
SQL to calculate the average education level for the department number in the
current row. For example:
DECLARE XMP CURSOR FOR
SELECT EMPNO, LASTNAME, WORKDEPT, EDLEVEL
FROM CORPDATA.EMPLOYEE X
WHERE EDLEVEL >
(SELECT AVG(EDLEVEL)
FROM CORPDATA.EMPLOYEE
WHERE WORKDEPT = X.WORKDEPT)
A correlated subquery looks like an uncorrelated one, except for the presence of
one or more correlated references. In the example, the single correlated reference is
the occurrence of X.WORKDEPT in the subselects FROM clause. Here, the
qualifier X is the correlation name defined in the FROM clause of the outer
SELECT statement. In that clause, X is introduced as the correlation name of the
table CORPDATA.EMPLOYEE.
Now, consider what happens when the subquery is executed for a given row of
CORPDATA.EMPLOYEE. Before it is executed, the occurrence of X.WORKDEPT is
replaced with the value of the WORKDEPT column for that row. Suppose, for
example, that the row is for CHRISTINE I HAAS. Her work department is A00,
which is the value of WORKDEPT for this row. The subquery executed for this
row is:
(SELECT AVG(EDLEVEL)
FROM CORPDATA.EMPLOYEE
WHERE WORKDEPT = 'A00')
Thus, for the row considered, the subquery produces the average education level
of Christines department. This is then compared in the outer statement to
Christines own education level. For some other row for which WORKDEPT has a
different value, that value appears in the subquery in place of A00. For example,
for the row for MICHAEL L THOMPSON, this value would be B01, and the
subquery for his row would deliver the average education level for department
B01.
The result table produced by the query would have the following values:
(from CORPDATA.EMPLOYEE)
fetch EMPNO
LASTNAME
WORKDEPT
EDLEVEL
000010
HAAS
A00
18
000030
KWAN
C01
20
000070
PULASKI
D21
16
000090
HENDERSON
E11
16
RV2W560-3
88
Consider what happens when the subquery is executed for a given department of
CORPDATA.EMPLOYEE. Before it is executed, the occurrence of X.WORKDEPT is
replaced with the value of the WORKDEPT column for that group. Suppose, for
example, that the first group selected has A00 for the value of WORKDEPT. The
subquery executed for this group is:
(SELECT AVG(SALARY)
FROM CORPDATA.EMPLOYEE
WHERE SUBSTR('A00',1,1) = SUBSTR(WORKDEPT,1,1))
Thus, for the group considered, the subquery produces the average salary for the
area. This is then compared in the outer statement to the average salary for
department 'A00'. For some other group for which WORKDEPT is B01, the
subquery would result in the average salary for the area where department B01
belongs.
The result table produced by the query would have the following values:
(from CORPDATA.EMPLOYEE)
fetch WORKDEPT
AVG
SALARY
D21
25153.33
E01
40175.00
RV2W561-3
89
You can define a correlation name for each table name appearing in a FROM
clause. Simply include the correlation names after the table names. Leave one or
more blanks between a table name and its correlation name, and place a comma
after the correlation name if it is followed by another table name. The following
FROM clause, for example, defines the correlation names TA and TB for the tables
TABLEA and TABLEB, and no correlation name for the table TABLEC.
FROM TABLEA TA, TABLEC, TABLEB TB
90
Suppose a row in the CORPDATA.PROJECT table was deleted. Rows related to the
deleted project in the CORPDATA.EMP_ACT table must also be deleted. To do
this, you can use:
DELETE FROM CORPDATA.EMP_ACT X
WHERE NOT EXISTS
(SELECT *
FROM CORPDATA.PROJECT
WHERE PROJNO = X.PROJNO)
SQL determines, for each row in the CORPDATA.EMP_ACT table, whether a row
with the same project number exists in the CORPDATA.PROJECT table. If not, the
CORPDATA.EMP_ACT row is deleted.
v The correlated subquery and the outer-level statement can refer to the same
table or to different tables.
v In an INSERT statement, neither the correlated subquery nor an outer-level
SELECT within the INSERT statement can be based on the same table into
which you are inserting.
v The outer-level SELECT that defines the correlation name can join two or more
tables.
v You can use correlated subqueries in HAVING clauses. When you do, SQL
evaluates the subquery, once per group, of the outer-level SELECT. The column
you refer to in the HAVING clause must specify a property of each group (for
example, WORKDEPT) either the columns you grouped the rows by or another
column with one of the column functions.
v You can nest correlated subqueries.
91
TO data type
Decimal
Numeric
Decimal
Integer, Smallint
Decimal
Float
Numeric
Decimal
Numeric
Integer, Smallint
Numeric
Float
Integer, Smallint
Decimal
Integer, Smallint
Numeric
Integer, Smallint
Float
Float
Numeric
Float
Integer, Smallint
Character
DBCS-open
Character
UCS-2 graphic
DBCS-open
Character
DBCS-open
UCS-2 graphic
DBCS-either
Character
DBCS-either
DBCS-open
DBCS-either
UCS-2 graphic
DBCS-only
DBCS-open
DBCS-only
DBCS graphic
DBCS-only
UCS-2 graphic
DBCS graphic
UCS-2 graphic
UCS-2 graphic
Character
UCS-2 graphic
DBCS-open
UCS-2 graphic
DBCS graphic
When converting to a longer length, data will be padded with the appropriate pad
character. When converting to a shorter length, data may be lost due to truncation.
An inquiry message prompts you to confirm the request.
If you have a column that does not allow the null value and you want to change it
to now allow the null value, use the DROP NOT NULL clause. If you have a
column that allows the null value and you want to prevent the use of null values,
use the SET NOT NULL clause. This will result in an SQLCODE of -190 if any of
the existing values in that column are the null value and the ALTER TABLE will
not be performed.
When modifying an existing column, only the attributes that you specify will be
changed. All other attributes will remain unchanged. For example, given the
following table definition:
92
COL2 would still have an allocated length of 10 and CCSID 937, and COL3 would
still have an allocated length of 10.
Dropping a column deletes that column from the table definition. If CASCADE is
specified, any views, indexes, and constraints dependent on that column will also
be dropped. If RESTRICT is specified, SQLCODE of -196 will be issued if any
views, indexes, or constraints are dependent on the column, and the column will
not be dropped.
For details on adding and dropping constraints, see Chapter 6. Data Integrity.
An ALTER TABLE statement is performed as a set operation as long as
commitment control is active. However, internally, the operation is broken down
into the following steps:
1. Drop constraints
2. Drop columns for which the RESTRICT option was specified
3. Alter column definitions (this includes adding columns and dropping columns
for which the CASCADE option was specified)
4. Add constraints
Within each of these stages, the order in which the user specifies the clauses is the
order in which they are performed, with one exception. If any columns are being
dropped, that operation is logically done before any column definitions are added
or altered, in case record length is increased as a result of the ALTER TABLE
statement.
If the select list contains elements other than columns such as expressions,
functions, constants, or special registers, and the AS clause was not used to name
the columns, a column list must be specified for the view. In the following
example, the columns of the view are LASTNAME and YEARSOFSERVICE.
93
The previous view can also be defined by using the AS clause in the select list to
name the columns in the view. For example:
CREATE VIEW CORPDATA.EMP_YEARSOFSERVICE AS
SELECT LASTNAME,
YEARS (CURRENT_DATE - HIREDATE) AS YEARSOFSERVICE
FROM CORPDATA.EMPLOYEE
Once you have created the view, you can use it to select the data or possibly
change the data in the base table.
The following restrictions must be considered when creating the view:
v You cannot change, insert, or delete data in a read-only view. A view is
read-only if it includes any of the following:
The first FROM clause identifies more than one table (join).
The first FROM clause identifies a read-only view.
The first SELECT clause contains any of the SQL column functions (SUM,
MAX, MIN, AVG, COUNT, STDDEV, or VAR).
The first SELECT clause specifies the keyword DISTINCT.
The outer subselect contains a GROUP BY or HAVING clause.
A subquery, such that the base object of the outer-most subselect and a table
of a subquery are the same table
In the above cases, you can get data from the views by means of the SQL
SELECT statement, but you cannot use statements such as INSERT, UPDATE,
or DELETE.
v You cannot insert a row in a view if:
The table on which the view is based has a column that has no default value,
does not allow nulls, and is not in the view.
The view has a column resulting from an expression, a constant, a function,
or a special register and the column was specified in the INSERT column list.
The WITH CHECK OPTION was specified when the view was created and
the row does not match the selection criteria.
v You cannot update a column of a view that results from an expression, a
constant, a function, or a special register.
v You cannot use UNION, UNION ALL, FOR UPDATE OF, FOR READ ONLY,
ORDER BY, or OPTIMIZE FOR n ROWS in the definition of a view.
Views are created with the sort sequence in effect at the time the CREATE VIEW
statement is run. The sort sequence applies to all character and UCS-2 graphic
comparisons in the CREATE VIEW statement subselect. See Using Sort Sequence
in SQL on page 49 for more information on sort sequences.
Views can also be created using the WITH CHECK OPTION to specify the level of
checking that should be done when data is inserted or updated through the view.
See WITH CHECK OPTION on a View on page 106 for more information.
94
Using Indexes
An index is used by the system for faster data retrieval. The following example
creates an index over the column LASTNAME in the CORPDATA.EMPLOYEE
table:
CREATE INDEX CORPDATA.INX1 ON CORPDATA.EMPLOYEE (LASTNAME)
Any number of indexes can be created. However, because the indexes are
maintained by the system, a large number of indexes can adversely affect
performance. For more information on working with indexes, see Effectively
Using an SQL Index on page 366.
If an index is created that has exactly the same attributes as an existing index, the
new index shares the existing indexes binary tree. Otherwise, another binary tree
is created. If the attributes of the new index are exactly the same as another index,
except the new index has one or more fewer columns, another binary tree is still
created. It is still created because the extra columns would prevent the index from
being used by cursors or UPDATE statements which update those extra columns.
Indexes are created with the sort sequence in effect at the time the CREATE INDEX
statement is run. The sort sequence applies to all SBCS character fields and UCS-2
graphic fields of the index. See Using Sort Sequence in SQL on page 49 for more
information on sort sequences.
95
The result of the previous sample statement is a row of information for each
column in the table. Some of the information is not visible because the width of
the information is wider than the display screen.
For more information about each column, specify a select-statement like this:
SELECT NAME, TBNAME, COLTYPE, LENGTH, DEFAULT
FROM CORPDATA.SYSCOLUMNS
WHERE TBNAME = 'DEPARTMENT'
In addition to the column name for each column, the select-statement shows:
v The name of the table that contains the column
v The data type of the column
v The length attribute of the column
v If the column allows default values
The result looks like this:
96
NAME
TBNAME
COLTYPE
LENGTH
DEFAULT
DEPTNO
DEPARTMENT
CHAR
DEPTNAME
DEPARTMENT
VARCHAR
29
MGRNO
DEPARTMENT
CHAR
ADMRDEPT
DEPARTMENT
CHAR
This statement creates a table with three columns and a check constraint over
COL2 which limits the values allowed in that column to positive integers. Given
this table, the following statement:
INSERT INTO T1 VALUES (-1, -1, -1)
would fail because the value to be inserted into COL2 does not meet the check
constraint; this is, -1 is not greater than 0. The following statement:
INSERT INTO T1 VALUES (1, 1, 1)
would be successful. Once that row is inserted, the following statement would fail:
ALTER TABLE T1 ADD CONSTRAINT C1 CHECK (COL1=1 AND COL1<COL2)
This ALTER TABLE statement attempts to add a second check constraint which
limits the value allowed in COL1 to 1 and also effectively rules that values in
COL2 be greater than 1. This constraint would not be be allowed because the
second part of the constraint is not met by the existing data (the value of 1 in
COL2 is not less than the value of 1 in COL1).
97
98
In this case, the DEPARTMENT table has a column of unique department numbers
(DEPTNO) which functions as a primary key, and is a parent table in two
constraint relationships:
REPORTS_TO_EXISTS
is a self-referencing constraint in which the DEPARTMENT table is both
the parent and the dependent in the same relationship. Every non-null
value of ADMRDEPT must match a value of DEPTNO. A department must
report to an existing department in the database. The DELETE CASCADE
rule indicates that if a row with a DEPTNO value n is deleted, every row
in the table for which the ADMRDEPT is n is also deleted.
WORKDEPT_EXISTS
establishes the EMPLOYEE table as a dependent table, and the column of
employee department assignments (WORKDEPT) as a foreign key. Thus,
every value of WORKDEPT must match a value of DEPTNO. The DELETE
SET NULL rule says that if a row is deleted from DEPARTMENT in which
the value of DEPTNO is n, then the value of WORKDEPT in EMPLOYEE
is set to null in every row in which the value was n. The UPDATE
RESTRICT rule says that a value of DEPTNO in DEPARTMENT cannot be
updated if there are values of WORKDEPT in EMPLOYEE that match the
current DEPTNO value.
Constraint UNIQUE_LNAME_IN_DEPT in the EMPLOYEE table causes last names
to be unique within a department. While this constraint is unlikely, it illustrates
how a constraint made up of several columns can be defined at the table level.
Once a referential constraint is defined, the system enforces the constraint on every
INSERT, DELETE, and UPDATE operation performed through SQL or any other
interface including CL commands, utilities, or high-level language statements.
99
100
Notice that the parent table columns are not specified in the REFERENCES clause.
The columns are not required to be specified as long as the referenced table has a
primary key or eligible unique key which can be used as the parent key.
Every row inserted into the PROJECT table must have a value of DEPTNO that is
equal to some value of DEPTNO in the department table. (The null value is not
allowed because DEPTNO in the project table is defined as NOT NULL.) The row
must also have a value of RESPEMP that is either equal to some value of EMPNO
in the employee table or is null.
The tables with the sample data as they appear in Appendix A. DB2 for AS/400
Sample Tables conform to these constraints. The following INSERT statement fails
because there is no matching DEPTNO value (A01) in the DEPARTMENT table.
INSERT INTO CORPDATA.PROJECT (PROJNO, PROJNAME, DEPTNO, RESPEMP)
VALUES ('AD3120', 'BENEFITS ADMIN', 'A01', '000010')
Update Rules
The action taken on dependent tables when an UPDATE is performed on a parent
table depends on the update rule specified for the referential constraint. If no
update rule was defined for a referential constraint, the UPDATE NO ACTION
rule is used.
v UPDATE NO ACTION
Specifies that the row in the parent table can be updated if no other row
depends on it. If a dependent row exists in the relationship, the UPDATE fails.
The check for dependent rows is performed at the end of the statement.
v UPDATE RESTRICT
Specifies that the row in the parent table can be updated if no other row
depends on it. If a dependent row exists in the relationship, the UPDATE fails.
The check for dependent rows is performed immediately.
101
The subtle difference between RESTRICT and NO ACTION rules is easiest seen
when looking at the interaction of triggers and referential constraints. Triggers can
be defined to fire either before or after an operation (an UPDATE statement, in this
case). A before trigger fires before the UPDATE is performed and therefore before
any checking of constraints. An after trigger is fired after the UPDATE is performed,
and after a constraint rule of RESTRICT (where checking is performed
immediately), but before a constraint rule of NO ACTION (where checking is
performed at the end of the statement). The triggers and rules would occur in the
following order:
1. A before trigger would be fired before the UPDATE and before a constraint rule
of RESTRICT or NO ACTION.
2. An after trigger would be fired after a constraint rule of RESTRICT, but before a
NO ACTION rule.
If you are updating a dependent table, any non-null foreign key values that you
change must match the primary key for each relationship in which the table is a
dependent. For example, department numbers in the employee table depend on
the department numbers in the department table. You can assign an employee to
no department (the null value), but not to a department that does not exist.
If an UPDATE against a table with a referential constraint fails, all changes made
during the update operation are undone. For more information on the implications
of commitment control and journaling when working with constraints, see
Journaling on page 299 and Commitment Control on page 299.
The following statement fails because it violates the referential constraint that exists
between the primary key DEPTNO in DEPARTMENT and the foreign key
DEPTNO in PROJECT:
UPDATE CORPDATA.PROJECT
SET DEPTNO = 'D00'
WHERE DEPTNO = 'D01';
102
deletes or updates rows according to the delete rules specified. All delete rules of
all affected relationships must be satisfied in order for the delete operation to
succeed. If a referential constraint is violated, the DELETE fails.
The action to be taken on dependent tables when a DELETE is performed on a
parent table depends on the delete rule specified for the referential constraint. If no
delete rule was defined, the DELETE NO ACTION rule is used.
v DELETE NO ACTION
Specifies that the row in the parent table can be deleted if no other row depends
on it. If a dependent row exists in the relationship, the DELETE fails. The check
for dependent rows is performed at the end of the statement.
v DELETE RESTRICT
Specifies that the row in the parent table can be deleted if no other row depends
on it. If a dependent row exists in the relationship, the DELETE fails. The check
for dependent rows is performed immediately.
For example, you cannot delete a department from the department table if it is
still responsible for some project which is described by a dependent row in the
project table.
v DELETE CASCADE
Specifies that first the designated rows in the parent table are deleted. Then, the
dependent rows are deleted.
For example, you can delete a department by deleting its row in the department
table. Deleting the row from the department table also deletes:
The rows for all departments that report to it
All departments that report to those departments and so forth.
v DELETE SET NULL
Specifies that each nullable column of the foreign key in each dependent row is
set to its default value. This means that the column is only set to its default
value if it is a member of a foreign key that references the row being deleted.
Only the dependent rows that are immediate descendents are affected.
v DELETE SET DEFAULT
Specifies that each column of the foreign key in each dependent row is set to its
default value. This means that the column is only set to its default value if it is a
member of a foreign key that references the row being deleted. Only the
dependent rows that are immediate descendants are affected.
For example, you can delete an employee from the employee table even if the
employee manages some department. In that case, the value of MGRNO for each
employee who reported to the manager is set to blanks in the department table.
If some other default value was specified on the create of the table, that value is
used.
This is due to the REPORTS_TO_EXISTS constraint defined for the department
table.
If a descendent table has a delete rule of RESTRICT or NO ACTION and a row is
found such that a descendant row cannot be deleted, the entire DELETE fails.
When running this statement with a program, the number of rows deleted is
returned in SQLERRD(3) in the SQLCA. This number includes only the number of
rows deleted in the table specified in the DELETE statement. It does not include
those rows deleted according to the CASCADE rule. SQLERRD(5) in the SQLCA
contains the number of rows that were affected by referential constraints in all
tables.
Chapter 6. Data Integrity
103
The subtle difference between RESTRICT and NO ACTION rules is easiest seen
when looking at the interaction of triggers and referential constraints. Triggers can
be defined to fire either before or after an operation (a DELETE statement, in this
case). A before trigger fires before the DELETE is performed and therefore before
any checking of constraints. An after trigger is fired after the DELETE is performed,
and after a constraint rule of RESTRICT (where checking is performed
immediately), but before a constraint rule of NO ACTION (where checking is
performed at the end of the statement). The triggers and rules would occur in the
following order:
1. A before trigger would be fired before the DELETE and before a constraint rule
of RESTRICT or NO ACTION.
2. An after trigger would be fired after a constraint rule of RESTRICT, but before a
NO ACTION rule.
Given the tables and the data as they appear in Appendix A. DB2 for AS/400
Sample Tables, one row is deleted from table DEPARTMENT, and table
EMPLOYEE is updated to set the value of WORKDEPT to its default wherever the
value was E11. A question mark (?) in the sample data below reflects the null
value. The results would appear as follows:
Table 16. DEPARTMENT Table. Contents of the table after the DELETE statement is
complete.
DEPTNO
DEPTNAME
MGRNO
ADMRDEPT
A00
000010
A00
B01
PLANNING
000020
A00
C01
INFORMATION CENTER
000030
A00
D01
DEVELOPMENT CENTER
A00
D11
MANUFACTURING SYSTEMS
000060
D01
D21
ADMINISTRATION SYSTEMS
000070
D01
E01
SUPPORT SERVICES
000050
A00
E21
SOFTWARE SUPPORT
000100
E01
Note that there were no cascaded deletes in the DEPARTMENT table because no
department reported to department E11.
Below are snapshots of the affected portion of the EMPLOYEE table before and
after the DELETE statement is completed.
Table 17. Partial EMPLOYEE Table. Partial contents before the DELETE statement.
104
EMPNO
FIRSTNME MI
000230
JAMES
JEFFERSON
D21
2094
1966-11-21
000240
SALVATORE M
MARINO
D21
3780
1979-12-05
000250
DANIEL
SMITH
D21
0961
1960-10-30
Table 17. Partial EMPLOYEE Table (continued). Partial contents before the DELETE
statement.
EMPNO
FIRSTNME MI
000260
SYBIL
JOHNSON
D21
8953
1975-09-11
000270
MARIA
PEREZ
D21
9001
1980-09-30
000280
ETHEL
SCHNEIDER E11
0997
1967-03-24
000290
JOHN
PARKER
E11
4502
1980-05-30
000300
PHILIP
SMITH
E11
2095
1972-06-19
000310
MAUDE
SETRIGHT
E11
3332
1964-09-12
000320
RAMLAL
MEHTA
E21
9990
1965-07-07
000330
WING
LEE
E21
2103
1976-02-23
000340
JASON
GOUNOT
E21
5696
1947-05-05
Table 18. Partial EMPLOYEE Table. Partial contents after the DELETE statement.
EMPNO
FIRSTNME MI
000230
JAMES
JEFFERSON
D21
2094
1966-11-21
000240
SALVATORE M
MARINO
D21
3780
1979-12-05
000250
DANIEL
SMITH
D21
0961
1960-10-30
000260
SYBIL
JOHNSON
D21
8953
1975-09-11
000270
MARIA
PEREZ
D21
9001
1980-09-30
000280
ETHEL
SCHNEIDER ?
0997
1967-03-24
000290
JOHN
PARKER
4502
1980-05-30
000300
PHILIP
SMITH
2095
1972-06-19
000310
MAUDE
SETRIGHT
3332
1964-09-12
000320
RAMLAL
MEHTA
E21
9990
1965-07-07
000330
WING
LEE
E21
2103
1976-02-23
000340
JASON
GOUNOT
E21
5696
1947-05-05
Check Pending
Referential constraints and check constraints can be in a state known as check
pending, where potential violations of the constraint exist. For referential
constraints, a violation occurs when potential mismatches exist between parent and
foreign keys. For check constraints, a violation occurs when potential values exist
in columns which are limited by the check constraint. When the system determines
that the constraint may have been violated (such as after a restore operation), the
constraint is marked as check pending. When this happens, restrictions are placed
on the use of tables involved in the constraint. For referential constraints, the
following restrictions apply:
v No input or output operations are allowed on the dependent file.
v Only read and insert operations are allowed on the parent file.
When a check constraint is in check pending, the following restrictions apply:
v Read operations are not allowed on the file.
v Inserts and updates are allowed and the constraint is enforced.
Chapter 6. Data Integrity
105
Create another view over V1, specifying the WITH CASCADED CHECK OPTION:
CREATE VIEW V2 AS SELECT COL1
FROM V1 WITH CASCADED CHECK OPTION
106
The following INSERT statement fails because it would produce a row that does
not conform to the definition of V2:
INSERT INTO V2 VALUES (5)
The following INSERT statement fails only because V3 is dependent on V2, and V2
has a WITH CASCADED CHECK OPTION.
INSERT INTO V3 VALUES (5)
Create second view over V1, this time specifying WITH LOCAL CHECK OPTION:
CREATE VIEW V2 AS SELECT COL1
FROM V1 WITH LOCAL CHECK OPTION
The same INSERT that failed in the previous CASCADED CHECK OPTION
example would succeed now because V2 does not have any search conditions, and
the search conditions of V1 do not need to be checked since V1 does not specify a
check option.
INSERT INTO V2 VALUES (5)
The difference between LOCAL and CASCADED CHECK OPTION lies in how
many of the dependent views search conditions are checked when a row is
inserted or updated.
v WITH LOCAL CHECK OPTION specifies that the search conditions of only
those dependent views that have the WITH LOCAL CHECK OPTION or WITH
CASCADED CHECK OPTION are checked when a row is inserted or updated.
107
v WITH CASCADED CHECK OPTION specifies that the search conditions of all
dependent views are checked when a row is inserted or updated.
Example
Use the following table and views:
CREATE TABLE T1 (COL1 CHAR(10))
CREATE VIEW V1 AS SELECT COL1
FROM T1 WHERE COL1 LIKE 'A%'
CREATE VIEW V2 AS SELECT COL1
FROM V1 WHERE COL1 LIKE '%Z'
WITH LOCAL CHECK OPTION
CREATE VIEW V3 AS SELECT COL1
FROM V2 WHERE COL1 LIKE 'AB%'
CREATE VIEW V4 AS SELECT COL1
FROM V3 WHERE COL1 LIKE '%YZ'
WITH CASCADED CHECK OPTION
CREATE VIEW V5 AS SELECT COL1
FROM V4 WHERE COL1 LIKE 'ABC%'
108
Trigger Sample
A sample trigger program follows. It is written in ILE C, with embedded SQL.
See the DB2 for AS/400 Database Programming book for a full discussion and more
examples of trigger usage in DB2 for AS/400.
109
#include "string.h"
#include "stdlib.h"
#include "stdio.h"
#include <recio.h>
#include <xxcvt.h>
#include "qsysinc/h/trgbuf"
/* Trigger input parameter
*/
#include "lib1/csrc/msghand1"
/* User defined message handler
*/
/*********************************************************************/
/* This is a trigger program which is called whenever there is an
*/
/* update to the EMPLOYEE table. If the employee's commission is
*/
/* greater than the maximum commission, this trigger program will
*/
/* increase the employee's salary by 1.04 percent and insert into
*/
/* the RAISE table.
*/
/*
*/
/* The EMPLOYEE record information is passed from the input parameter*/
/* to this trigger program.
*/
/*********************************************************************/
Qdb_Trigger_Buffer_t *hstruct;
char *datapt;
/*******************************************************/
/* Structure of the EMPLOYEE record which is used to
*/
/* store the old or the new record that is passed to
*/
/* this trigger program.
*/
/*
*/
/* Note : You must ensure that all the numeric fields */
/*
are aligned at 4 byte boundary in C.
*/
/*
Used either Packed struct or filler to reach */
/*
the byte boundary alignment.
*/
/*******************************************************/
_Packed struct rec{
char empn[6];
_Packed struct { short fstlen ;
char fstnam[12];
} fstname;
char minit[1];
_Packed struct { short lstlen;
char lstnam[15];
} lstname;
char dept[3];
char phone[4];
char hdate[10];
char jobn[8];
short edclvl;
char sex1[1];
char bdate[10];
decimal(9,2) salary1;
decimal(9,2) bonus1;
decimal(9,2) comm1;
} oldbuf, newbuf;
EXEC SQL INCLUDE SQLCA;
110
*/
*/
*/
*/
*/
*/
*/
*/
struct {
char empno[6];
char name[30];
decimal(9,2) salary;
decimal(9,2) new_salary;
} rpt1;
/*******************************************************/
/* Start to monitor any exception.
*/
/*******************************************************/
_FEEDBACK fc;
_HDLR_ENTRY hdlr = main_handler;
/****************************************/
/* Make the exception handler active.
*/
/****************************************/
CEEHDLR(&hdlr, NULL, &fc);
/****************************************/
/* Ensure exception handler OK
*/
/****************************************/
if (fc.MsgNo != CEE0000)
{
printf("Failed to register exception handler.\n");
exit(99);
};
/*******************************************************/
/* Move the data from the trigger buffer to the local */
/* structure for reference.
*/
/*******************************************************/
hstruct = (Qdb_Trigger_Buffer_t *)argv[1];
datapt = (char *) hstruct;
obufoff = hstruct ->Old_Record_Offset;
/* old buffer
memcpy(&oldbuf,datapt+obufoff,; hstruct->Old_Record_Len);
*/
*/
111
GO TO ERR_EXIT;
/*******************************************************/
/* Set the transaction isolation level to the same as */
/* the application based on the input parameter in the */
/* trigger buffer.
*/
/*******************************************************/
if(strcmp(hstruct->Commit_Lock_Level,"0") == 0)
EXEC SQL SET TRANSACTION ISOLATION LEVEL NONE;
else{
if(strcmp(hstruct->Commit_Lock_Level,"1") == 0)
EXEC SQL SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED, READ
WRITE;
else {
if(strcmp(hstruct->Commit_Lock_Level,"2") == 0)
EXEC SQL SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
else
if(strcmp(hstruct->Commit_Lock_Level,"3") == 0)
EXEC SQL SET TRANSACTION ISOLATION LEVEL ALL;
}
}
/********************************************************/
/* If the employee's commission is greater than maximum */
/* commission, then increase the employee's salary
*/
/* by 1.04 percent and insert into the RAISE table.
*/
/********************************************************/
if (newbuf.comm1 >= commission)
{
EXEC SQL SELECT EMPNO, EMPNAME, SALARY
INTO :rpt1.empno, :rpt1.name, :rpt1.salary
FROM TRGPERF/EMP_ACT
WHERE EMP_ACT.EMPNO=:newbuf.empn ;
if (sqlca.sqlcode == 0) then
{
rpt1.new_salary = salary * percentage;
EXEC SQL INSERT INTO TRGPERF/RAISE VALUES(:rpt1);
}
goto finished;
}
err_exit:
exit(1);
/* All done */
finished:
return;
} /* end of main line
*/
112
/******************************************************************/
/* INCLUDE NAME : MSGHAND1
*/
/*
*/
/* DESCRIPTION : Message handler to signal an exception to
*/
/*
the application to inform that an
*/
/*
error occured in the trigger program.
*/
/*
*/
/* NOTE : This message handler is a user defined routine.
*/
/*
*/
/******************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <recio.h>
#include <leawi.h>
#pragma linkage (QMHSNDPM, OS)
void QMHSNDPM(char *,
void *,
void *,
int,
char *,
char *,
int,
void *,
void *,
...);
/*
/*
/*
/*
/*
/*
/*
/*
/*
/*
Message identifier
*/
Qualified message file name
*/
Message data or text
*/
Length of message data or text */
Message type
*/
Call message queue
*/
Call stack counter
*/
Message key
*/
Error code
*/
Optionals:
length of call message queue
name
Call stack entry qualification
display external messages
screen wait time
*/
/*********************************************************************/
/******** This is the start of the exception handler function.
*/
/*********************************************************************/
void main_handler(_FEEDBACK *cond, _POINTER *token, _INT4 *rc,
_FEEDBACK *new)
{
/****************************************/
/* Initialize variables for call to
*/
/* QMHSNDPM.
*/
/* User must create a message file and */
/* define a message ID to match the
*/
/* following data.
*/
/****************************************/
char
message_id[7] = "TRG9999";
char
message_file[20] = "MSGF
LIB1
";
char
message_data[50] = "Trigger error
" ;
int
message_len = 30;
char
message_type[10] = "*ESCAPE
";
char
message_q[10] = "_C_pep
";
int
pgm_stack_cnt = 1;
char
message_key[4];
113
struct error_code {
int bytes_provided;
int bytes_available;
char message_id[7];
} error_code;
/****************************************/
/* Declare error code structure for
*/
/* QMHSNDPM.
*/
/****************************************/
error_code.bytes_provided = 15;
/****************************************/
/* Set the error handler to resume and */
/* mark the last escape message as
*/
/* handled.
*/
/****************************************/
*rc = CEE_HDLR_RESUME;
/****************************************/
/* Send my own *ESCAPE message.
*/
/****************************************/
QMHSNDPM(message_id,
&message_file,
&message_data,
message_len,
message_type,
message_q,
pgm_stack_cnt,
&message_key,
&error_code );
/****************************************/
/* Check that the call to QMHSNDPM
*/
/* finished correctly.
*/
/****************************************/
if (error_code.bytes_available != 0)
{
printf("Error in QMHOVPM : %s\n", error_code.message_id);
}
}
114
115
v Defines one parameter which is used both as an input parameter and an output
parameter. The parameter is a character field of length ten. Parameters can be
defined to be type IN, OUT, or INOUT. The parameter type determines when
the values for the parameters get passed to and from the procedure.
v Defines the name of the program which corresponds to the procedure, which is
PROC1 in MYLIB. MYLIB.PROC1 is the program which is called when the
procedure is invoked on a CALL statement.
v Indicates that the procedure P1 (program MYLIB.PROC1) is written in C. The
language is important since it impacts the types of parameters that can be
passed. It also affects how the parameters are passed to the procedure (for
example, for ILE C procedures, a NUL-terminator is passed on character,
graphic, date, time, and timestamp parameters).
v Defines the CALL type to be GENERAL WITH NULLS. This indicates that the
parameter for the procedure can possibly contain the NULL value, and therefore
would like an additional argument passed to the procedure on the CALL
statement. The additional argument is an array of N short integers, where N is
the number of parameters that are declared in the CREATE PROCEDURE
statement. In this example, the array contains only one element since there is
only parameter.
It is important to note that it is not necessary to define a procedure in order to call
it. However, if no procedure definition is found, either from a prior CREATE
PROCEDURE or from a DECLARE PROCEDURE in this program, certain
restrictions and assumptions are made when the procedure is invoked on the
CALL statement. For example, the NULL indicator argument cannot be passed. See
Using Embedded CALL Statement Where No Procedure Definition Exists on
page 122 for an example of a CALL statement without a corresponding procedure
definition.
116
a FOR statement
an IF statement
a LOOP statement
a REPEAT statement
a WHILE statement
The following example takes as input the employee number and a rating that was
received on the last evaluation. The procedure uses a CASE statement to determine
the appropriate increase and bonus for the update:
EXEC SQL CREATE PROCEDURE UPDATE_SALARY_2
(IN EMPLOYEE_NUMBER CHAR(6),
IN RATING INT)
LANGUAGE SQL MODIFIES SQL DATA
CASE RATING
WHEN 1
UPDATE CORPDATA.EMPLOYEE
SET SALARY = SALARY * 1.10,
BONUS = 1000
WHERE EMPNO = EMPLOYEE_NUMBER;
WHEN 2
UPDATE CORPDATA.EMPLOYEE
SET SALARY = SALARY * 1.05,
BONUS = 500
WHERE EMPNO = EMPLOYEE_NUMBER;
ELSE
UPDATE CORPDATA.EMPLOYEE
SET SALARY = SALARY * 1.03
BONUS = 0
WHERE EMPNO = EMPLOYEE_NUMBER;
END CASE;
117
118
This handler is invoked if any errors occur, ie, the SQLSTATE class is not 00,
01 or 02. Since indicators are always passed to SQL procedures, the
indicator value for DEPT_SALARY is 1 when the procedure returns. If this
handler is invoked, SQLCODE and SQLSTATE are reinitialized to 0.
If the handler for SQLEXCEPTION is not specified and an error occurs that is
not handled in another handler, execution of the compound statement is
terminated and the error is returned in the SQLCA. Similar to indicators, the
SQLCA is always returned from SQL procedures.
Includes an OPEN, FETCH, and CLOSE of cursor C1. If a CLOSE of the
cursor is not specified, the cursor is closed at the end of the compound
statement since SET RESULT SETS is not specified in the CREATE
PROCEDURE statement.
Includes a WHILE statement which loops until the last record is fetched. For
each row retrieved, the TOTAL_SALARY is incremented and, if the
employees bonus is more than 0, the BONUS_CNT is incremented.
Returns DEPT_SALARY and DEPT_BONUS_CNT as output parameters.
Compound statements can be made atomic so if an error occurs that is not
expected, the statements within the atomic statement are rolled back. When a
procedure that contains an atomic compound statement is called, the transaction
must be at a commit boundary. If the compound statement is successful, the
transaction is committed.
The following example takes as input the department number. It ensures the
EMPLOYEE_BONUS table exists, and inserts the name of all employees in the
department who get a bonus. The procedure returns the total count of all
employees who get a bonus.
EXEC SQL
CREATE PROCEDURE CREATE_BONUS_TABLE
(IN DEPT_NUMBER CHAR(3),
INOUT CNT INT)
LANGUAGE SQL MODIFIES SQL DATA
CS1: BEGIN ATOMIC
DECLARE NAME VARCHAR(30) DEFAULT NULL;
DECLARE CONTINUE HANDLER FOR 42710
SELECT COUNT(*) INTO CNT
FROM DATALIB.EMPLOYEE_BONUS;
DECLARE CONTINUE HANDLER FOR 23505
SET CNT = CNT + 1;
DECLARE UNDO HANDLER FOR SQLEXCEPTION
SET CNT = NULL;
IF DEPT_NUMBER IS NOT NULL THEN
CREATE TABLE DATALIB.EMPLOYEE_BONUS
(FULLNAME VARCHAR(30),
BONUS DECIMAL(10,2))
PRIMARY KEY (FULLNAME);
FOR_1:FOR V1 AS C1 CURSOR FOR
SELECT FIRSTNME, MIDINIT, LASTNAME, BONUS
FROM CORPDATA.EMPLOYEE
WHERE WORKDEPT = CREATE_BONUS_TABLE.DEPT_NUMBER;
IF BONUS > 0 THEN
SET NAME = FIRSTNME || ' ' || MIDINIT || ' '||LASTNAME;
INSERT INTO DATALIB.EMPLOYEE_BONUS
VALUES(CS1.NAME, FOR_1.BONUS);
SET CNT = CNT + 1;
END IF;
END FOR FOR_1;
END IF;
END CS1;
119
You can also use dynamic SQL in an SQL procedure. The following example
creates a table that contains all employees in a specific department. The
department number is passed as input to the procedure and is concatenated to the
table name.
|
|
|
|
|
|
|
|
|
|
120
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
END;
|
|
|
|
Sets variable STMT to the DROP statement, and prepares and executes the
statement.
|
|
Sets variable STMT to the CREATE statement, and prepares and executes the
statement.
Sets variable STMT to the INSERT statement, and prepares and executes the
statement. A parameter marker is specified in the where clause. When the
statement is executed, the variable P_DEPT is passed on the USING clause.
|
|
|
|
|
|
|
|
If the procedure is called passing value D21 for the department, table
DEPT_D21_T is created and the table is initialized with all the employees that are
in department D21.
121
122
v The program to call is determined based on the procedure name specified on the
CALL, and, if necessary, the naming convention.
v The language of the program to call is determined based on information
retrieved from the system about the program.
When the CALL statement is invoked, DB2 SQL for AS/400 attempts to find the
program based on standard SQL naming conventions. For the above example,
assume that the naming option of *SYS (system naming) is used and that a
DFTRDBCOL parameter was not specified on the CRTSQLPLI command. In this
case, the library list is searched for a program named P2. Since the call type is
GENERAL, no additional argument is passed to the program for indicator
variables.
Note: If an indicator variable is specified on the CALL statement and its value is
less than zero when the CALL statement is executed, an error results
because there is no way to pass the indicator to the procedure.
Assuming program P2 is found in the library list, the contents of host variable
HV2 are passed in to the program on the CALL and the argument returned from
P2 is mapped back to the host variable after P2 has completed execution.
123
strncpy(dap->sqldaid,"SQLDA
",8);
dap->sqldabc = bc;
/* bc set in the malloc statement above */
dap->sqln = SQLDA_HV_ENTRIES;
dap->sqld = SQLDA_HV_ENTRIES;
dap->sqlvar[0].sqltype = SHORTINT;
dap->sqlvar[0].sqllen = 2;
dap->sqlvar[0].sqldata = (char*) &col1;
dap->sqlvar[0].sqlname.length = 0;
dap->sqlvar[1].sqltype = NUL_TERM_CHAR;
dap->sqlvar[1].sqllen = 4;
dap->sqlvar[1].sqldata = col2;
...
EXEC SQL CALL P1 USING DESCRIPTOR :*dap;
...
}
It should be noted that the name of the called procedure may also be stored in a
host variable and the host variable used in the CALL statement, instead of the
hard-coded procedure name. For example:
...
main()
{
char proc_name[15];
...
strcpy (proc_name, "MYLIB.P3");
...
EXEC SQL CALL :proc_name ...;
...
}
124
char hv3[10],string[100];
:
strcpy(string,"CALL MYLIB.P3 ('P3 TEST')");
EXEC SQL EXECUTE IMMEDIATE :string;
:
125
that language. A host variable declaration indicates that DB2 SQL for AS/400
supports this data type as a parameter in this language. The declaration indicates
how host variables must be declared to be received and set properly by the
procedure. When calling an SQL procedure, all SQL data types are supported so no
column is provided in the table.
Table 19. Data Types of Parameters
SQL Data Type
C and C++
CL
SMALLINT
short
INTEGER
long
DECIMAL(p,s)
decimal(p,s)
TYPE(*DEC) LEN(p s)
PIC S9(p-s)V9(s)
PACKED-DECIMAL Note:
Precision must not be
greater than 18.
NUMERIC(p,s)
REAL or FLOAT(p)
float
DOUBLE PRECISION or
FLOAT or FLOAT(p)
double
CHARACTER(n)
TYPE(*CHAR) LEN(n)
PIC X(n)
VARCHAR(n)
Varying-Length Character
String (see COBOL chapter)
Note: Only supported for
ILE COBOL for AS/400.
Varying-Length Character
String (see COBOL chapter)
Note: Only supported for
ILE COBOL for AS/400.
GRAPHIC(n)
VARGRAPHIC(n)
VARGRAPHIC structured
form (see C chapter)
Varying-Length Graphic
String (see COBOL chapter)
Note: Only supported for
ILE COBOL for AS/400.
DATE
TYPE(*CHAR) LEN(10)
PIC X(10)
TIME
TYPE(*CHAR) LEN(8)
PIC X(8)
TIMESTAMP
TYPE(*CHAR) LEN(26)
PIC X(26)
Indicator Variable
short
126
FORTRAN
PL/I
REXX
SMALLINT
INTEGER*2
FIXED BIN(15)
INTEGER
INTEGER*4
FIXED BIN(31)
DECIMAL(p,s)
FIXED DEC(p,s)
NUMERIC(p,s)
REAL or FLOAT(p)
REAL*4
FLOAT BIN(p)
DOUBLE PRECISION or
FLOAT or FLOAT(p)
REAL*8
FLOAT BIN(p)
CHARACTER(n)
CHARACTER*n
CHAR(n)
VARCHAR(n)
CHAR(n) VAR
CHAR(n) VAR
GRAPHIC(n)
VARGRAPHIC(n)
DATE
CHARACTER*10
CHAR(10)
TIME
CHARACTER*8
CHAR(8)
TIMESTAMP
CHARACTER*26
CHAR(26)
Indicator Variable
INTEGER*2
FIXED BIN(15)
RPG
ILE RPG
SMALLINT
INTEGER
127
RPG
DECIMAL(p,s)
NUMERIC(p,s)
REAL or FLOAT(p)
DOUBLE PRECISION or
FLOAT or FLOAT(p)
CHARACTER(n)
VARCHAR(n)
GRAPHIC(n)
VARGRAPHIC(n)
DATE
TIME
128
ILE RPG
RPG
ILE RPG
TIMESTAMP
Indicator Variable
129
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Program CRPG
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
D INOUT1
S
7P 2
D INOUT1IND
S
4B 0
D INOUT2
S
7P 2
D INOUT2IND
S
4B 0
C
EVAL
INOUT1 = 1
C
EVAL
INOUT1IND = 0
C
EVAL
INOUT2 = 1
C
EVAL
INOUT2IND = -2
C/EXEC SQL CALL PROC1 (:INOUT1 :INOUT1IND , :INOUT2
C+
:INOUT2IND)
C/END-EXEC
C
EVAL
INOUT1 = 1
C
EVAL
INOUT1IND = 0
C
EVAL
INOUT2 = 1
C
EVAL
INOUT2IND = -2
C/EXEC SQL CALL PROC1 (:INOUT1 :INOUT1IND , :INOUT2
C+
:INOUT2IND)
C/END-EXEC
C
INOUT1IND
IFLT
0
C*
:
C*
HANDLE NULL INDICATOR
C*
:
C
ELSE
C*
:
C*
INOUT1 CONTAINS VALID DATA
C*
:
C
ENDIF
C*
:
C*
HANDLE ALL OTHER PARAMETERS
C*
IN A SIMILAR FASHION
C*
:
C
RETURN
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
End of PROGRAM CRPG
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
130
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Program PROC1
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
D INOUTP
S
7P 2
D INOUTP2
S
7P 2
D NULLARRAY
S
4B 0 DIM(2)
C
*ENTRY
PLIST
C
PARM
INOUTP
C
PARM
INOUTP2
C
PARM
NULLARRAY
C
NULLARRAY(1) IFLT
0
C*
:
C*
INOUTP DOES NOT CONTAIN MEANINGFUL DATA
C*
C
ELSE
C*
:
C*
INOUTP CONTAINS MEANINGFUL DATA
C*
:
C
ENDIF
C*
PROCESS ALL REMAINING VARIABLES
C*
C*
BEFORE RETURNING, SET OUTPUT VALUE FOR FIRST
C*
PARAMETER AND SET THE INDICATOR TO A NON-NEGATIV
C*
VALUE SO THAT THE DATA IS RETURNED TO THE CALLING
C*
PROGRAM
C*
C
EVAL
INOUTP2 = 20.5
C
EVAL
NULLARRAY(2) = 0
C*
C*
INDICATE THAT THE SECOND PARAMETER IS TO CONTAIN
C*
THE NULL VALUE UPON RETURN. THERE IS NO POINT
C*
IN SETTING THE VALUE IN INOUTP SINCE IT WON'T BE
C*
PASSED BACK TO THE CALLER.
C
EVAL
NULLARRAY(1) = -5
C
RETURN
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
End of PROGRAM PROC1
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
131
Examples
These examples show how the arguments of the CALL statement are passed to the
procedure for several languages. They also show how to receive the arguments
into local variables in the procedure.
The first example shows the calling ILE C program that uses the CREATE
PROCEDURE definitions to call the P1 and P2 procedures. Procedure P1 is written
in C and has 10 parameters. Procedure P2 is written in PL/I and also has 10
parameters.
Assume two procedures are defined as follows:
EXEC SQL CREATE PROCEDURE P1 (INOUT PARM1 CHAR(10),
INOUT PARM2 INTEGER,
INOUT PARM3 SMALLINT,
INOUT PARM4 FLOAT(22),
INOUT PARM5 FLOAT(53),
INOUT PARM6 DECIMAL(10,5),
INOUT PARM7 VARCHAR(10),
INOUT PARM8 DATE,
INOUT PARM9 TIME,
INOUT PARM10 TIMESTAMP)
EXTERNAL NAME TEST12.CALLPROC2
LANGUAGE C GENERAL WITH NULLS
EXEC SQL CREATE PROCEDURE P2 (INOUT PARM1 CHAR(10),
INOUT PARM2 INTEGER,
INOUT PARM3 SMALLINT,
INOUT PARM4 FLOAT(22),
INOUT PARM5 FLOAT(53),
INOUT PARM6 DECIMAL(10,5),
INOUT PARM7 VARCHAR(10),
INOUT PARM8 DATE,
INOUT PARM9 TIME,
INOUT PARM10 TIMESTAMP)
EXTERNAL NAME TEST12.CALLPROC
LANGUAGE PLI GENERAL WITH NULLS
132
133
/*******************************************************/
/* Initialize variables for the call to the procedures */
/*******************************************************/
strcpy(PARM1,"PARM1");
PARM2 = 7000;
PARM3 = -1;
PARM4 = 1.2;
PARM5 = 1.0;
PARM6 = 10.555;
PARM7.parm7l = 5;
strcpy(PARM7.parm7c,"PARM7");
strncpy(PARM8,"1994-12-31",10);
/* FOR DATE
*/
strncpy(PARM9,"12.00.00",8);
/* FOR TIME
*/
strncpy(PARM10,"1994-12-31-12.00.00.000000",26);
/* FOR TIMESTAMP */
/***********************************************/
/* Call the C procedure
*/
/*
*/
/*
*/
/***********************************************/
EXEC SQL CALL P1 (:PARM1, :PARM2, :PARM3,
:PARM4, :PARM5, :PARM6,
:PARM7, :PARM8, :PARM9,
:PARM10 );
if (strncmp(SQLSTATE,"00000",5))
{
/* Handle error or warning returned on CALL statement */
}
/* Process return values from the CALL.
:
/***********************************************/
/* Call the PLI procedure
*/
/*
*/
/*
*/
/***********************************************/
/* Reset the host variables prior to making the CALL
/*
:
EXEC SQL CALL P2 (:PARM1, :PARM2, :PARM3,
:PARM4, :PARM5, :PARM6,
:PARM7, :PARM8, :PARM9,
:PARM10 );
if (strncmp(SQLSTATE,"00000",5))
{
/* Handle error or warning returned on CALL statement
}
/* Process return values from the CALL.
:
}
*/
*/
*/
*/
*/
134
*/
*/
*/
*/
*/
*/
135
/**********************************************************/
/* Copy NUL terminated string into local variable.
*/
/* Note that the parameter in the CREATE PROCEDURE was
*/
/* declared as varying length character. For C, varying
*/
/* length are passed as NUL terminated strings unless
*/
/* FOR BIT DATA is specified in the CREATE PROCEDURE
*/
/**********************************************************/
strcpy(parm7,argv[7]);
/**********************************************************/
/* Copy date into local variable.
*/
/* Note that date and time variables are always passed in */
/* ISO format so that the lengths of the strings are
*/
/* known. strcpy would work here just as well.
*/
/**********************************************************/
strncpy(parm8,argv[8],10);
/* Copy time into local variable
strncpy(parm9,argv[9],8);
*/
/**********************************************************/
/* Copy timestamp into local variable.
*/
/* IBM SQL timestamp format is always passed so the length*/
/* of the string is known.
*/
/**********************************************************/
strncpy(parm10,argv[10],26);
/**********************************************************/
/* The indicator array is passed as an array of short
*/
/* integers. There is one entry for each parameter passed */
/* on the CREATE PROCEDURE (10 for this example).
*/
/* Below is one way to set each indicator into separate
*/
/* variables.
*/
/**********************************************************/
ind = (short int *) argv[11];
ind1 = *(ind++);
ind2 = *(ind++);
ind3 = *(ind++);
ind4 = *(ind++);
ind5 = *(ind++);
ind6 = *(ind++);
ind7 = *(ind++);
ind8 = *(ind++);
ind9 = *(ind++);
ind10 = *(ind++);
:
/* Perform any additional processing here
*/
:
return;
}
/******** END OF C PROCEDURE P1 *******************************/
136
The next example shows a REXX procedure called from an ILE C program.
Assume a procedure is defined as follows:
EXEC SQL CREATE PROCEDURE REXXPROC
(IN PARM1 CHARACTER(20),
IN PARM2 INTEGER,
IN PARM3 DECIMAL(10,5),
IN PARM4 DOUBLE PRECISION,
IN PARM5 VARCHAR(10),
IN PARM6 GRAPHIC(4),
IN PARM7 VARGRAPHIC(10),
IN PARM8 DATE,
IN PARM9 TIME,
IN PARM10 TIMESTAMP)
EXTERNAL NAME 'TEST.CALLSRC(CALLREXX)'
LANGUAGE REXX GENERAL WITH NULLS
137
138
/* *************************************************************/
/* Call the procedure - on return from the CALL statement the */
/* SQLCODE should be 0. If the SQLCODE is non-zero,
*/
/* the procedure detected an error.
*/
/* *************************************************************/
strcpy(parm1,"TestingREXX");
parm2 = 12345;
parm3 = 5.5;
parm4 = 3e3;
parm5.dlen = 5;
strcpy(parm5.dat,"parm6");
strcpy(parm8,"1994-01-01");
strcpy(parm9,"13.01.00");
strcpy(parm10,"1994-01-01-13.01.00.000000");
EXEC SQL CALL REXXPROC (:parm1, :parm2,
:parm3,:parm4,
:parm5, :parm6,
:parm7,
:parm8, :parm9,
:parm10);
if (strncpy(SQLSTATE,"00000",5))
{
/* handle error or warning returned on CALL
:
}
:
*/
139
/**********************************************************************/
/****** START OF REXX MEMBER TEST/CALLSRC CALLREXX ********************/
/**********************************************************************/
/* REXX source member TEST/CALLSRC CALLREXX
*/
/* Note the extra parameter being passed for the indicator*/
/* array.
*/
/*
*/
/* ACCEPT THE FOLLOWING INPUT VARIABLES SET TO THE
*/
/* SPECIFIED VALUES :
*/
/* AR1
CHAR(20)
= 'TestingREXX'
*/
/* AR2
INTEGER
= 12345
*/
/* AR3
DECIMAL(10,5)
= 5.5
*/
/* AR4
DOUBLE PRECISION = 3e3
*/
/* AR5
VARCHAR(10)
= 'parm6'
*/
/* AR6
GRAPHIC
= G'C1C1C2C2C3C3'
*/
/* AR7
VARGRAPHIC
=
*/
/*
G'E2E2E3E3E4E4E5E5E6E6E7E7E8E8E9E9EAEA'
*/
/* AR8
DATE
= '1994-01-01'
*/
/* AR9
TIME
= '13.01.00'
*/
/* AR10
TIMESTAMP
=
*/
/*
'1994-01-01-13.01.00.000000'
*/
/* AR11
INDICATOR ARRAY = +0+0+0+0+0+0+0+0+0+0
*/
/**********************************************************/
/* Parse the arguments into individual parameters
*/
/**********************************************************/
parse arg ar1 ar2 ar3 ar4 ar5 ar6 ar7 ar8 ar9 ar10 ar11
/**********************************************************/
/* Verify that the values are as expected
*/
/**********************************************************/
if ar1<>"'TestingREXX'" then signal ar1tag
if ar2<>12345 then signal ar2tag
if ar3<>5.5 then signal ar3tag
if ar4<>3e3 then signal ar4tag
if ar5<>"'parm6'" then signal ar5tag
if ar6 <>"G'AABBCC'" then signal ar6tag
if ar7 <>"G'SSTTUUVVWWXXYYZZAA'" then ,
signal ar7tag
if ar8 <> "'1994-01-01'" then signal ar8tag
if ar9 <> "'13.01.00'" then signal ar9tag
if ar10 <> "'1994-01-01-13.01.00.000000'" then signal ar10tag
if ar11 <> "+0+0+0+0+0+0+0+0+0+0" then signal ar11tag
140
/************************************************************/
/* Perform other processing as necessary ..
*/
/************************************************************/
:
/************************************************************/
/* Indicate the call was successful by exiting with a
*/
/* return code of 0
*/
/************************************************************/
exit(0)
ar1tag:
say "ar1 did not match" ar1
exit(1)
ar2tag:
say "ar2 did not match" ar2
exit(1)
:
:
/************ END OF REXX MEMBER
**********************************/
141
142
Static SQL
Dynamic SQL
ALTER TABLE
CALL
CLOSE
COMMENT ON
COMMIT
143
144
SQL Statement
Static SQL
Dynamic SQL
CONNECT
CREATE ALIAS
CREATE COLLECTION
CREATE INDEX
CREATE PROCEDURE
CREATE SCHEMA
See Note 8.
CREATE TABLE
CREATE VIEW
DECLARE CURSOR
See Note 4.
DECLARE PROCEDURE
DECLARE STATEMENT
DECLARE VARIABLE
DELETE
DESCRIBE
See Note 7.
DESCRIBE TABLE
DISCONNECT
DROP
EXECUTE
See Note 1.
EXECUTE IMMEDIATE
See Note 2.
FETCH
GRANT
INCLUDE
INSERT
LABEL ON
LOCK TABLE
OPEN
PREPARE
See Note 3.
RELEASE
RENAME
REVOKE
ROLLBACK
SELECT INTO
See Note 5.
SELECT statement
See Note 6.
SET CONNECTION
SET OPTION
See Note 9.
Static SQL
Dynamic SQL
SET TRANSACTION
UPDATE
WHENEVER
Notes:
1. Cannot be prepared, but used to run prepared SQL statements. The SQL
statement must be previously prepared by the PREPARE statement prior to
using the EXECUTE statement. See example for PREPARE under Using the
PREPARE and EXECUTE Statements on page 146.
2. Cannot be prepared, but used with dynamic statement strings that do not have
any ? parameter markers. The EXECUTE IMMEDIATE statement causes the
statement strings to be prepared and run dynamically at program run time. See
example for EXECUTE IMMEDIATE under Processing Non-SELECT
statements.
3. Cannot be prepared, but used to parse, optimize, and set up dynamic SELECT
statements prior to running. See example for PREPARE under Processing
Non-SELECT statements.
4. Cannot be prepared, but used to define the cursor for the associated dynamic
SELECT statement prior to running.
5. A SELECT INTO statement cannot be prepared or used in EXECUTE
IMMEDIATE.
6. Cannot be used with EXECUTE or EXECUTE IMMEDIATE but can be prepared
and used with OPEN.
7. Cannot be prepared, but used to return a description of a prepared statement.
8. Can only be run using the Run SQL Statements (RUNSQLSTM) command.
9. Can only be used when running a REXX procedure.
145
1. Verify that the SQL statement you want to build is one that can be run
dynamically (see Table 22 on page 143).
2. Build the SQL statement. (Use Interactive SQL for an easy way to build, verify,
and run your SQL statement. See Chapter 17. Using Interactive SQL for more
information.)
To run a dynamic SQL non-SELECT statement:
1. Run the SQL statement using EXECUTE IMMEDIATE, or PREPARE the SQL
statement, then EXECUTE the prepared statement.
2. Handle any SQL return codes that might result.
The following is an example of an application running a dynamic SQL
non-SELECT statement (stmtstrg):
EXEC SQL
EXECUTE IMMEDIATE :stmtstrg;
146
In routines similar to the example above, you must know the number of parameter
markers and their data types, because the host variables that provide the input
data are declared when the program is being written.
Note: All prepared statements that are associated with an application server are
destroyed whenever the connection to the application server ends.
Connections are ended by a CONNECT (Type 1) statement, a DISCONNECT
statement, or a RELEASE followed by a successful COMMIT.
147
Note: Remember that because the SELECT statement, in this case, always returns
the same number and type of data items as previously run fixed-list SELECT
statements, you do not have to use the SQL descriptor area (SQLDA).
Varying-List Select-Statements
In dynamic SQL, varying-list SELECT statements are ones for which the number
and format of result columns to be returned are not predictable; that is, you do not
know how many variables you need, or what the data types are. Therefore, you
cannot define host variables in advance to accommodate the result columns
returned.
Note: In REXX, steps 5.b on page 149, 6 on page 149, and 7 on page 149 are not
applicable.
If your application accepts varying-list SELECT statements, your program has to:
1. Place the input SQL statement into a host variable.
2. Issue a PREPARE statement to validate the dynamic SQL statement and put it
into a form that can be run. If DLYPRP (*YES) is specified on the CRTSQLxxx
command, the preparation is delayed until the first time the statement is used
in an EXECUTE or DESCRIBE statement, unless the USING clause is specified
on the PREPARE statement.
3. Declare a cursor for the statement name.
4. Open the cursor (declared in step 3) that includes the name of the dynamic
SELECT statement.
5. Issue a DESCRIBE statement to request information from SQL about the type
and size of each column of the result table.
Notes:
a. You can also code the PREPARE statement with an INTO clause to
perform the functions of PREPARE and DESCRIBE with a single statement.
148
b. If the SQLDA is not large enough to contain column descriptions for each
retrieved column, the program must determine how much space is needed,
get storage for that amount of space, build a new SQLDA, and reissue the
DESCRIBE statement.
6. Allocate the amount of storage needed to contain a row of retrieved data.
7. Put storage addresses into the SQLDA (SQL descriptor area) to tell SQL where
to put each item of retrieved data.
8. FETCH a row.
9. When end of data occurs, close the cursor.
10. Handle any SQL return codes that might result.
149
SQLDA Format
The SQLDA consists of four variables followed by an arbitrary number of
occurrences of a sequence of six variables collectively named SQLVAR.
Note: The SQLDA in REXX is different. For more information, see Chapter 15.
Coding SQL Statements in REXX Applications.
When an SQLDA is used in OPEN, FETCH, CALL, and EXECUTE, each occurrence
of SQLVAR describes a host variable.
The variables of SQLDA are as follows (variable names are in lowercase for C):
SQLDAID
SQLDAID is used for storage dumps. It is a string of 8 characters that have
the value 'SQLDA' after the SQLDA that is used in a PREPARE or
DESCRIBE statement. It is not used for FETCH, OPEN, CALL or
EXECUTE.
SQLDAID is not applicable in REXX.
SQLDABC
SQLDABC indicates the length of the SQLDA. It is a 4-byte integer that
has the value SQLN*LENGTH(SQLVAR) + 16 after the SQLDA is used in a
PREPARE or DESCRIBE statement. SQLDABC must have a value equal to
or greater than SQLN*LENGTH(SQLVAR) + 16 prior to use by FETCH,
OPEN, CALL, or EXECUTE.
SQLABC is not applicable in REXX.
SQLN SQLN is a 2-byte integer that specifies the total number of occurrences of
SQLVAR. It must be set prior to use by any SQL statement to a value
greater than or equal to 0.
SQLN is not applicable in REXX.
SQLD SQLD is a 2-byte integer that specifies the pertinent number of occurrences
of SQLVAR; that is, the number of host variables described by the SQLDA.
This field is set by SQL on a DESCRIBE or PREPARE statement. In other
statements, this field must be set prior to use to a value greater than or
equal to 0 and less than or equal to SQLN.
SQLVAR
The variables of SQLVAR are SQLTYPE, SQLLEN, SQLRES, SQLDATA,
SQLIND, and SQLNAME. These variables are set by SQL on a DESCRIBE
or PREPARE statement. In other statements, they must be set prior to use.
These variables are defined as follows:
SQLTYPE
SQLTYPE is a 2-byte integer that specifies the data type of the host
variable as shown in the table below. Odd values for SQLTYPE show that
the host variable has an associated indicator variable addressed by
SQLIND.
SQLLEN
SQLLEN is a 2-byte integer variable that specifies the length attributes of
the host variables shown in Figure 10-2.
150
Table 23. SQLTYPE and SQLLEN Values for PREPARE, DESCRIBE, FETCH, OPEN, CALL, or EXECUTE
For PREPARE and DESCRIBE
SQLLEN
10
Fixed-length character
string representation of a
date
Length attribute
of the host
variable
Time
Fixed-length character
string representation of a
time
Length attribute
of the host
variable
392/393
Timestamp
26
Fixed-length character
string representation of a
timestamp
Length attribute
of the host
variable
400/401
N/A
N/A
NUL-terminated graphic
string
Length attribute
of the host
variable
448/449
Varying-length character
string
Length attribute
of the column
Varying-length character
string
Length attribute
of the host
variable
452/453
Fixed-length character
string
Length attribute
of the column
Fixed-length character
string
Length attribute
of the host
variable
456/457
Long varying-length
character string
Length attribute
of the column
Long varying-length
character string
Length attribute
of the host
variable
460/461
N/A
N/A
NUL-terminated character
string
Length attribute
of the host
variable
464/465
Varying-length graphic
string
Length attribute
of the column
Varying-length graphic
string
Length attribute
of the host
variable
468/469
472/473
Long varying-length
graphic string
Length attribute
of the column
Length attribute
of the host
variable
476/477
N/A
N/A
PASCAL L-string
Length attribute
of the host
variable
480/481
Floating point
4 for single
precision, 8 for
double precision
Floating point
4 for single
precision, 8 for
double precision
484/485
Packed decimal
Precision in byte
1; scale in byte 2
Packed decimal
Precision in byte
1; scale in byte 2
488/489
Zoned decimal
Precision in byte
1; scale in byte 2
Zoned decimal
Precision in byte
1; scale in byte 2
496/497
Large integer
Large integer
SQLTYPE
SQLLEN
384/385
Date
388/389
151
Table 23. SQLTYPE and SQLLEN Values for PREPARE, DESCRIBE, FETCH, OPEN, CALL, or
EXECUTE (continued)
For PREPARE and DESCRIBE
SQLTYPE
SQLLEN
5
500/501
Small integer
504/505
N/A
N/A
SQLLEN
Small integer
Precision in byte
1; scale in byte 2
SQLRES
SQLRES is a 12-byte reserved area for boundary alignment purposes. Note
that, in OS/400, pointers must be on a quad-word boundary.
SQLRES is not applicable in REXX.
SQLDATA
SQLDATA is a 16-byte pointer variable that specifies the address of the
host variables when the SQLDA is used on OPEN, FETCH, CALL, and
EXECUTE.
When the SQLDA is used on PREPARE and DESCRIBE, this area is
overlaid with the following information:
The CCSID of a character, date, time, timestamp, and graphic field is
stored in the third and fourth bytes of SQLDATA. For BIT data, the CCSID
is 65535. In REXX, the CCSID is returned in the variable SQLCCSID.
SQLIND
SQLIND is a 16-byte pointer that specifies the address of a small integer
host variable that is used as an indication of null or not null when the
SQLDA is used on OPEN, FETCH, CALL, and EXECUTE. A negative value
indicates null and a non-negative indicates not null. This pointer is only
used if SQLTYPE contains an odd value.
When the SQLDA is used on PREPARE and DESCRIBE, this area is
reserved for future use.
SQLNAME
SQLNAME is a variable-length character variable with a maximum length
of 30, which contains the name of selected column, label, or system column
name after a PREPARE or DESCRIBE. In OPEN, FETCH, EXECUTE, or
CALL, it can be used to pass the CCSID of character strings. CCSIDs can
be passed for character, graphic, date, time, and timestamp host variables.
The SQLNAME field in an SQLVAR array entry of an input SQLDA can be set to
specify the CCSID:
Data Type
Character
Character
Character
GRAPHIC
Sub-type
SBCS
MIXED
BIT
not applicable
Length of
SQLNAME
8
8
8
8
SQLNAME
Bytes 1 & 2
X0000
X0000
X0000
X0000
SQLNAME
Bytes 3 & 4
CCSID
CCSID
XFFFF
CCSID
5. Binary numbers can be represented in the SQLDA as either lengths 2 or 4, or with the precision in byte 1 and the scale in byte 2.
If the first byte is greater than X00, it indicates precision and scale.
152
Data Type
Any other data
type
Sub-type
not applicable
Length of
SQLNAME
not applicable
SQLNAME
Bytes 1 & 2
not applicable
SQLNAME
Bytes 3 & 4
not applicable
Note: It is important to remember that the SQLNAME field is only for overriding
the CCSID. Applications that use the defaults do not need to pass CCSID
information. If a CCSID is not passed, the default CCSID for the job is used.
The default for graphic host variables is the associated double-byte CCSID for the
job CCSID. If an associated double-byte CCSID does not exist, 65535 is used.
Note: The SELECT statement has no INTO clause. Dynamic SELECT statements
must not have an INTO clause, even if they return only one row.
When the statement is read, it is assigned to a host variable. The host variable (for
example, named DSTRING) is then processed, using the PREPARE statement, as
shown:
EXEC SQL
PREPARE S1 FROM :DSTRING;
Allocating Storage
You can allocate storage for the SQLDA. (Allocating storage is not necessary in
REXX.) The techniques for acquiring storage are language dependent. The SQLDA
must be allocated on a 16-byte boundary. The SQLDA consists of a fixed-length
header, 16 bytes long. The header is followed by a varying-length array section
(SQLVAR), each element of which is 80 bytes in length. The amount of storage you
need to allocate depends on how many elements you want to have in the SQLVAR
array. Each column you select must have a corresponding SQLVAR array element.
Therefore, the number of columns listed in your SELECT statement determines
how many SQLVAR array elements you should allocate. Because SELECT
statements are specified at run time, however, it is impossible to know how many
columns will be accessed. Consequently, you must estimate the number of
columns. Suppose, in this example, that no more than 20 columns are ever
expected to be accessed by a single SELECT statement. This means that the
SQLVAR array should have a dimension of 20 (for an SQLDA size 20 x 80, or 1600,
plus 16 for a total of 1616 bytes), because each item in the select-list must have a
corresponding entry in SQLVAR.
Having allocated what you estimated to be enough space for your SQLDA in the
SQLN field of the SQLDA, set an initial value equal to the number of SQLVAR
array elements. In the following example, set SQLN to 20:
Allocate space for an SQLDA of 1616 bytes on a quadword boundary
SQLN = 20;
153
Note: In PL/I the ALLOCATE statement is the only way to ensure the allocation
of a quadword boundary.
Having allocated storage, you can now issue a DESCRIBE statement.
EXEC SQL
DESCRIBE S1 INTO :SQLDA;
When the DESCRIBE statement is run, SQL places values in the SQLDA that
provide information about the select-list. The following Figure 9 shows the
contents of the SQLDA after the DESCRIBE is run:
SQLDA Size
SQLDA (8 bytes)
453
20 SQLN (2 bytes)
2 SQLD (2 bytes)
(reserved)
3
37
SQLVAR
Element 1
(80 bytes)
0
WORKDEPT
453
(reserved)
37
SQLVAR
Element 2
(80 bytes)
0
7
P H O N E N O
RV3W188-0
Your program might have to alter the SQLN value if the SQLDA is not large
enough to contain the described SQLVAR elements. For example, let the SELECT
statement contain 27 select-list expressions instead of the 20 or less that you
estimated. Because the SQLDA was only allocated with an SQLVAR dimension of
20 elements, SQL cannot describe the select-list, because the SQLVAR has too many
elements. SQL sets the SQLD to the actual number of columns specified by the
SELECT statement, and the remainder of the structure is ignored. Therefore, after a
DESCRIBE, you should compare the SQLN to the SQLD. If the value of SQLD is
greater than the value of SQLN, allocate a larger SQLDA based on the value in
SQLD, as follows:
EXEC SQL
DESCRIBE S1 INTO :SQLDA;
IF SQLN <= SQLD THEN
DO;
/*Allocate a larger SQLDA using the value of SQLD.*/
/*Reset SQLN to the larger value.*/
154
EXEC SQL
DESCRIBE S1 INTO :SQLDA;
END;
If you use DESCRIBE on a non SELECT statement, SQL sets SQLD to 0. Therefore,
if your program is designed to process both SELECT and non SELECT statements,
you can describe each statement (after it is prepared) to determine whether it is a
SELECT statement. This sample routine is designed to process only SELECT
statements; the SQLD is not checked.
Your program must now analyze the elements of SQLVAR. Remember that each
element describes a single select-list expression. Consider again the SELECT
statement that is being processed:
SELECT WORKDEPT, PHONENO
FROM CORPDATA.EMPLOYEE
WHERE LASTNAME = 'PARKER'
The first item in the select-list is WORKDEPT. At the beginning of this section, we
identified that each SQLVAR element contains the fields SQLTYPE, SQLLEN,
SQLRES, SQLDATA, SQLIND, and SQLNAME. SQL returns, in the SQLTYPE field,
a code that describes the data type of the expressions and whether nulls are
applicable or not.
For example, SQL sets SQLTYPE to 453 in SQLVAR element 1 (see Figure 9 on
page 154 ). This specifies that WORKDEPT is a fixed-length character string
(CHAR) column and that nulls are permitted in the column.
SQL sets SQLLEN to the length of the column. Because the data type of
WORKDEPT is CHAR, SQL sets SQLLEN equal to the length of the character
string. For WORKDEPT, that length is 3. Therefore, when the SELECT statement is
later run, a storage area large enough to hold a CHAR(3) string is needed.
Because the data type of WORKDEPT is CHAR FOR SBCS DATA, the first 4 bytes
of SQLDATA were set to the CCSID of the character column (see Figure 9 on
page 154 ). The last field in an SQLVAR element is a varying-length character
string called SQLNAME. The first 2 bytes of SQLNAME contain the length of the
character data. The character data itself is usually the name of a column used in
the SELECT statement (WORKDEPT in the above example.) The exceptions to this
are select-list items that are unnamed, such as functions (for example,
SUM(SALARY)), expressions (for example, A+BC), and constants. In these cases,
SQLNAME is an empty string. SQLNAME can also contain a label rather than a
name. One of the parameters associated with the PREPARE and DESCRIBE
statements is the USING clause. You can specify it this way:
EXEC SQL
DESCRIBE S1 INTO:SQLDA
USING LABELS;
If you specify NAMES (or omit the USING parameter entirely), only column
names are placed in the SQLNAME field. If you specify SYSTEM NAMES, only the
system column names are placed in the SQLNAME field. If you specify LABELS,
only labels associated with the columns listed in your SQL statement are entered
here. If you specify ANY, labels are placed in the SQLNAME field for those
columns that have labels; otherwise, the column names are entered. If you specify
BOTH, names and labels are both placed in the field with their corresponding
lengths. If you specify BOTH, however, you must remember to double the size of
the SQLVAR array because you are including twice the number of elements. If you
Chapter 8. Dynamic SQL Applications
155
specify ALL, column names, labels, and system column names are placed in the
field with their corresponding lengths. If you specify ALL, remember to triple the
size of the SQLVAR array. If you specify ALL:
v Names, and labels are placed in the field with their corresponding lengths.
v The size of the SQLVAR array must triple because you are including the number
of elements.
For more information on the USING option and on column labels, see the DB2 for
AS/400 SQL Reference book.
In the example, the second SQLVAR element contains the information for the
second column used in the select: PHONENO. The 453 code in SQLTYPE specifies
that PHONENO is a CHAR column. For a CHAR data type of length 4, SQL sets
SQLLEN to 4.
After analyzing the result of the DESCRIBE, you can allocate storage for variables
containing the result of the SELECT statement. For WORKDEPT, a character field
of length 3 must be allocated; for PHONENO, a character field of length 4 must be
allocated.
After the storage is allocated, you must set SQLDATA and SQLIND to point to the
appropriate areas. For each element of the SQLVAR array, SQLDATA points to the
place where the results are to be put. SQLIND points to the place where the null
indicator is to be put. The following figure shows what the structure looks like
now:
SQLDA Size
S
453
1616
20
FLDA: (CHAR(3))
(reserved)
Address of FLDA
SQLVAR
Element 1
(80 bytes)
Address of FLDAI
8
453
SQLVAR
Element 2
(80 bytes)
FLDB: (CHAR(4))
WORKDEPT
(reserved)
Address of FLDB
Indicator
Variables: (halfword)
FLDAI:
FLDBI:
Address of FLDBI
7
P H O N E N O
RV3W189-0
156
Using a Cursor
You are now ready to retrieve the SELECT statements results. Dynamically defined
SELECT statements must not have an INTO statement. Therefore, all dynamically
defined SELECT statements must use a cursor. Special forms of the DECLARE,
OPEN, and FETCH are used for dynamically defined SELECT statements.
The DECLARE statement for the example statement is:
EXEC SQL DECLARE C1 CURSOR FOR S1;
As you can see, the only difference is that the name of the prepared SELECT
statement (S1) is used instead of the SELECT statement itself. The actual retrieval
of result rows is made as follows:
EXEC SQL
OPEN C1;
EXEC SQL
FETCH C1 USING DESCRIPTOR :SQLDA;
DO WHILE (SQLCODE = 0);
/*Display ... the results pointed to by SQLDATA*/
END;
/*Display ('END OF LIST')*/
EXEC SQL
CLOSE C1;
The cursor is opened, and the result table is evaluated. Notice that there are no
input host variables needed for the example SELECT statement. The SELECT result
rows are then returned using FETCH. On the FETCH statement, there is no list of
output host variables. Rather, the FETCH statement tells SQL to return results into
areas described by the descriptor called SQLDA. The same SQLDA that was set up
by DESCRIBE is now being used for the output of the SELECT statement. In
particular, the results are returned into the storage areas pointed to by the
SQLDATA and SQLIND fields of the SQLVAR elements. The following figure
shows what the structure looks like after the FETCH statement has been processed.
157
SQLDA Size
S
453
1616
20
(reserved)
FLDA: (CHAR(3))
E11
Address of FLDA
SQLVAR
Element 1
(80 bytes)
Address of FLDAI
8
WORKDEPT
453
SQLVAR
Element 2
(80 bytes)
FLDB: (CHAR(4))
4502
(reserved)
Address of FLDB
Address of FLDBI
7
Indicator
Variables: (halfword)
FLDAI:
FLDBI:
0
P H O N E N O
RV3W190-0
The meaning of the SMALLINT pointed to by SQLIND is the same as any other
indicator variable:
0
<0
>0
Note: Unless HOLD is specified, dynamic cursors are closed during COMMIT or
ROLLBACK.
If you want to run the same SELECT statement several times, using different
values for LASTNAME, you can use an SQL statement such as PREPARE or
EXECUTE (as described in Using the PREPARE and EXECUTE Statements on
page 146) like this:
SELECT WORKDEPT, PHONENO FROM CORPDATA.EMPLOYEE WHERE LASTNAME = ?
When your parameters are not predictable, your application cannot know the
number or types of the parameters until run time. You can arrange to receive this
information at the time your application is run, and by using a USING
DESCRIPTOR on the OPEN statement, you can substitute the values contained in
specific host variables for the parameter markers included in the WHERE clause of
the SELECT statement.
To code such a program, you need to use the OPEN statement with the USING
DESCRIPTOR clause. This SQL statement is used to not only open a cursor, but to
replace each parameter marker with the value of the corresponding host variable.
The descriptor name that you specify with this statement must identify an SQLDA
that contains a valid description of those host variables. This SQLDA, unlike those
158
previously described, is not used to return information on data items that are part
of a SELECT list. That is, it is not used as output from a DESCRIBE statement, but
as input to the OPEN statement. It provides information on host variables that are
used to replace parameter markers in the WHERE clause of the SELECT statement.
It gets this information from the application, which must be designed to place
appropriate values into the necessary fields of the SQLDA. The SQLDA is then
ready to be used as a source of information for SQL in the process of replacing
parameter markers with host variable data.
When you use the SQLDA for input to the OPEN statement with the USING
DESCRIPTOR clause, not all of its fields have to be filled in. Specifically,
SQLDAID, SQLRES, and SQLNAME can be left blank (SQLNAME (SQLCCSID in
REXX) can be set if a specific CCSID is needed.) Therefore, when you use this
method for replacing parameter markers with host variable values, you need to
determine:
v How many ? parameter markers are there?
v What are the data types and attributes of these parameters markers (SQLTYPE,
SQLLEN, and SQLNAME)?
v Do you want an indicator variable?
In addition, if the routine is to handle both SELECT and non SELECT statements,
you may want to determine what category of statement it is. (Alternatively, you
can write code to look for the SELECT keyword.)
If your application uses parameter markers, your program has to:
1. Read a statement into the DSTRING varying-length character string host
variable.
2. Determine the number of ? parameter markers.
3. Allocate an SQLDA of that size.
This is not applicable in REXX.
4. Set SQLN and SQLD to the number of ? parameter markers.
SQLN is not applicable in REXX.
5. Set SQLDABC equal to SQLN*LENGTH(SQLVAR) + 16.
This is not applicable in REXX.
6. For each ? parameter marker:
a. Determine the data types, lengths, and indicators.
b. Set SQLTYPE and SQLLEN.
c. Allocate storage to hold the input values (the ? values).
d. Set these values.
e. Set SQLDATA and SQLIND (if applicable) for each ? parameter marker.
f. If character variables are used, and they are in a CCSID other than the job
default CCSID, set SQLNAME (SQLCCSID in REXX) accordingly.
g. If graphic variables are used and they have a CCSID other than the
associated DBCS CCSID for the job CCSID, set the SQLNAME (SQLCCSID
in REXX) to that CCSID.
h. Issue the OPEN statement with a USING DESCRIPTOR clause to open your
cursor and substitute a host variable value for each of the parameter
markers.
The statement can then be processed normally.
159
160
2. As a receiving area for column values (named in an INTO clause): You can
use a host variable to specify a program data area that is to contain the column
values of a retrieved row. The INTO clause names one or more host variables
that you want to contain column values returned by SQL. For example,
suppose you are retrieving the EMPNO, LASTNAME, and WORKDEPT column
161
values from rows in the CORPDATA.EMPLOYEE table. You could define a host
variable in your program to hold each column, then name the host variables
with an INTO clause. For example:
EXEC SQL
SELECT EMPNO, LASTNAME, WORKDEPT
INTO :CBLEMPNO, :CBLNAME, :CBLDEPT
FROM CORPDATA.EMPLOYEE
WHERE EMPNO = :EMPID
END-EXEC.
In this example, the host variable CBLEMPNO receives the value from
EMPNO, CBLNAME receives the value from LASTNAME, and CBLDEPT
receives the value from WORKDEPT.
3. As a value in a SELECT clause: When specifying a list of items in the SELECT
clause, you are not restricted to the column names of tables and views. Your
program can return a set of column values intermixed with host variable values
and literal constants. For example:
MOVE '000220' TO PERSON.
EXEC SQL
SELECT "A", LASTNAME, SALARY, :RAISE,
SALARY + :RAISE
INTO :PROCESS, :PERSON-NAME, :EMP-SAL,
:EMP-RAISE, :EMP-TTL
FROM CORPDATA.EMPLOYEE
WHERE EMPNO = :PERSON
END-EXEC.
PERSON-NAME
EMP-SAL
EMPRAISE
EMP-TTL
LUTZ
29840
4476
34316
Assignment Rules
SQL column values are set to (or assigned to) host variables during the running of
FETCH and SELECT INTO statements. SQL column values are set from (or
assigned from) host variables during the running of INSERT, UPDATE, and CALL
statements. All assignment operations observe the following rules:
v Numbers and strings are not compatible:
Numbers cannot be assigned to string columns or string host variables.
Strings cannot be assigned to numeric columns or numeric host variables.
v All character and DBCS graphic strings are compatible with UCS-2 graphic
columns if conversion is supported between the CCSIDs. All graphic strings are
compatible if the CCSIDs are compatible. All numeric values are compatible.
Conversions are performed by SQL whenever necessary. All character and DBCS
graphic strings are compatible with UCS-2 graphic columns for assignment
162
6. A DBCS-open or DBCS-either column or variable is a variable that was declared in the host language by including the definition
of an externally described file. DBCS-open variables are also declared if the job CCSID indicates MIXED data, or the DECLARE
VARIABLE statement is used and a MIXED CCSID or the FOR MIXED DATA clause is specified. See DECLARE VARIABLE in the
DB2 for AS/400 SQL Reference book.
Chapter 9. Common Concepts and Rules for Using SQL with Host Languages
163
164
Indicator Variables
An indicator variable is a halfword integer variable used to indicate whether its
associated host variable has been assigned a null value:
v If the value for the result column is null, SQL puts a -1 in the indicator variable.
v If you do not use an indicator variable and the result column is a null value, a
negative SQLCODE is returned.
v If the value for the result column causes a data mapping error. SQL sets the
indicator variable to 2.
You can also use an indicator variable to verify that a retrieved string value has
not been truncated. If truncation occurs, the indicator variable contains a positive
integer that specifies the original length of the string.
When the database manager returns a value from a result column, you can test the
indicator variable. If the value of the indicator variable is less than zero, you know
the value of the results column is null. When the database manager returns a null
value, the host variable will be set to the default value for the result column.
Chapter 9. Common Concepts and Rules for Using SQL with Host Languages
165
You specify an indicator variable (preceded by a colon) immediately after the host
variable or immediately after the keyword INDICATOR. For example:
EXEC SQL
SELECT COUNT(*), AVG(SALARY)
INTO :PLICNT, :PLISAL:INDNULL
FROM CORPDATA.EMPLOYEE
WHERE EDLEVEL < 18
END-EXEC.
You can then test INDNULL to see if it contains a negative value. If it does, you
know SQL returned a null value.
Always test for NULL in a column by using the IS NULL predicate. For example:
WHERE expression IS NULL
The EQUAL predicate will always be evaluated as false when it compares a null
value. The result of this example will select no rows.
SAL-REC.
10 MIN-SAL
PIC S9(6)V99 USAGE COMP-3.
10 AVG-SAL
PIC S9(6)V99 USAGE COMP-3.
10 MAX-SAL
PIC S9(6)V99 USAGE COMP-3.
01 SALTABLE.
02 SALIND
PIC S9999 USAGE COMP-4 OCCURS 3 TIMES.
01 EDUC-LEVEL
PIC S9999 COMP-4.
...
MOVE 20 TO EDUC-LEVEL.
...
EXEC SQL
SELECT MIN(SALARY), AVG(SALARY), MAX(SALARY)
INTO :SAL-REC:SALIND
FROM CORPDATA.EMPLOYEE
WHERE EDLEVEL>:EDUC-LEVEL
END-EXEC.
166
When NEWPHONE contains other than a null value, set PHONEIND to zero by
preceding the statement with:
MOVE 0 to PHONEIND.
Otherwise, to tell SQL that NEWPHONE contains a null value, set PHONEIND to
a negative value, as follows:
MOVE -1 TO PHONEIND.
Chapter 9. Common Concepts and Rules for Using SQL with Host Languages
167
Return code.
SQLSTATE
Return code.
SQLERRD(3)
SQLWARN0
For more information about the SQLCA, see Appendix B, SQL Communication
Area in the DB2 for AS/400 SQL Reference book. For a listing of DB2 for AS/400
SQLCODEs and SQLSTATEs, see Appendix B..
SQLERROR
168
GO TO label
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.
Chapter 9. Common Concepts and Rules for Using SQL with Host Languages
169
170
This chapter describes the unique application and coding requirements for
embedding SQL statements in a C or C++ program. C program refers to ILE C for
AS/400 programs. C++ program refers to ILE C++ programs or programs that are
created with the VisualAge C++ for AS/400 compiler. This chapter also defines the
requirements for host structures and host variables.
A detailed sample C program, showing how SQL statements can be used, is
provided in Appendix C. Sample Programs Using DB2 for AS/400 Statements.
A C or C++ program that contains SQL statements must include one or both of the
following:
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 executed. 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 either directly or by using the
SQL INCLUDE statement. Using the SQL INCLUDE statement requests the
inclusion of a standard declaration:
EXEC SQL INCLUDE SQLCA ;
A standard declaration includes both a structure definition and a static data area
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:
#ifndef SQLCODE
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]
Copyright IBM Corp. 1997, 1998
171
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.
For more information on SQLCA, see Appendix B, SQL Communication Area in
the DB2 for AS/400 SQL Reference book.
|
|
|
|
|
|
A standard declaration includes only a structure definition with the name sqlda.
C and C++ declarations that are included for the SQLDA are:
#ifndef SQLDASIZE
struct sqlda {
unsigned char sqldaid[8];
long sqldabc;
short sqln;
short sqld;
struct sqlvar {
short sqltype;
short sqllen;
unsigned char *sqldata;
|
|
|
|
|
|
|
|
|
|
172
|
|
|
|
|
|
|
|
|
short *sqlind;
struct sqlname {
short length;
unsigned char data[30];
} sqlname;
} sqlvar[1];
};
#define SQLDASIZE(n) (sizeof(struct sqlda) + (n-1)* sizeof(struct sqlvar))
#endif
One benefit from using the INCLUDE SQLDA SQL statement is that you also get
the following macro definition:
#define SQLDASIZE(n) (sizeof(struct sqlda) + (n-1)* sizeof(struc sqlvar))
This macro makes it easy to allocate storage for an SQLDA with a specified
number of SQLVAR elements. In the following example, the SQLDASIZE macro is
used to allocate storage for an SQLDA with 20 SQLVAR elements.
#include <stdlib.h>
EXEC SQL INCLUDE SQLDA;
struct sqlda *mydaptr;
short numvars = 20;
.
.
mydaptr = (struct sqlda *) malloc(SQLDASIZE(numvars));
mydaptr->sqln = 20;
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;
An SQL statement can be placed wherever a C or C++ statement that can be run
can be placed.
173
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 ;
|
|
|
|
Comments
In addition to using SQL comments (--), you can include C comments (/*...*/)
within embedded SQL statements whenever a blank is allowed, except between the
keywords EXEC and SQL. Comments can span any number of lines. You cannot
nest comments. You can use single-line comments (comments that start with //) in
C++, but you cannot use them in C.
|
|
|
|
v If you are not using the default margins of 1 and 80, it is possible to place the
shift characters outside of the margins. For this example, assume the margins are
5 and 75. This SQL statement has a valid graphic constant of
G<AABBCCDDEEFFGGHHIIJJKK>.
*...(....1....+....2....+....3....+....4....+....5....+....6....+....7....)....8
EXEC SQL SELECT * FROM GRAPHTAB
WHERE GRAPHCOL = G'<AABBCCDD>
<EEFFGGHHIIJJKK>';
Including Code
You can include SQL statements, C, or C++ statements by embedding the
following SQL statement in the source code:
|
|
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.
174
Margins
|
|
|
|
|
You must code SQL statements within the margins that are specified by the
MARGINS parameter on the CRTSQLCI, CRTSQLCPPI, or CVTSQLCPP command.
If EXEC SQL does not start within the specified margins, the SQL precompiler does
not recognize the SQL statement. For more information about CRTSQLCI,
CRTSQLCPPI, and CVTSQLCPP, see Appendix D. DB2 for AS/400 CL Command
Descriptions.
Names
|
You can use any valid C or C++ variable name for a host variable. It is subject to
the following restrictions:
Do not use host variable names or external entry names that begin with 'SQL',
'RDI', or 'DSN' in any combination of uppercase or lowercase letters. These names
are reserved for the database manager. The length of host variable names is limited
to 64.
C, C++, and SQL use the word null, but for different meanings. The C and C++
languages have a null character (NUL), a null pointer (NULL), and a null
statement (just a semicolon). The C NUL is a single character that compares equal
to 0. The C NULL is a special reserved pointer value that does not point to any
valid data object. The SQL null value is a special value that is distinct from all
nonnull values and denotes the absence of a (non-null) value.
Statement Labels
Executable SQL statements can be preceded with a label.
Preprocessor Sequence
|
You must run the SQL preprocessor before the C or C++ preprocessor. You cannot
use C or C++ preprocessor directives within SQL statements.
Trigraphs
|
|
|
|
|
|
|
|
|
|
Some characters from the C and C++ character set are not available on all
keyboards. You can enter these characters into a C or C++ source program by
using a sequence of three characters that is called a trigraph. The following trigraph
sequences are supported within host variable declarations:
v ??( left bracket
v
v
v
v
v
175
WHENEVER Statement
The target for the GOTO clause in an SQL WHENEVER statement must be within
the scope of any SQL statements affected by the WHENEVER statement.
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.
|
|
|
|
In C++, the C++ statements that are used to define the host variables must be
preceded by a BEGIN DECLARE SECTION statement and followed by an END
DECLARE SECTION statement. You cannot use any variable that is not between
the BEGIN DECLARE SECTION statement and the END DECLARE SECTION
statement as a host variable.
All host variables within an SQL statement must be preceded by a colon (:).
The names of host variables must be unique within the program, even if the host
variables are in different blocks or procedures.
An SQL statement that uses a host variable must be within the scope of the
statement in which the variable was declared.
Host variables cannot be union elements.
176
Numeric
auto
extern
static
const
volatile
float
double
decimal ( precision
)
, scale
signed
long
short
int
,
variable-name
;
=
expression
Notes:
1. Precision and scale must be integer constants. Precision may be in the range
from 1 to 31. 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.
177
Single-Character Form
char
auto
extern
static
const
volatile
unsigned
signed
,
variable-name
;
[
1 ]
expression
char
auto
extern
static
const
volatile
unsigned
signed
,
variable-name [ length ]
;
=
expression
Notes:
1. The length must be an integer constant that is greater than 1 and not greater
than 32741.
2. If the *CNULRQD option is specified on the CRTSQLCI, CRTSQLCPPI, or
CVTSQLCPP 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 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:
|
|
|
|
|
|
178
|
|
|
|
|
|
|
|
struct
auto
extern
static
const
volatile
short
signed
_Packed
var-1 ;
int
tag
char var-2 [
length ]
unsigned
signed
,
variable-name
;
=
expression ,
expression }
Notes:
1. length must be an integer constant that is greater than 0 and not greater than
32740.
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.
Example:
EXEC SQL BEGIN DECLARE SECTION;
/* valid declaration of host variable vstring */
struct VARCHAR {
short len;
char s[10];
} vstring;
179
Single-Graphic Form
wchar_t
auto
extern
static
const
volatile
,
variable-name
;
=
expression
wchar_t
auto
extern
static
const
volatile
,
variable-name [ length ]
;
=
expression
Notes:
1. length must be an integer constant that is greater than 1 and not greater than
16371.
2. If the *CNULRQD option is specified on the CRTSQLCI, CRTSQLCPPI, or
CVTSQLCPP 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:
|
|
|
|
|
|
|
|
|
180
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
SQLWARN1 is set to W
struct
auto
extern
static
const
volatile
short
signed
_Packed
var-1 ;
tag
int
,
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.
Example:
EXEC SQL BEGIN DECLARE SECTION;
/* valid declaration of host variable graphic string */
181
struct VARGRAPH {
short len;
wchar_t s[10];
} vstring;
/* invalid declaration of host variable wstring */
struct VARGRAPH wstring;
In C and C++ programs, you can define a host structure, which is a named set of
elementary C or C++ variables. Host structures have a maximum of two levels,
even though the host structure might itself occur within a multilevel structure. An
exception is the declaration of a varying-length string, which requires another
structure.
|
|
A host structure name can be a group name whose subordinate levels name
elementary C or C++ variables. For example:
struct {
|
|
|
|
|
|
struct {
} a_st;
char c1;
char c2;
} b_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, a_st could not be used as a host variable or referred to in an SQL
statement. A host structure for SQL data has two levels and can be thought of as a
named set of host variables. After the host structure is defined, you can refer to it
in an SQL statement instead of listing the several host variables (that is, the names
of the host variables that make up the host structure).
For example, you can retrieve all column values from selected rows of the table
CORPDATA.EMPLOYEE with:
struct { char empno[7];
struct
char midint,
struct
.....
strcpy("000220",pemp1.empno);
.....
exec sql
182
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.
183
Host Structures
struct
auto
extern
static
_Packed
const
volatile
tag
float
double
decimal ( precision
)
,
long
signed
short
varchar-structure
vargraphic-structure
,
char
var-1
scale
int
var-2
signed
unsigned
[ length ]
,
wchar_t
var-5
;
[
length ]
,
variable-name
;
=
expression
varchar-structure
struct
{
tag
char
var-4
short
signed
length ]
var-3
int
signed
unsigned
vargraphic-structure
struct
{
tag
var-6
short
signed
wchar_t var-7 [
length ]
Note:
184
int
short
auto
extern
static
const
volatile
signed
int
,
variable-name [
dimension ]
;
=
expression
185
v c1_var and c2_var are not valid host variables in any SQL statement.
v A structure cannot contain an intermediate level structure.
For example, 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;
...
186
_Packed
auto
extern
static
struct
tag
const
volatile
var-1
float
double
decimal ( precision
)
,
long
signed
short
varchar-structure
vargraphic-structure
,
char
scale
int
var-2
signed
unsigned
[ length ]
,
wchar_t
var-5
;
[
length ]
,
variable-name [ dimension ]
;
=
expression
varchar-structure
_Packed
struct
short
tag
char
var-4 [
signed
length ]
var-3
int
signed
unsigned
vargraphic-structure
_Packed
struct
{
tag
wchar_t
var-7 [ length ]
short
signed
;
var-6
int
187
Notes:
1. For details on declaring numeric, character, and graphic host variables, see the
notes under numeric-host variables, character-host, and graphic-host variables.
2. The struct tag can be used to define other data areas, but these cannot be used
as host variables.
3. Dimension must be an integer constant between 1 and 32767.
struct
auto
extern
static
_Packed
const
volatile
short
signed
var-1
tag
[ dimension-1 ]
int
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
32767.
188
/*
/*
/*
/*
/*
/*
Ptr
Ptr
Ptr
Ptr
Ptr
to an integer
to a ptr to a long integer
to a single character
to a char array of 20 bytes
to a variable char array of 30
bytes.
*/
*/
*/
*/
*/
*/
*/
*/
v When a host variable is referenced within an SQL statement, that host variable
must be referenced exactly as declared, with the exception of pointers to
NUL-terminated character arrays. For example, the following declaration
required parentheses:
char (*mychara)[20];
*/
However, the parentheses are not allowed when the host variable is referenced
in an SQL statement, such as a SELECT:
EXEC SQL SELECT name INTO :*mychara FROM mytable;
v Only the asterisk can be used as an operator over a host variable name.
v The maximum length of a host variable name is affected by the number of
asterisks specified, as these asterisks are considered part of the name.
v Pointers to structures are not usable as host variables except for variable
character structures. Also, pointer fields in structures are not usable as host
variables.
v SQL requires that all specified storage for based host variables be allocated. If
the storage is not allocated, unpredictable results can occur.
Include name
Externally described file name
Format name or a list of format names
Options
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 can not be specified. Unions declared using the typedef union created by the
#pragma mapinc and #include directive cannot be used as host variables in SQL
Chapter 10. Coding SQL Statements in C and C++ Applications
189
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
Appendix A. DB2 for AS/400 Sample Tables, you can code the following:
#pragma mapinc ("dept","CORPDATA/DEPARTMENT(*ALL)","both")
#include "dept"
CORPDATA_DEPARTMENT_DEPARTMENT_both_t Dept_Structure;
190
SQLTYPE of Host
Variable
SQLLEN of Host
Variable
short int
500
SMALLINT
long int
496
INTEGER
decimal(p,s)
484
p in byte 1, s in byte
2
DECIMAL (p,s)
float
480
FLOAT (single
precision)
double
480
FLOAT (double
precision)
single-character form
452
CHAR(1)
NUL-terminated
character form
460
length
VARCHAR (length 1)
length
VARCHAR (length)
Table 24. C or C++ Declarations Mapped to Typical SQL Data Types (continued)
SQLTYPE of Host
Variable
SQLLEN of Host
Variable
VARCHAR structure
form where length >
254
456
length
VARCHAR(length)
single-graphic form
468
GRAPHIC(1)
NUL-terminated
single-graphic form
400
length
VARGRAPHIC
(length - 1)
VARGRAPHIC
structured form
where length < 128
464
length
VARGRAPHIC
(length)
VARGRAPHIC
structured form
where length > 127
472
length
VARGRAPHIC
(length)
You can use the following table to determine the C or C++ data type that is
equivalent to a given SQL data type.
Table 25. SQL Data Types Mapped to Typical C or C++ Declarations
SQL Data Type
Notes
SMALLINT
short int
INTEGER
long int
DECIMAL(p,s)
decimal(p,s)
NUMERIC(p,s) or nonzero
scale binary
No exact equivalent
Use decimal(p,s).
float
double
CHAR(1)
single-character form
CHAR(n)
No exact equivalent
VARCHAR(n)
NUL-terminated character
form
single-graphic form
GRAPHIC (n)
No exact equivalent
191
Table 25. SQL Data Types Mapped to Typical C or C++ Declarations (continued)
SQL Data Type
Notes
VARGRAPHIC(n)
NUL-terminated graphic
form
DATE
TIME
192
VARGRAPHIC structured
form
NUL-terminated character
form
NUL-terminated character
form
Table 25. SQL Data Types Mapped to Typical C or C++ Declarations (continued)
SQL Data Type
Notes
TIMESTAMP
NUL-terminated character
form
Apostrophes and quotation marks have different meanings in C, C++, and SQL. C
and C++ use quotation marks to delimit string constants and apostrophes to
delimit character constants. SQL does not have this distinction, but uses quotation
marks for delimited identifiers and uses apostrophes to delimit character string
constants. Character data in SQL is distinct from integer data.
193
194
The SQLCODE, SQLSTATE, and SQLCA variable declarations must appear in the
WORKING-STORAGE SECTION or LINKAGE SECTION of your program and can
be placed wherever a record description entry can be specified in those sections.
When you use the INCLUDE statement, the SQL COBOL precompiler includes
COBOL source statements for the SQLCA:
01 SQLCA.
05 SQLCAID
05 SQLCABC
05 SQLCODE
05 SQLERRM.
49 SQLERRML
49 SQLERRMC
05 SQLERRP
05 SQLERRD
05 SQLWARN.
10 SQLWARN0
10 SQLWARN1
10 SQLWARN2
10 SQLWARN3
10 SQLWARN4
10 SQLWARN5
Copyright IBM Corp. 1997, 1998
PIC X(8).
PIC S9(9) BINARY.
PIC S9(9) BINARY.
PIC S9(4) BINARY.
PIC X(70).
PIC X(8).
OCCURS 6 TIMES
PIC S9(9) BINARY.
PIC
PIC
PIC
PIC
PIC
PIC
X.
X.
X.
X.
X.
X.
195
10 SQLWARN6
10 SQLWARN7
10 SQLWARN8
10 SQLWARN9
10 SQLWARNA
05 SQLSTATE
PIC
PIC
PIC
PIC
PIC
PIC
X.
X.
X.
X.
X.
X(5).
For ILE COBOL for AS/400, the SQLCA is declared using the GLOBAL clause.
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.
For more information on SQLCA, see Appendix B, SQL Communication Area in
the DB2 for AS/400 SQL Reference book.
196
description entry can be specified in those sections. For ILE COBOL for AS/400,
the SQLDA is declared using the GLOBAL clause.
Dynamic SQL is an advanced programming technique described in Chapter 8.
Dynamic SQL Applications. 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.
For more information, refer to the DB2 for AS/400 SQL Reference book.
Program Section
WORKING-STORAGE SECTION or
LINKAGE SECTION
WORKING-STORAGE SECTION or
LINKAGE SECTION
INCLUDE member-name
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:
An UPDATE statement coded in a COBOL program might be coded as follows:
EXEC SQL
UPDATE DEPARTMENT
SET MGRNO = :MGR-NUM
WHERE DEPTNO = :INT-DEPT
END-EXEC.
Comments
In addition to SQL comments (--), you can include COBOL comment lines (* or /
in column 7) within embedded SQL statements except between the keywords
EXEC and SQL. COBOL debugging lines (D in column 7) are treated as comment
lines by the precompiler.
197
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.
*...+....1....+....2....+....3....+....4....+....5....+....6....+....7....+....8
EXEC SQL
SELECT * FROM GRAPHTAB
WHERE GRAPHCOL = G'<AABB>
'<CCDDEEFFGGHHIIJJKK>'
END-EXEC.
Including Code
SQL statements or COBOL host variable declaration statements can be included by
embedding the following SQL statement at the point in the source code where the
statements are to be embedded:
EXEC SQL INCLUDE member-name END-EXEC.
Margins
Code SQL statements in columns 12 through 72. If EXEC SQL starts before the
specified margin (that is, before column 12), the SQL precompiler will not
recognize the statement.
Sequence Numbers
The source statements generated by the SQL precompiler are generated with the
same sequence number as the SQL statement.
Names
Any valid COBOL variable name can be used for a host variable and is subject to
the following restrictions:
Do not use host variable names or external entry names that begin with 'SQL',
'RDI', or 'DSN'. These names are reserved for the database manager.
198
should not be specified in the PROCESS statement. Instead *APOST and *QUOTE
should be specified in the OPTION parameter of the CRTSQLCBL and
CRTSQLCBLI commands.
Statement Labels
Executable SQL statements in the PROCEDURE DIVISION can be preceded by a
paragraph name.
WHENEVER Statement
The target for the GOTO clause in an SQL WHENEVER statement must be a
section name or unqualified paragraph name in the PROCEDURE DIVISION.
199
01
77
level-1
USAGE
IS
variable-name
PICTURE
PIC
picture-string
BINARY
COMPUTATIONAL-4
COMP-4
.
VALUE
IS
numeric-constant
IS
Notes:
1. BINARY, COMPUTATIONAL-4, and COMP-4 are equivalent. A portable
application should code BINARY, because COMPUTATIONAL-4 and COMP-4
are IBM extensions that are not supported in 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 9.
2. level-1 indicates a COBOL level between 2 and 48.
The following figure shows the syntax for valid decimal host variable declarations.
DECIMAL
01
77
level-1
USAGE
IS
variable-name
PICTURE
PIC
PACKED-DECIMAL
COMPUTATIONAL-3
COMP-3
COMPUTATIONAL
COMP
.
VALUE
picture-string
IS
numeric-constant
IS
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 18.
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 the COBOL for AS/400 program, the picture-string associated with these
200
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.
3. level-1 indicates a COBOL level between 2 and 48.
The following figure shows the syntax for valid numeric host variable declarations.
Numeric
01
77
level-1
variable-name
PICTURE
PIC
picture-string
IS
DISPLAY
display clause
USAGE
IS
VALUE
numeric-constant
IS
display clause
SIGN
DISPLAY
LEADING SEPARATE
IS
CHARACTER
Notes:
1. The picture-string associated with SIGN LEADING SEPARATE and DISPLAY
must have the form S9(i)V9(d) (or S9...9V9...9, with i and d instances of 9). i + d
must be less than or equal to 18.
2. level-1 indicates a COBOL level between 2 and 48.
201
Floating-point
01
77
level-1
variable-name
COMPUTATIONAL-1
COMP-1
COMPUTATIONAL-2
COMP-2
USAGE
IS
VALUE
numeric-constant
IS
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.
01
77
level-1
variable-name
PICTURE
PIC
picture-string
IS
DISPLAY
USAGE
VALUE
string-constant
IS
IS
.
Notes:
1. The picture string associated with these forms must be X(m) (or XXX...X, with m
instance of X) with 1 m 32 766.
2. level-1 indicates a COBOL level between 2 and 48.
202
01
level-1
variable-name
49
var-1
picture-string-1
IS
USAGE
IS
.
VALUE
49
PICTURE
PIC
BINARY
COMPUTATIONAL-4
COMP-4
var-2
numeric-constant
PICTURE
PIC
IS
picture-string-2
IS
DISPLAY
USAGE
IS
.
VALUE
string-constant
IS
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 will use the full size of the S9(m) variable even
though COBOL on the AS/400 only recognizes values up to the specified
precision. This can cause data truncation errors when COBOL statements are
being run and may 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.
203
01
77
level-1
variable-name
PICTURE
PIC
picture-string
IS
DISPLAY-1
VALUE
USAGE
string-constant
IS
IS
.
Notes:
1. The picture string associated with these forms must be G(m) (or GGG...G, with
m instance of G) or N(m) (or NNN...N, with m instance of N) with 1 m 16
383.
2. level-1 indicates a COBOL level between 2 and 48.
01
level-1
variable-name
49
var-1
picture-string-1
IS
USAGE
IS
.
VALUE
49
numeric-constant
PICTURE
PIC
BINARY
COMPUTATIONAL-4
COMP-4
var-2
PICTURE
PIC
IS
picture-string-2
IS
DISPLAY-1
USAGE
IS
.
VALUE
string-constant
IS
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 will use the full size of the S9(m) variable even
though COBOL on the AS/400 only recognizes values up to the specified
precision. This can cause data truncation errors when COBOL statements are
being run and may effectively limit the maximum length of variable-length
graphic strings to the specified precision.
2. The picture-string-2 associated with these forms 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.
204
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 (that is, PL/I style). For example, specify B.C1
rather than C1 OF B or C1 IN B. However, PL/I style 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:
v A COBOL item that must begin in area A
v Any SQL statement (except SQL INCLUDE)
After the host structure is defined, you can refer to it in an SQL statement instead
of listing the several host variables (that is, the names of the data items that
comprise the host structure).
For example, you can retrieve all column values from selected rows of the table
CORPDATA.EMPLOYEE with:
01 PEMPL.
10 EMPNO
10 FIRSTNME.
49 FIRSTNME-LEN
49 FIRSTNME-TEXT
10 MIDINIT
10 LASTNAME.
49 LASTNAME-LEN
49 LASTNAME-TEXT
10 WORKDEPT
...
MOVE "000220" TO EMPNO.
...
EXEC SQL
SELECT *
INTO :PEMPL
FROM CORPDATA.EMPLOYEE
WHERE EMPNO = :EMPNO
END-EXEC.
PIC X(6).
PIC S9(4) USAGE BINARY.
PIC X(12).
PIC X(1).
PIC S9(4) USAGE BINARY.
PIC X(15).
PIC X(3).
205
Notice that in the declaration of PEMPL, two varying-length string elements are
included in the structure: FIRSTNME and LASTNAME.
Host Structure
The following figure shows the syntax for the valid host structure.
Host Structure
level-1
level-2
variable-name .
var-1
PICTURE
PIC
IS
floating-point .
varchar-string .
vargraphic-string .
picture-string
usage-clause .
floating-point
COMPUTATIONAL-1
COMP-1
COMPUTATIONAL-2
COMP-2
USAGE
IS
VALUE
constant
IS
usage-clause
BINARY
COMPUTATIONAL-4
COMP-4
PACKED-DECIMAL
COMPUTATIONAL-3
COMP-3
COMPUTATIONAL
COMP
DISPLAY
display-clause
DISPLAY-1
USAGE
IS
VALUE
display-clause
SIGN
DISPLAY
206
LEADING
IS
constant
IS
SEPARATE
CHARACTER
varchar-string
49
var-2
PICTURE
PIC
picture-string-1
IS
USAGE
IS
.
VALUE
49 var-3
PICTURE
PIC
numeric-constant
BINARY
COMPUTATIONAL-4
COMP-4
picture-string-2
BINARY
COMPUTATIONAL-4
COMP-4
picture-string-2
IS
IS
DISPLAY
VALUE
USAGE
constant
IS
IS
vargraphic-string
49
var-2
PICTURE
PIC
picture-string-1
IS
USAGE
IS
.
VALUE
49 var-3
numeric-constant
PICTURE
PIC
IS
IS
DISPLAY-1
USAGE
VALUE
constant
IS
IS
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 and floating-point host variables are only supported for
ILE COBOL for AS/400.
4. For details on declaring numeric, character, and graphic host variables, see the
notes under numeric-host variables, character-host variables, and graphic-host
variables.
207
level-1 variable-name
USAGE
IS
PICTURE
PIC
BINARY
COMPUTATIONAL-4
COMP-4
picture-string
OCCURS dimension
.
VALUE
IS
TIMES
constant
IS
Notes:
1. Dimension must be an integer between 1 and 32767.
2. level-1 must be an integer between 2 and 48.
3. BINARY, COMPUTATIONAL-4, and COMP-4 are equivalent. A portable
application should code BINARY, because COMPUTATIONAL-4 and COMP-4
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.
A-STRUCT.
02 B-ARRAY OCCURS 10 TIMES.
03 C1-VAR PIC X(20).
03 C2-VAR PIC S9(4).
208
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.
....
EXEC SQL
FETCH C1 FOR 10 ROWS INTO :DEPT :IND-ARRAY
END-EXEC.
209
level-1
TIMES
level-2
var-1
PICTURE
PIC
IS
floating-point .
varchar-string .
vargraphic-string .
picture-string-1
usage-clause .
VALUE
constant
floating-point
COMPUTATIONAL-1
COMP-1
COMPUTATIONAL-2
COMP-2
USAGE
IS
IS
usage-clause
BINARY
COMPUTATIONAL-4
COMP-4
PACKED-DECIMAL
COMPUTATIONAL-3
COMP-3
COMPUTATIONAL
COMP
DISPLAY
display-clause
DISPLAY-1
USAGE
IS
VALUE
display-clause
SIGN
DISPLAY
210
LEADING
IS
constant
IS
SEPARATE
CHARACTER
varchar-string
49
var-2
PICTURE
PIC
picture-string-2
IS
USAGE
IS
.
VALUE
49 var-3
PICTURE
PIC
numeric-constant
BINARY
COMPUTATIONAL-4
COMP-4
picture-string-3
BINARY
COMPUTATIONAL-4
COMP-4
picture-string-3
IS
IS
DISPLAY
VALUE
USAGE
constant
IS
IS
vargraphic-string
49
var-2
PICTURE
PIC
picture-string-2
IS
USAGE
IS
.
VALUE
49 var-3
numeric-constant
PICTURE
PIC
IS
IS
DISPLAY-1
USAGE
VALUE
constant
IS
IS
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 and floating-point host variables are only supported for
ILE COBOL for AS/400.
4. For details on declaring numeric, character, and graphic host variables, see the
notes under numeric-host variables, character-host variables, and graphic-host
variables.
5. Dimension must be an integer constant between 1 and 32767.
211
level-1
TIMES
level-2 var-1
PICTURE
PIC
USAGE
IS
picture-string
IS
BINARY
COMPUTATIONAL-4
COMP-4
VALUE
constant
IS
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 32767.
4. BINARY, COMPUTATIONAL-4, and COMP-4 are equivalent. A portable
application should code BINARY, because COMPUTATIONAL-4 and COMP-4
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.
DEPARTMENT-STRUCTURE.
COPY DDS-ALL-FORMATS OF DEPARTMENT.
212
DEPT.
04 DEPT-ARRAY OCCURS 10 TIMES.
COPY DDS-ALL-FORMATS OF DEPARTMENT.
:
Note: DATE, TIME, and TIMESTAMP columns will generate character host
variable definitions that are treated by SQL with the same comparison and
assignment rules as the DATE, TIME, or TIMESTAMP column. For example,
a date host variable can only be compared against a DATE column or a
character string which is a valid representation of a date.
Although GRAPHIC and VARGRAPHIC are mapped to character variables
in COBOL for AS/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.
SQLTYPE of
Host Variable
484
i+d in byte 1, d
in byte 2
DECIMAL(i+d,d)
213
Table 26. COBOL Declarations Mapped to Typical SQL Data Types (continued)
COBOL Data Type
SQLTYPE of
Host Variable
504
i+d in byte 1, d
in byte 2
No exact
equivalent use
DECIMAL(i+d,d)
or NUMERIC
(i+d,d)
S9(i)V9(d)DISPLAY
488
i+d in byte 1, d
in byte 2
NUMERIC(i+d,d)
500
SMALLINT
496
INTEGER
500
i+d in byte 1, d
in byte 2
No exact
equivalent use
DECIMAL(i+d,d)
or NUMERIC
(i+d,d)
496
i+d in byte 1, d
in byte 2
No exact
equivalent use
DECIMAL(i+d,d)
or NUMERIC
(i+d,d)
COMP-1
480
FLOAT(single
precision)
COMP-2
480
FLOAT(double
precision)
452
CHAR(m)
448
VARCHAR(m)
456
VARCHAR(m)
468
GRAPHIC(m)
VARGRAPHIC(m)
VARGRAPHIC(m)
The following table can be used to determine the COBOL data type that is
equivalent to a given SQL data type.
Table 27. SQL Data Types Mapped to Typical COBOL Declarations
214
Notes
SMALLINT
S9(m) COMP-4
m is from 1 to 4
INTEGER
S9(m) COMP-4
m is from 5 to 9
Table 27. SQL Data Types Mapped to Typical COBOL Declarations (continued)
SQL Data Type
Notes
DECIMAL(p,s)
If p<19: S9(p-s)V9(s)
PACKED-DECIMAL or
S9(p-s)V9(s) COMP or
S9(p-s)V9(s) COMP-3 If p>18:
Not supported
p is precision; s is scale.
0<=s<=p<=18. If s=0, use
S9(p) or S9(p)V. If s=p, use
SV9(s).
NUMERIC(p,s)
If p<19: S9(p-s)V9(s)
DISPLAY If p>18: Not
supported
p is precision; s is scale.
0<=s<=p<=18. If s=0, use
S9(p) or S9(p)V. If s=p, use
SV9(s).
FLOAT(single precision)
FLOAT(double precision)
CHAR(n)
32766n1
VARCHAR(n)
Varying-length character
string
32740n1
GRAPHIC(n)
16383n1
VARGRAPHIC(n)
DATE
TIME
TIMESTAMP
215
The COBOL declarations for SMALLINT and INTEGER 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.
216
The scope of the SQLCODE, SQLSTATE, and SQLCA variables must include the
scope of all SQL statements in the program.
The included PL/I source statements for the SQLCA are:
DCL 1 SQLCA,
2 SQLCAID
2 SQLCABC
2 SQLCODE
2 SQLERRM
2 SQLERRP
2 SQLERRD(6)
2 SQLWARN,
3 SQLWARN0
3 SQLWARN1
3 SQLWARN2
3 SQLWARN3
3 SQLWARN4
3 SQLWARN5
3 SQLWARN6
3 SQLWARN7
3 SQLWARN8
3 SQLWARN9
3 SQLWARNA
2 SQLSTATE
CHAR(8),
FIXED(31) BINARY,
FIXED(31) BINARY,
CHAR(70) VAR,
CHAR(8),
FIXED(31) BINARY,
CHAR(1),
CHAR(1),
CHAR(1),
CHAR(1),
CHAR(1),
CHAR(1),
CHAR(1),
CHAR(1),
CHAR(1),
CHAR(1),
CHAR(1),
CHAR(5);
217
replaced with SQLSTOTE when a declare for SQLSTATE is found in the program
and the SQLCA is provided by the precompiler.
For more information on SQLCA, see Appendix B, SQL Communication Area in
the DB2 for AS/400 SQL Reference book.
218
Each SQL statement in a PL/I program must begin with EXEC SQL and end with
a semicolon (;). The key words EXEC SQL must appear all on one line, but the
remainder of the statement can appear on the next and subsequent lines.
Example
An UPDATE statement coded in a PL/I program might be coded as follows:
EXEC SQL UPDATE DEPARTMENT
SET MGRNO = :MGR_NUM
WHERE DEPTNO = :INT_DEPT ;
Comments
In addition to SQL comments (--), you can include PL/I comments (/*...*/) in
embedded SQL statements wherever a blank is allowed, except between the
keywords EXEC and SQL.
Including Code
SQL statements or PL/I host variable declaration statements can be included by
placing the following SQL statement at the point in the source code where the
statements are to be embedded:
EXEC SQL INCLUDE member-name ;
Margins
Code SQL statements within the margins specified by the MARGINS parameter on
the CRTSQLPLI command. If EXEC SQL does not start within the specified
margins, the SQL precompiler will not recognize the SQL statement. For more
information about the CRTSQLPLI command, see Appendix D. DB2 for AS/400 CL
Command Descriptions.
Names
Any valid PL/I variable name can be used for a host variable and is subject to the
following restrictions:
Chapter 12. Coding SQL Statements in PL/I Applications
219
Do not use host variable names or external entry names that begin with 'SQL',
'RDI', or 'DSN'. These names are reserved for the database manager.
Statement Labels
All executable SQL statements, like PL/I statements, can have a label prefix.
WHENEVER Statement
The target for the GOTO clause in an SQL WHENEVER statement must be a label
in the PL/I source code and must be within the scope of any SQL statements
affected by the WHENEVER statement.
Numeric-Host Variables
The following figure shows the syntax for valid scalar numeric-host variable
declarations.
220
Numeric
DECLARE
DCL
variable-name
,
(
BINARY
BIN
variable-name
FIXED
( precision )
FLOAT
( precision )
DECIMAL
DEC
FIXED
( precision
)
,scale
FLOAT
( precision )
PICTURE picture-string
;
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.
Character-Host Variables
The following figure shows the syntax for valid scalar character-host variables.
Character
DECLARE
DCL
variable-name
,
(
variable-name
CHARACTER
CHAR
length )
VARYING
VAR
Notes:
1. 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.
Chapter 12. Coding SQL Statements in PL/I Applications
221
Host Structures
The following figure shows the syntax for valid host structure declarations.
222
Host Structures
DECLARE
1 variable-name
DCL
level-1 variable-name ,
level-2
var-1
,
(
data-types
var-2
data-types
BINARY
BIN
DECIMAL
DEC
FIXED
FLOAT
FIXED
( precision )
UNALIGNED
( precision
)
,
scale
FLOAT
( precision )
UNALIGNED
PICTURE picture-string
CHARACTER
CHAR
( length )
VARYING
VAR
ALIGNED
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 and character host variables, see the notes
under numeric-host variables and character-host variables.
223
DECLARE
DCL
variable-name ( dimension )
,
(
BINARY
BIN
variable-name ( dimension )
FIXED
precision )
;
224
DECLARE
1 variable-name ( dimension )
DCL
level-1 variable-name ,
level-2
var-1
,
(
data-types
var-2
data-types
BINARY
BIN
DECIMAL
DEC
FIXED
FLOAT
FIXED
UNALIGNED
( precision )
( precision
,
FLOAT
)
scale
UNALIGNED
( precision )
PICTURE picture-string
CHARACTER
CHAR
( length )
VARYING
VAR
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 and character host variables, see the notes
under numeric-host variables and character-host variables.
5. Dimension must be an integer constant between 1 and 32767.
225
DECLARE
1 variable-name ( dimension )
DCL
level-1 variable-name ,
level-2
identifier ( dimension-2 )
BINARY
BIN
FIXED
( precision )
Notes:
1. Level-1 indicates that there is an intermediate level structure.
2. Level-1 must be an integer constant between 1 and 254.
3. Level-2 must be an integer constant between 2 and 255.
4. Dimension-1 and dimension-2 must be integer constants between 1 and 32767.
1 DEPT_REC(10),
%INCLUDE DEPARTMENT(DEPARTMENT,RECORD);
226
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.
SQLTYPE of
Host Variable
500
SMALLINT
496
INTEGER
DEC FIXED(p,s)
484
p in byte 1, s in
byte 2
DECIMAL(p,s)
480
FLOAT (single
precision)
FLOAT (double
precision)
480
FLOAT (single
precision)
480
FLOAT (double
precision)
488
p in byte 1, s in
byte 2
NUMERIC (p,s)
504
p in byte 1, s in
byte 2
No exact
equivalent, use
NUMERIC(p,s).
CHAR(n)
452
CHAR(n)
448
VARCHAR(n)
227
Table 28. PL/I Declarations Mapped to Typical SQL Data Types (continued)
PL/I Data Type
SQLTYPE of
Host Variable
456
VARCHAR(n)
The following table can be used to determine the PL/I data type that is equivalent
to a given SQL data type.
Table 29. SQL Data Types Mapped to Typical PL/I Declarations
SQL Data Type
PL/I Equivalent
Explanatory Notes
SMALLINT
BIN FIXED(p)
INTEGER
BIN FIXED(p)
DECIMAL(p,s) or
NUMERIC(p,s)
228
CHAR(n)
CHAR(n)
VARCHAR(n)
CHAR(n) VAR
GRAPHIC(n)
Not supported
Not supported.
VARGRAPHIC(n)
Not supported
Not supported.
DATE
CHAR(n)
TIME
CHAR(n)
n must be at least 6; to
include seconds, n must be at
least 8.
Table 29. SQL Data Types Mapped to Typical PL/I Declarations (continued)
SQL Data Type
PL/I Equivalent
Explanatory Notes
TIMESTAMP
CHAR(n)
BIN FIXED(15);
229
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.
For more information on the structure parameter passing technique, see Improved
Performance by Structure Parameter Passing Techniques on page 389.
230
B
B
B
B
B
B
B
B
B
1
9
13
17
19
89
97
97
101
105
109
113
117
121
121
122
123
124
125
126
127
128
129
130
131
132
8 SQLAID
120SQLABC
160SQLCOD
180SQLERL
88 SQLERM
96 SQLERP
120 SQLERR
1000SQLER1
1040SQLER2
1080SQLER3
1120SQLER4
1160SQLER5
1200SQLER6
131 SQLWRN
121 SQLWN0
122 SQLWN1
123 SQLWN2
124 SQLWN3
125 SQLWN4
126 SQLWN5
127 SQLWN6
128 SQLWN7
129 SQLWN8
130 SQLWN9
131 SQLWNA
136 SQLSTT
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
SQL
Note: Variable names in RPG for AS/400 are limited to 6 characters. The standard
SQLCA names have been changed to a length of 6. RPG for AS/400 does
not have a way of defining arrays in a data structure without also defining
Copyright IBM Corp. 1997, 1998
231
232
Example
An UPDATE statement coded in an RPG for AS/400 program might be coded as
follows:
*...1....+....2....+....3....+....4....+....5....+....6....+....7...*
C/EXEC SQL UPDATE DEPARTMENT
C+
SET MANAGER = :MGRNUM
C+
WHERE DEPTNO = :INTDEP
C/END-EXEC
Comments
In addition to SQL comments (--), RPG for AS/400 comments can be included
within SQL statements wherever a blank is allowed, except between the keywords
EXEC and SQL. To embed an RPG for AS/400 comment within the SQL statement,
place an asterisk (*) in position 7.
Including Code
SQL statements and RPG for AS/400 calculation specifications can be included by
embedding the SQL statement:
*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....8
C/EXEC SQL INCLUDE member-name
C/END-EXEC
The /COPY statement can be used to include SQL statements or RPG for AS/400
specifications.
Sequence Numbers
The sequence numbers of the source statements generated by the SQL precompiler
are based on the *NOSEQSRC/*SEQSRC keywords of the OPTION parameter on
the CRTSQLRPG command. When *NOSEQSRC is specified, the sequence number
from the input source member is used. For *SEQSRC, the sequence numbers start
at 000001 and are incremented by 1.
233
Names
Any valid RPG variable name can be used for a host variable and is subject to the
following restrictions:
Do not use host variable names or external entry names that begin with 'SQ', 'SQL',
'RDI', or 'DSN'. These names are reserved for the database manager.
Statement Labels
A TAG statement can precede any SQL statement. Code the TAG statement on the
line preceding EXEC SQL.
WHENEVER Statement
The target for the GOTO clause must be the label of the TAG statement. The scope
rules for the GOTO/TAG must be observed.
234
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.
235
*...1....+....2....+....3....+....4....+....5....+....6....+....7. ..*
IBARRAY
DS
10
I
01 20 C1VAR
I
B 21 220C2VAR
The following example uses a host structure array called DEPT and a multiple-row
FETCH statement to retrieve 10 rows from the DEPARTMENT table.
...
*...1....+....2....+....3....+....4....+....5....+....6....+....7...*
E
INDS
4 4 0
IDEPT
DS
10
I
01 03 DEPTNO
I
04 32 DEPTNM
I
33 38 MGRNO
I
39 41 ADMRD
IINDARR
DS
10
I
B
1
80INDS
C/EXEC SQL
C+ DECLARE C1 CURSOR FOR
C+
SELECT *
C+
FROM CORPDATA.DEPARTMENT
C/END-EXEC
C/EXEC SQL
C+ OPEN C1
C/END-EXEC
C/EXEC SQL
C+ FETCH C1 FOR 10 ROWS INTO :DEPT:INDARR
C/END-EXEC
Note: Code an F-spec for a file in your RPG program only if you use RPG for
AS/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.
236
*...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 which 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 which is a valid representation of a date.
Although varying-length columns generate fixed-length character-host variable
definitions, to SQL they are varying-length character variables.
Although GRAPHIC and VARGRAPHIC columns are mapped to character
variables in RPG for AS/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.
237
Table 30. RPG for AS/400 Declarations Mapped to Typical SQL Data Types
RPG for
AS/400 Data
Type
Col 43
Col 52
Data Structure
subfield
blank
blank
Length = n where n
256
452
CHAR(n)
Data structure
(without
subfields)
n/a
n/a
Length = n where n
9999
452
CHAR(n)
Input field
blank
blank
Length = n where n
256
452
CHAR(n)
Calculation
result field
n/a
blank
Length = n where n
256
452
CHAR(n)
Data Structure
subfield
Length = 2
500
SMALLINT
Data Structure
subfield
Length = 4
496
INTEGER
Data Structure
subfield
1-4
Length = 2
500
DECIMAL(4,s)
where
s=column 52
Data Structure
subfield
1-9
Length = 4
496
DECIMAL(9,s)
where
s=column 52
Data Structure
subfield
0 to 9
p in byte 1, s in DECIMAL(p,s)
byte 2
where p = n*2-1
and s = column
52
Input field
0 to 9
p in byte 1, s in DECIMAL(p,s)
byte 2
where p = n*2-1
and s = column
52
Input field
blank
0 to 9
p in byte 1, s in DECIMAL(p,s)
byte 2
where p = n
and s = column
52
Input field
0 to 4 if n
= 2; 0 to 9
if n = 4
Length = 2 or 4
484
p in byte 1, s in DECIMAL(p,s)
byte 2
where p=4 if
n=2 or 9 if n=4
and s = column
52
Calculation
result field
n/a
0 to 9
p in byte 1, s in DECIMAL(p,s)
byte 2
where p = n
and s = column
52
Data Structure
subfield
blank
0 to 9
p in byte 1, s in NUMERIC(p,s)
byte 2
where p = n
and s = column
52
238
The following table can be used to determine the RPG for AS/400 data type that is
equivalent to a given SQL data type.
Table 31. SQL Data Types Mapped to Typical RPG for AS/400 Declarations
SQL Data Type
Notes
SMALLINT
INTEGER
DECIMAL
NUMERIC
FLOAT (single
precision)
No exact equivalent
FLOAT (double
precision)
No exact equivalent
CHAR(n)
OR
Calculation result field defined without
decimal places.
CHAR(n)
VARCHAR(n)
No exact equivalent
GRAPHIC(n)
Not supported
Not supported
VARGRAPHIC(n)
Not supported
Not supported
DATE
Subfield of a data structure. Blank in position If the format is *USA, *JIS, *EUR, or *ISO, the
length must be at least 10. If the format is
52 of the subfield specification.
*YMD, *DMY, or *MDY, the length must be at
OR
least 8. If the format is *JUL, the length must
be at least 6.
Field defined without decimal places.
239
Table 31. SQL Data Types Mapped to Typical RPG for AS/400 Declarations (continued)
SQL Data Type
Notes
TIME
Subfield of a data structure. Blank in position Length must be at least 6; to include seconds,
length must be at least 8.
52 of the subfield specification.
OR
Field defined without decimal places.
TIMESTAMP
Subfield of a data structure. Blank in position Length must be at least 19. To include
microseconds at full precision, length must be
52 of the subfield specification.
26. If length is less than 26, truncation occurs
OR
on the microseconds part.
Field defined without decimal places.
Example
Given the statement:
*...1....+....2....+....3....+....4....+....5....+....6....+....7...*
C/EXEC SQL FETCH CLS_CURSOR INTO :CLSCD,
C+
:DAY :DAYIND,
C+
:BGN :BGNIND,
C+
:END :ENDIND
C/END-EXEC
240
*...1....+....2....+....3....+....4....+....5....+....6....+....7...*
I
DS
I
1
7 CLSCD
I
B
8
90DAY
I
B 10 110DAYIND
I
12 19 BGN
I
B 20 210BGNIND
I
22 29 END
I
B 30 310ENDIND
241
242
0
0
0
0 DIM(6)
0
0
0
0
0
0
Note: Variable names in RPG for AS/400 are limited to 6 characters. The standard
SQLCA names were changed to a length of 6 for RPG for AS/400. To
maintain compatibility with RPG for AS/400 programs which are converted
to ILE RPG for AS/400, the names for the SQLCA will remain as used with
RPG for AS/400. The SQLCA defined for the ILE RPG for AS/400 has
added the field SQLERRD which is defined as an array of six integers.
SQLERRD is defined to overlay the SQLERR definition.
243
8A
12B
14B
16B
80A
18B
20B
32A
48*
64*
66B
96A
0
0
0
0
0
DIM(SQL_NUM)
2B 0
4B 0
16A
32*
48*
50B 0
80A
244
Since ILE RPG for AS/400 does not support structures within arrays, the
INCLUDE SQLDA generates two data structures. The second data structure is used
to setup/reference the part of the SQLDA which 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 does a MOVEA of 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 does a MOVEA
of SQL_VAR,n to SQLVAR where n is the number of the field description to be
processed.
Example
An UPDATE statement coded in an ILE RPG for AS/400 program might be coded
as follows:
*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....8.
C/EXEC SQL UPDATE DEPARTMENT
C+
SET MANAGER = :MGRNUM
C+
WHERE DEPTNO = :INTDEP
C/END-EXEC
Comments
In addition to SQL comments (--), ILE RPG for AS/400 comments can be included
within SQL statements wherever SQL allows a blank character. To embed an ILE
RPG for AS/400 comment within the SQL statement, place an asterisk (*) in
position 7.
Chapter 14. Coding SQL Statements in ILE RPG for AS/400 Applications
245
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>.
*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....8.
C/EXEC SQL
SELECT * FROM GRAPHTAB WHERE GRAPHCOL =
G'<AABBCCDDEE>
C+<FFGGHHIIJJKK>'
C/END-EXEC
Including Code
SQL statements and RPG calculation specifications can be included by using the
SQL statement:
*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....8
C/EXEC SQL INCLUDE member-name
C/END-EXEC
The RPG /COPY statement can be used to include SQL statements or RPG
specifications.
Sequence Numbers
The sequence numbers of the source statements generated by the SQL precompiler
are based on the *NOSEQSRC/*SEQSRC keywords of the OPTION parameter on
the CRTSQLRPGI command. When *NOSEQSRC is specified, the sequence number
from the input source member is used. For *SEQSRC, the sequence numbers start
at 000001 and are incremented by 1.
Names
Any valid ILE RPG for AS/400 variable name can be used for a host variable and
is subject to the following restrictions:
Do not use host variable names or external entry names that begin with the
characters 'SQ', 'SQL', 'RDI', or 'DSN'. These names are reserved for the database
manager. The length of host variable names is limited to 64.
Statement Labels
A TAG statement can precede any SQL statement. Code the TAG statement on the
line preceding EXEC SQL.
WHENEVER Statement
The target for the GOTO clause must be the label of the TAG statement. The scope
rules for the GOTO/TAG must be observed.
246
SQL embedded in ILE RPG for AS/400 does not use the SQL BEGIN DECLARE
SECTION and END DECLARE SECTION statements to identify host variables. Do
not put these statements in the source program.
All host variables within an SQL statement must be preceded by a colon (:).
The names of host variables must be unique within the program, even if the host
variables are in different procedures.
An SQL statement that uses a host variable must be within the scope of the
statement in which the variable was declared.
Chapter 14. Coding SQL Statements in ILE RPG for AS/400 Applications
247
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
CORPDATA.EMPLOYEE is placed in EMPNO, the second column is placed in
FIRSTN, and so on.
*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....8
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, 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.
248
v If the date and time format and separator of date and time subfields within the
host structure are not the same as the DATFMT, DATSEP, TIMFMT, and TIMSEP
parameters on the CRTSQLRPGI command, then the host structure array is not
usable.
For all statements, other than the blocked FETCH and blocked INSERT, if an
occurrence data structure is used, the current occurrence is used. For the blocked
FETCH and blocked INSERT, the occurrence is set to 1.
The following example uses a host structure array called DEPT and a blocked
FETCH statement to retrieve 10 rows from the DEPARTMENT table.
*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....8
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
4B 0 DIM(4)
...
C/EXEC SQL
C+ DECLARE C1 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
Chapter 14. Coding SQL Statements in ILE RPG for AS/400 Applications
249
Note: Code an F-spec for a file in your ILE RPG for AS/400 program only if you
use ILE RPG for AS/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 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.
*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....8
DTDEPT
E DS
EXTNAME(DEPARTMENT)
D DEPTN
E
EXTFLD(DEPTNAME)
D ADMRD
E
EXTFLD(ADMRDEPT)
If the GRAPHIC or VARGRAPHIC column has a UCS-2 CCSID, the generated host
variable will have the UCS-2 CCSID assigned to it.
250
Table 32. ILE RPG for AS/400 Declarations Mapped to Typical SQL Data Types
SQLTYPE
of Host
Variable
SQLLEN of
Host Variable
Length = n where n
32766
452
CHAR(n)
n/a
Length = n where n
32766 (pos 59-63)
452
CHAR(n)
blank
length=n where n is 1
to 254. VARYING in
columns 44-80.
448
VARCHAR (n)
Definition
specification
blank
456
VARCHAR (n)
Definition
specification
Length 4
500
SMALLINT
Definition
specification
Length = 5
500
SMALLINT
Definition
specification
Length 9 and 5
496
INTEGER
Definition
specification
Length = 10
496
INTEGER
Definition
specification
1-4
Length = 2
500
DECIMAL(4,s)
s=col 41, 42
Definition
specification
1-9
Length = 4
496
DECIMAL(9,s)
s=col 41, 42
Definition
specification
0 to 30
Length = n where n is
1 to 16
484
p in byte 1, s
in byte 2
DECIMAL(p,s)
where p = n*2-1
and s = pos 41, 42
Definition
specification
blank
Length = 4
480
FLOAT (single
precision)
Definition
specification
blank
Length = 8
480
FLOAT (double
precision)
Definition
specification
not a subfield
blank
0 to 30
Length = n where n is
1 to 16
484
p in byte 1, s
in byte 2
DECIMAL(p,s)
where p = n*2-1
and s = pos 41, 42
Input field
(pos 36 = P)
n/a
n/a
Length = n where n is
1 to 16 (pos 37-46)
484
p in byte 1, s
in byte 2
DECIMAL(p,s)
where p = n*2-1
and s = pos 47, 48
Input field
(pos 36 =
blank or S)
n/a
n/a
Length = n where n is
1 to 30 (pos 37-46)
484
p in byte 1, s
in byte 2
DECIMAL(p,s)
where p = n and s
= pos 47, 48
RPG Data
Type
D spec Pos
40
D spec Pos
41,42
Data structure
(without
subfields)
blank
blank
Calculation
result field
(pos 69,70 =
blank)
n/a
Definition
specification
Chapter 14. Coding SQL Statements in ILE RPG for AS/400 Applications
251
Table 32. ILE RPG for AS/400 Declarations Mapped to Typical SQL Data Types (continued)
SQLTYPE
of Host
Variable
SQLLEN of
Host Variable
RPG Data
Type
D spec Pos
40
D spec Pos
41,42
Input field
(pos 36 = B)
n/a
n/a
Length = n where n is
2 or 4 (pos 37-46)
484
p in byte 1, s
in byte 2
DECIMAL(p,s)
where p=4 if n=2
or 9 if n=4 s = pos
47, 48
Calculation
result field
(pos 69,70
blank)
n/a
n/a
Length = n where n is
1 to 30 (pos 59-63)
484
p in byte 1, s
in byte 2
DECIMAL(p,s)
where p = n and s
= pos 64, 65
Data Structure
subfield
blank
0 to 30
Length = n where n is
1 to 30
488
p in byte 1, s
in byte 2
NUMERIC(p,s)
where p = n and s
= pos 41, 42
Definition
specification
0 to 30
Length = n where n is
1 to 30
488
p in byte 1, s
in byte 2
NUMERIC(p,s)
where p = n and s
= pos 41, 42
Input field
(pos 36 = G)
n/a
n/a
Length = n where n is
1 to 32766 (pos 37-46)
468
GRAPHIC(m)
where m = n/2 m
= (TO-FROM-1)/2
Definition
specification
blank
length=n where n is 1
to 127. VARYING in
columns 44-80.
464
VARGRAPHIC (n)
Definition
specification
blank
472
VARGRAPHIC (n)
Definition
specification
blank
Length = n where n is
6, 8 or 10
384
DATE (DATFMT,
DATSEP specified
in pos 44-80)
Input field
(pos 36 = D)
n/a
n/a
Length = n where n is
6, 8, or 10 (pos 37-46)
384
DATE (format
specified in pos
31-34)
Definition
specification
blank
Length = n where n is
8
388
TIME (TIMFMT,
TIMSEP specified
in pos 44-80)
Input field
(pos 36 = T)
n/a
n/a
Length = n where n is
8 (pos 37-46)
388
TIME (format
specified in pos
31-34)
Definition
specification
blank
Length = n where n is
26
392
TIMESTAMP
Input field
(pos 36 = Z)
n/a
n/a
Length = n where n is
26 (pos 37-46)
392
TIMESTAMP
Notes:
1. In the first column the term definition specification includes data structure
subfields unless explicitly stated otherwise.
2. In definition specifications the length of binary fields (B in pos 40) is
determined by the following:
v FROM (pos 26-32) is not blank, then length = TO-FROM+1.
252
v FROM (pos 26-32) is blank, then length = 2 if pos 33-39 < 5, or length = 4 if
pos 33-39 > 4.
3. SQL will create the date/time subfield using the DATE/TIME format specified
on the CRTSQLRPGI command. The conversion to the host variable
DATE/TIME format will occur 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 33. SQL Data Types Mapped to Typical RPG Declarations
SQL Data Type
SMALLINT
Notes
DECIMAL
NUMERIC
CHAR(n)
Chapter 14. Coding SQL Statements in ILE RPG for AS/400 Applications
253
Table 33. SQL Data Types Mapped to Typical RPG Declarations (continued)
SQL Data Type
Notes
CHAR(n)
VARCHAR(n)
GRAPHIC(n)
n can be 1 to 16383.
DATE
A character field
OR
A character field
OR
A character field
OR
Definition specification with a Z in
position 40.
OR
254
Example
Given the statement:
*...1....+....2....+....3....+....4....+....5....+....6....+....7....+....8
C/EXEC SQL FETCH CLS_CURSOR INTO :CLSCD,
C+
:DAY :DAYIND,
C+
:BGN :BGNIND,
C+
:END :ENDIND
C/END-EXEC
255
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/END-EXEC
...
C/EXEC SQL
C+ FETCH C1 FOR 10 ROWS
C+
USING DESCRIPTOR :SQLDA
C+
INTO :DEPARTMENT:IND_ARRAY
C/END-EXEC
256
SQLERRMC
SQLERRP
SQLERRD.n
SQLWARN.n
SQLSTATE
257
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. See the DB2 for AS/400
SQL Reference book for more information on the SQLDA.
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
460/461
476/477
PASCAL L-string
496/497
500/501
504/505
stem.n.SQLLEN
If SQLTYPE does not indicate a DECIMAL or NUMERIC data type, the
maximum length of the data contained in stem.n.SQLDATA.
stem.n.SQLLEN.SQLPRECISION
If the data type is DECIMAL or NUMERIC, this contains the precision of
the number.
stem.n.SQLLEN.SQLSCALE
If the type is DECIMAL or NUMERIC, this contains the scale of the
number.
stem.n.SQLCCSID
The CCSID of the nth column of the data.
The following variables must be provided by the application before an
EXECUTE...USING DESCRIPTOR or an OPEN...USING DESCRIPTOR statement,
258
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
quotes, for example:
'EXECSQL COMMIT'
EXECUTE
EXECUTE IMMEDIATE
FETCH 7
GRANT
INSERT 7, 8
LABEL ON
LOCK TABLE
OPEN
PREPARE
RENAME
REVOKE
ROLLBACK
SET OPTION 9
SET TRANSACTION
UPDATE 8
259
The following SQL statements are not supported by the SQL/REXX interface:
BEGIN DECLARE SECTION
CONNECT
CREATE SCHEMA
DECLARE PROCEDURE
DECLARE STATEMENT
DECLARE VARIABLE
DISCONNECT
Comments
Neither SQL comments (--) nor REXX comments are allowed in strings
representing SQL statements.
Including Code
Unlike the other host languages, support is not provided for including externally
defined statements.
Margins
There are no special margin rules for the SQL/REXX interface.
Names
Any valid REXX name not ending in a period (.) can be used for a host variable.
The name must be 64 characters or less.
Variable names should not begin with the characters 'SQL', 'RDI', 'DSN', 'RXSQL',
or 'QRW'.
Nulls
Although the term null is used in both REXX and SQL, the term has different
meanings in the two languages. REXX has a null string (a string of length zero)
and a null clause (a clause consisting only of blanks and comments). The SQL null
value is a special value that is distinct from all non-null values and denotes the
absence of a (non-null) value.
260
Statement Labels
REXX command statements can be labeled as usual.
+10
-10
-100
This can be used to detect errors and warnings issued by either the database
manager or by the SQL/REXX interface.
v The SIGNAL ON ERROR and SIGNAL ON FAILURE facilities can be used to
detect errors (negative RC values), but not warnings.
261
SQL Type
Code
SQL Type
Description
Undefined Variable
None
Data that is
not valid was
detected.
Varying-length character
string
448/449
VARCHAR(n)
Varying-length graphic
string
464/465
VARGRAPHIC(n)
Floating point
480/481
FLOAT
Packed decimal
484/485
DECIMAL(m,n)
Signed integers
496/497
INTEGER
262
causes REXX to set the variable stringvar to the string of characters 100 (without
the apostrophes). This is evaluated by the SQL/REXX interface as the number 100,
and it is passed to SQL as such.
On the other hand,
stringvar = '100'
causes REXX to set the variable stringvar to the string of characters '100' (with the
apostrophes). This is evaluated by the SQL/REXX interface as the string 100, and it
is passed to SQL as such.
11. The byte immediately following the leading apostrophe is a X'0E' shift-out, and the byte immediately preceding the trailing
apostrophe is a X'0F' shift-in.
Chapter 15. Coding SQL Statements in REXX Applications
263
264
265
QSQLCMIT
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) or for CVTSQLCPP
|
|
|
The SQL precompiler assumes that the host language statements are syntactically
correct. If the host language statements are not syntactically correct, the
precompiler may not correctly identify SQL statements and host variable
declarations. There are limits on the forms of source statements that can be passed
through the precompiler. 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 get secondary input from the file that
is specified by the INCFILE parameter of the CRTSQLxxx 13 and CVTSQLCPP
command. The SQL INCLUDE statement causes input to be read from the
specified member until it reaches the end of the member. The included member
may not contain other precompiler INCLUDE statements, but can contain both
application program and SQL statements.
|
|
|
|
|
Another preprocessor may process source statements before the SQL precompiler.
However, any preprocessor run before the SQL precompile must be able to pass
through SQL statements.
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 options in the input source member by
using the SQL SET OPTION statement. See the DB2 for AS/400 SQL Reference book
for the SET OPTION syntax.
|
|
13. The xxx in this command refers to the host language indicators: CBL for the COBOL for AS/400 language, CBLI for the ILE
COBOL for AS/400 language, PLI for the AS/400 PL/I language, CI for the ILE C for AS/400 language, RPG for the RPG for
AS/400 language, RPGI for the ILE RPG for AS/400 language, CPPI for the ILE C++/400 language.
266
converted to the CCSID of the original source file if necessary. If the include source
cannot be converted to the CCSID of the original source file, an error will occur.
The SQL precompiler will process 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. Prior to Version 2 Release 1.1, SQL looked for the not sign () in the
location '5F'X in CCSID 37. 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 or CVTSQLCPP command. The following items are
written to the printer file:
v Precompiler options
Options specified in the CRTSQLxxx or CVTSQLCPP command.
v Precompiler source
This output supplies precompiler source statements with the record numbers
that are assigned by the precompiler, if the listing option is in effect.
v Precompiler cross-reference
If *XREF was specified in the OPTION parameter, this output supplies a
cross-reference listing. The listing shows the precompiler record numbers of SQL
statements that contain the referred to host names and column names.
v Precompiler diagnostics
This output supplies diagnostic messages, showing the precompiler record
numbers of statements in error.
The output to the printer file will use a CCSID value of 65535. The data will not
be converted when it is written to the printer file.
Source statements processed by the precompiler are written to an output source file
that is specified on the CRTSQLxx or CVTSQLCPP command in the TOSRCFILE
parameter. The default file is QSQLTEMP (QSQLTEMP1 for ILE RPG for AS/400)
in the QTEMP library. In your precompiler-changed source code, SQL statements
have been converted to comments and calls to the SQL runtime. The name of the
output source file member is the same as the name specified in the PGM or OBJ
parameter of the CRTSQLxxx or CVTSQLCPP 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.
|
|
|
267
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
files 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.
CBLTEST1
A list of the options you specified when the SQL precompiler was called.
268
04/01/98 11:14:21
Page
IDENTIFICATION DIVISION.
PROGRAM-ID. CBLTEST1.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. IBM-AS400.
OBJECT-COMPUTER. IBM-AS400.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT OUTFILE, ASSIGN TO PRINTER-QPRINT,
FILE STATUS IS FSTAT.
DATA DIVISION.
FILE SECTION.
FD OUTFILE
DATA RECORD IS REC-1,
LABEL RECORDS ARE OMITTED.
01 REC-1.
05 CC
PIC X.
05 DEPT-NO
PIC X(3).
05 FILLER
PIC X(5).
05 AVERAGE-EDUCATION-LEVEL PIC ZZZ.
05 FILLER
PIC X(5).
05 AVERAGE-SALARY
PIC ZZZZ9.99.
01 ERROR-RECORD.
05 CC
PIC X.
05 ERROR-CODE
PIC S9(5).
05 ERROR-MESSAGE
PIC X(70).
WORKING-STORAGE SECTION.
EXEC SQL
INCLUDE SQLCA
END-EXEC.
77 FSTAT
PIC XX.
01 AVG-RECORD.
05 WORKDEPT
PIC X(3).
05 AVG-EDUC
PIC S9(4) USAGE COMP-4.
05 AVG-SALARY
PIC S9(6)V99 COMP-3.
PROCEDURE DIVISION.
***************************************************************
* This program will get the average education level and the *
* average salary by department.
*
***************************************************************
A000-MAIN-PROCEDURE.
OPEN OUTPUT OUTFILE.
***************************************************************
* Set-up WHENEVER statement to handle SQL errors.
*
***************************************************************
EXEC SQL
WHENEVER SQLERROR GO TO B000-SQL-ERROR
END-EXEC.
***************************************************************
* Declare cursor
*
***************************************************************
EXEC SQL
DECLARE CURS CURSOR FOR
SELECT WORKDEPT, AVG(EDLEVEL), AVG(SALARY)
FROM CORPDATA.EMPLOYEE
GROUP BY WORKDEPT
END-EXEC.
***************************************************************
* Open cursor
*
***************************************************************
EXEC SQL
OPEN CURS
END-EXEC.
2 SEQNBR
04/01/98 11:14:21
3Last Change
Page
100
200
300
400
500
600
700
800
900
1000
1100
1200
1300
1400
1500
1600
1700
1800
1900
2000
2100
2200
2300
2400
2500
2600
2700
2800
2900
3000
3100
3200
3300
3400
3500
3600
3700
3800
3900
4000
4100
4200
4300
4400
4500
4600
4700
4800
4900
5000
5100
5200
5300
5400
5500
5600
5700
5800
5900
6000
6100
6200
6300
Record number assigned by the precompiler when it reads the source record. Record numbers are used to
identify the source record in error messages and SQL run-time processing.
Sequence number taken from the source record. The sequence number is the number seen when you use the
source entry utility (SEU) to edit the source member.
Date when the source record was last changed. If Last is blank, it indicates that the record has not been
changed since it was created.
269
270
04/01/98 11:14:21
SEQNBR Last change
6400
6500
6600
6700
6800
6900
7000
7100
7200
7300
7400
7500
7600
7700
7800
7900
8000
8100
8200
8300
8400
8500
8600
8700
8800
8900
9000
9100
9200
9300
9400
9500
9600
9700
9800
9900
10000
10100
10200
Page
AVG-SALARY
BIRTHDATE
BONUS
B000-SQL-ERROR
35
55
55
****
CC
CC
COMM
CORPDATA
17
24
55
****
CURS
53
DEPT-NO
EDLEVEL
18
****
EDLEVEL
EMPLOYEE
55
****
EMPNO
ERROR-CODE
ERROR-MESSAGE
ERROR-RECORD
FIRSTNME
FSTAT
HIREDATE
JOB
LASTNAME
MIDINIT
PHONENO
REC-1
SALARY
55
25
26
23
55
31
55
55
55
55
55
16
****
SALARY
55
CBLTEST1
04/01/98 11:14:21
Page
Reference
IN REC-1
IN REC-1
SMALL INTEGER PRECISION(4,0) IN AVG-RECORD
STRUCTURE
83
DECIMAL(8,2) IN AVG-RECORD
DATE(10) COLUMN IN CORPDATA.EMPLOYEE
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
LABEL
47
CHARACTER(1) IN REC-1
CHARACTER(1) IN ERROR-RECORD
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
4 COLLECTION
5 55
CURSOR
62 73 83
CHARACTER(3) IN REC-1
COLUMN
54
6
SMALL INTEGER PRECISION(4,0) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
TABLE IN CORPDATA
7
55
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
NUMERIC(5,0) IN ERROR-RECORD
CHARACTER(70) IN ERROR-RECORD
STRUCTURE
VARCHAR(12) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
CHARACTER(2)
DATE(10) COLUMN IN CORPDATA.EMPLOYEE
CHARACTER(8) COLUMN IN CORPDATA.EMPLOYEE
VARCHAR(15) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
CHARACTER(1) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
CHARACTER(4) COLUMN IN CORPDATA.EMPLOYEE
COLUMN
54
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
The define column specifies the line number at which the name is defined. The line number is generated by
the SQL precompiler. **** means that the object was not defined or the precompiler did not recognize the
declarations.
WORKDEPT
55
No errors found in source
102 Source records processed
* * * * * E N D O F L I S T I N G
CBLTEST1
04/01/98 11:14:21
Page
271
|
|
|
|
|
|
|
|
|
272
|
|
Note: You must not change the source member in QTEMP/QSQLTEMP prior to
issuing the CRTxxxPGM command or the compile will fail.
In the DB2 Query Manager and SQL Development Kit, the following ILE
precompiler commands exist: CRTSQLCI, CRTSQLCBLI, CRTSQLRPGI,
CRTSQLCPPI, and CVTSQLCPP. There is a precompiler command for each of the
host languages: ILE C for AS/400, ILE COBOL for AS/400, and ILE RPG for
AS/400. Separate commands, by language, let you specify the required parameters
and take the default for the remaining parameters. The defaults are applicable only
to the language you are using. For example, the options *APOST and *QUOTE are
unique to COBOL. They are not included in the commands for the other
languages. Refer to Appendix D. DB2 for AS/400 CL Command Descriptions on
page 489 for more information.
The SQL precompiler automatically calls the host language compiler after the
successful completion of a precompile for the CRTSQLxxx commands, unless
*NOGEN is specified. If the *MODULE option is specified, the SQL precompiler
issues the CRTxxxMOD command to create the module. If the *PGM option is
specified, the SQL precompiler issues the CRTBNDxxx command to create the
program. If the *SRVPGM option is specified, the SQL precompiler issues the
CRTxxxMOD command to create the module, followed by the Create Service
Program (CRTSRVPGM) command to create the service program. The
CRTSQLCPPI command only create *MODULE objects. The CVTSQLCPP never
creates an object.
Within these languages, the following parameters are passed:
v If DBGVIEW(*SOURCE) is specified on the CRTSQLxxx command, then
DBGVIEW(*ALL) is specified on both the CRTxxxMOD and CRTBNDxxx
commands.
v If OUTPUT(*PRINT) is specified on the CRTSQLxxx command, it is passed on
both the CRTxxxMOD and CRTBNDxxx commands.
If OUTPUT(*NONE) is specified on the CRTSQLxxx command, it is not specified
on either the CRTxxxMOD command or the CRTBNDxxx command.
v The TGTRLS parameter value from the CRTSQLxxx command is specified on the
CRTxxxMOD, CRTBNDxxx, and Create Service Program (CRTSRVPGM)
commands.
v The REPLACE parameter value from the CRTSQLxxx command is specified on
the CRTxxxMOD, CRTBNDxxx, and CRTSRVPGM commands.
If a package is created as part of the precompile process, the REPLACE
parameter value from the CRTSQLxxx command is specified on the
CRTSQLPKG command.
v If OBJTYPE is either *PGM or *SRVPGM, and USRPRF(*USER) or system
naming (*SYS) with USRPRF(*NAMING) is specified, USRPRF(*USER) is
specified on the CRTBNDxxx or the CRTSRVPGM commands.
If OBJTYPE is either *PGM or *SRVPGM, and USRPRF(*OWNER) or SQL
naming (*SQL) with USRPRF(*NAMING) is specified, USRPRF(*OWNER) is
specified on the CRTBNDxxx or the CRTSRVPGM commands.
v For C and C++, the MARGINS are set in the temporary source file.
Chapter 16. Preparing and Running a Program with SQL Statements
273
|
|
|
|
|
|
|
|
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 SQL precompiler for VisualAge C++ for AS/400 is invoked using the
CVTSQLCPP CL command. This precompiler is different than the other language
precompilers since it does not have an option to generate the module or program
object. Since the precompiler runs on the AS/400 and the compiler runs on the
workstation, the two steps must be run independently.
|
|
|
|
|
|
|
|
|
|
CTTCONN /h<as400name>
|
|
|
|
|
This command copies myapp.sqx (your source) to the AS/400 into the
qsys.lib/mylib.lib/myfile.file/myapp.mbr directory. This is the same as the
AS/400 file system MYLIB/MYFILE (MYAPP) member.
274
|
|
|
4. Run the SQL precompiler on the AS/400 for the source member. This is the
CVTSQLCPP CL command. You can also do this from the workstation by using
the CTTHCMD command.
|
|
5. Copy the output source file member containing the converted SQL to the
workstation:
|
|
|
|
Alternately, you can leave the source on the AS/400 and run the compiler
against it there.
6. Run the C++ compiler and create the final module or program. If the output
source member is still on the AS/400:
iccas /c x:\qsys.lib\mylib.lib\mytosrcfile.file\myapp.mbr
iccas -c myapp.cpp
|
|
|
Note that the program must be created on the AS/400 where the precompile
was run since there is some additional SQL information that was created by the
precompiler that is needed for the final executable object.
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.
275
Binding an Application
Before you can run your application program, a relationship between the program
and any specified tables and views must be established. This process is called
binding. The result of binding is an access plan.
The access plan is a control structure that describes the actions necessary to satisfy
each SQL request. An access plan contains information about the program and
about the data the program intends to use.
For a nondistributed SQL program, the access plan is stored in the program. For a
distributed SQL program (where the RDB parameter was specified on the
CRTSQLxxx or CVTSQLCPP commands), 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 compiles, this occurs as the result of a successful
CRTxxxPGM. For ILE compiles, this occurs as the result of a successful
CRTBNDxxx, CRTPGM, or CRTSRVPGM command. If DB2 for AS/400 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 may
improve performance (for example, the addition of indexes), a new access plan is
automatically created. Binding does three 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, view,
and column names. If a specified table or view does not exist at the time of the
precompile or compile, the validation is done at run time. If the table or view
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, when it
builds an access plan. 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. If all the SQL statements are valid, the bind
process then builds and stores access plans 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
|
|
|
|
276
is returned. In this case, you might have to change the programs SQL statements
and reissue the CRTSQLxxx or CVTSQLCPP command to correct the situation.
For example, if a program contains an SQL statement that refers to COLUMNA in
TABLEA and the user deletes and recreates TABLEA so that COLUMNA no longer
exists, when you call the program, the automatic rebind will be unsuccessful
because COLUMNA no longer exists. In this case you must change the program
source and reissue the CRTSQLxxx command.
Program References
All collections, tables, views, SQL packages, and indexes referenced in SQL
statements in an SQL program are placed in the object information repository
(OIR) of the library when the program is created.
You can use the CL command Display Program References (DSPPGMREF) to
display all object references in the program. If the SQL naming convention is used,
the library name is stored in the OIR in one of three ways:
1. If the SQL name is fully qualified, the collection 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 collection 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:
1. If the object name is fully qualified, the library name is stored as the name
qualifier.
2. If the object is not fully qualified and the DFTRDBCOL parameter is not
specified, *LIBL is stored.
3. If the SQL name is not fully qualified and the DFTRDBCOL parameter is
specified, the collection name specified on the DFTRDBCOL parameter is stored
as the name qualifier.
When the SQL application program is successfully compiled, the Display Module
(DSPMOD), the Display Program (DSPPGM), or the Display Service Program
(DSPSRVPGM) command can be used to determine some of the options that were
specified on the SQL precompile. This information may be needed when the source
of the program has to be changed. These same SQL precompiler options can then
be specified on the CRTSQLxxx or CVTSQLCPP 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.
277
on the system command line. For more information on running programs, see the
CL Programming book.
Override Considerations
You can use overrides (specified by the OVRDBF command) to direct a reference to
a different table or view or to change certain operational characteristics of the
program or SQL Package. The following parameters are processed if an override is
specified:
TOFILE
MBR
SEQONLY
INHWRT
WAITRCD
All other override parameters are ignored. Overrides of statements in SQL
packages are accomplished by doing both of the following:
1. Specifying the OVRSCOPE(*JOB) parameter on the OVRDBF command
2. Sending the command to the application server by using the Submit Remote
Command (SBMRMTCMD) command
|
|
|
To override tables and views that are created with long names, you can create an
override using the system name that is associated with the table or view. When the
long name is specified in an SQL statement, the override is found using the
corresponding system name.
|
|
An alias is actually created as a DDM file. You can create an override that refers to
an alias name (DDM file). In this case, an SQL statement that refers to the file that
has the override actually uses the file to which the alias refers.
For more information on overrides, see the DB2 for AS/400 Database Programming
book, and the Data Management book.
278
279
F6=Insert line
F13=Services
F9=Retrieve
F10=Copy line
F24=More keys
Bottom
Note: If you are using the system naming convention, the names in parentheses
appear instead of the names shown above.
An interactive session consists of:
v Parameter values you specified for the STRSQL command .
280
v SQL statements you entered in the session along with corresponding messages
that follow each SQL statement
v Values of any parameters you changed using the session services function
v List selections you have made
Interactive SQL supplies a unique session-ID consisting of your user ID and the
current work station ID. This session-ID concept allows multiple users with the
same user ID to use interactive SQL from more than one work station at the same
time. Also, more than one interactive SQL session can be run from the same work
station at the same time from the same user ID.
If an SQL session exists and is being re-entered, any parameters specified on the
STRSQL command are ignored. The parameters from the existing SQL session are
used.
Typing Statements
The statement you type on the command line can be one or more lines long. You
cannot type comments for the SQL statement in interactive SQL. When the
statement has been processed, the statement and the resulting message are moved
upward on the display. You can then enter another statement.
If a statement is recognized by SQL but contains a syntax error, the statement and
the resulting text message (syntax error) are moved upward on the display. In the
input area, a copy of the statement is shown with the cursor positioned at the
syntax error. You can place the cursor on the message and press F1=Help for more
information about the error.
You can page through previous statements, commands, and messages. Press
F9=Retrieve with your cursor on a previous statement to place a copy of that
statement in the input area. If you need more room to type an SQL statement, page
down on the display.
Prompting
The prompt function helps you supply the necessary information for the syntax of
the statement you want to use. The prompt function can be used in any of the
three statement processing modes: *RUN, *VLD, and *SYN.
You have two options when using the prompter:
v Type the verb of the statement before pressing F4=Prompt.
The statement is parsed and the clauses that are completed are filled in on the
prompt displays.
If you type SELECT and press F4=Prompt, the following display appears:
281
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
_____________________________________________
_____________________________________________
_____________________________________________
_____________________________________________
_____________________________________________
_____________________________________________
_____________________________________________
Bottom
F3=Exit
F10=Copy line
Y=Yes, N=No
Y=Yes, N=No
Y=Yes, N=No
F4=Prompt
F5=Refresh
F6=Insert line
F9=Specify subquery
F12=Cancel F14=Delete line F15=Split line F24=More keys
v Press F4=Prompt before typing anything on the Enter SQL Statements display.
You are shown a list of statements. The list of statements varies and depends on
the current interactive SQL statement processing mode. For syntax check mode
with a language other than *NONE, the list includes all SQL statements. For run
and validate modes, only statements that can be run in interactive SQL are
shown. You can select the number of the statement you want to use. The system
prompts you for the statement you selected.
If you press F4=Prompt without typing anything, the following display appears:
Select SQL Statement
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ALTER TABLE
CALL
COMMENT ON
COMMIT
CONNECT
CREATE ALIAS
CREATE COLLECTION
CREATE INDEX
CREATE PROCEDURE
CREATE TABLE
CREATE VIEW
DELETE
DISCONNECT
DROP ALIAS
Selection
__
F3=Exit
More...
F12=Cancel
If you press F21=Display Statement on a prompt display, the prompter displays the
formatted SQL statement as it was filled in to that point.
When Enter is pressed within prompting, the statement that was built through the
prompt screens is inserted into the session. If the statement processing mode is
*RUN, the statement is run. The prompter remains in control if an error is
encountered.
282
Syntax Checking
The syntax of the SQL statement is checked when it enters the prompter. The
prompter does not accept a syntactically incorrect statement. You must correct the
syntax or remove the incorrect part of the statement or prompting will not be
allowed.
Subqueries
Subqueries can be selected on any display that has a WHERE or HAVING clause.
To see the subquery display, press F9=Specify subquery when the cursor is on a
WHERE or HAVING input line. A display appears that allows you to type in
subselect information. If the cursor is within the parentheses of the subquery when
F9 is pressed, the subquery information is filled in on the next display. If the cursor
is outside the parentheses of the subquery, the next display is blank. For more
information on subqueries, see Using Subqueries on page 83.
283
When Enter is pressed, the character string is put together, removing the extra shift
characters. The statement would look like this on the Enter SQL Statements
display:
SELECT * FROM TABLE1 WHERE COL1 = '<AABBCCDDEEFFGGHHIIJJKKLLMMNNOOPPQQRRSS>'
|
|
|
|
|
On a list, you can select one or more items, numerically specifying the order in
which you want them to appear in the statement. When the list function is exited,
the selections you made are inserted at the position of the cursor on the display
you came from.
Always select the list you are primarily interested in. For example, if you want a
list of columns, but you believe that the columns you want are in a table not
currently selected, press F18=Select columns. Then, from the column list, press F17
to change the table. If the table list were selected first, the table name would be
inserted into your statement. You would not have a choice for selecting columns.
You can request a list at any time while typing an SQL statement on the Enter SQL
Statements display. The selections you make from the lists are inserted on the Enter
SQL Statements display. They are inserted where the cursor is located in the
numeric order that you specified on the list display. Although the selected list
information is added for you, you must type the keywords for the statement.
The list function tries to provide qualifications that are necessary for the selected
columns, tables, and SQL packages. However, sometimes the list function cannot
determine the intent of the SQL statement. You need to review the SQL statement
and verify that the selected columns, tables, and SQL packages are properly
qualified.
284
4. Press F17=Select tables to obtain a list of tables, because you want the table
name to follow FROM.
Instead of a list of tables appearing as you expected, a list of collections
appears (the Select and Sequence Collections display). You have just entered
the SQL session and have not selected a collection to work with.
5. Type a 1 in the Seq column next to YOURCOLL2 collection.
Select and Sequence Collections
Type sequence numbers (1-999) to select collections, press Enter.
Seq
1
Collection
YOURCOLL1
YOURCOLL2
YOURCOLL3
YOURCOLL4
Type
SYS
SYS
SYS
SYS
Text
Company benefits
Employee personal data
Job classifications/requirements
Company insurances
6. Press Enter.
The Select and Sequence Tables display appears, showing the tables existing in
the YOURCOLL2 collection.
7. Type a 1 in the Seq column next to PEOPLE table.
Select and Sequence Tables
Type sequence numbers (1-999) to select tables, press Enter.
Seq
1
Table
EMPLCO
PEOPLE
EMPLEXP
EMPLEVL
EMPLBEN
EMPLMED
EMPLINVST
Collection
YOURCOLL2
YOURCOLL2
YOURCOLL2
YOURCOLL2
YOURCOLL2
YOURCOLL2
YOURCOLL2
Type Text
TAB
Employee company data
TAB
Employee personal data
TAB
Employee experience
TAB
Employee evaluation reports
TAB
Employee benefits record
TAB
Employee medical record
TAB
Employee investments record
8. Press Enter.
285
The Enter SQL Statements display appears again with the table name,
YOURCOLL2.PEOPLE, inserted after FROM. The table name is qualified by the
collection name in the *SQL naming convention.
Enter SQL Statements
Type SQL statement, press Enter.
===> SELECT
FROM YOURCOLL2.PEOPLE _
Table
PEOPLE
PEOPLE
PEOPLE
PEOPLE
PEOPLE
PEOPLE
PEOPLE
Type
CHARACTER
CHARACTER
CHARACTER
CHARACTER
CHARACTER
CHARACTER
CHARACTER
Digits
Length
6
30
11
30
20
9
20
286
From this display you can change session attributes and print, clear, or save the
session to a source file.
Option 1 (Change session attributes) displays the Change Session Attributes
display, which allows you to select the current values that are in effect for your
interactive SQL session. The options shown on this display change based on the
statement processing option selected.
The following session attributes can be changed:
v Commitment control attributes.
v The statement processing control.
v The SELECT output device.
v The list of collections.
v The list type to select either all your system and SQL objects, or only your SQL
objects.
v The data refresh option when displaying data.
v The allow copy data option.
v The naming option.
v The programming language.
v The date format.
v The time format.
v The date separator.
v The time separator.
v The decimal point representation.
v The SQL string delimiter.
v The sort sequence.
v The language identifier.
Option 2 (Print current session) accesses the Change Printer display, which lets you
print the current session immediately and then continue working. You are
prompted for printer information. All the SQL statements you entered and all the
messages displayed are printed just as they appear on the Enter SQL Statements
display.
Option 3 (Remove all entries from current session) lets you remove all the SQL
statements and messages from the Enter SQL Statements display and the session
history. You are prompted to ensure that you really want to delete the information.
Option 4 (Save session in source file) accesses the Change Source File display,
which lets you save the session in a source file. You are prompted for the source
file name. This function lets you embed the source file into a host language
program by using the source entry utility (SEU).
Note: Option 4 allows you to embed prototyped SQL statements in a high-level
language (HLL) program that uses SQL. The source file created by option 4
may be edited and used as the input source file for the Run SQL Statements
(RUNSQLSTM) command.
287
288
v Delete the old session and start a new session by selecting option 2 (Delete
existing SQL session and start a new session).
If you choose to delete the old session and continue with the new session, the
parameters you specified when you entered STRSQL are used. If you choose to
recover the old session, or are entering a previously saved session, the parameters
you specified when you entered STRSQL are ignored and the parameters from the
old session are used. A message is returned to indicate which parameters were
changed from the specified value to the old session value.
Original Value
New Value
Date Format
*YMD
*ISO
*EUR
*USA
*USA
*DMY
*MDY
*JUL
Time Format
*JIS
*EUR
Commitment Control
*CHG,
*NONE
*ALL
Naming Convention
*SYS
*SQL
*NO, *YES
*OPTIMIZE
Data Refresh
*ALWAYS
*FORWARD
Chapter 17. Using Interactive SQL
289
Original Value
New Value
Decimal Point
*SYSVAL
*PERIOD
Sort Sequence
*HEX
Notes:
1. If connecting to an AS/400 system that is running a release prior to Version 2
Release 3, the sort sequence value changes to *HEX.
2. When connecting to a DB2/2 or DB2/6000 application server, the date and time
formats specified must be the same format.
After the connection is completed, a message is sent stating that the session
attributes have been changed. The changed session attributes can be displayed by
using the session services display. While interactive SQL is running, no other
connection can be established for the default activation group.
When connected to a remote system with interactive SQL, a statement processing
mode of syntax-only checks the syntax of the statement against the syntax
supported by the local system instead of the remote system. Similarly, the SQL
prompter and list support use the statement syntax and naming conventions
supported by the local system. The statement is run, however, on the remote
system. Because of differences in the level of SQL support between the two
systems, syntax errors may be found in the statement on the remote system at run
time.
Lists of collections and tables are available when you are connected to the local
relational database. Lists of columns are available only when you are connected to
a relational database manager that supports the DESCRIBE TABLE statement.
When you exit interactive SQL with connections that have pending changes or
connections that use protected conversations, the connections remain. If you do not
perform additional work over the connections, the connections are ended during
the next COMMIT or ROLLBACK operation. You can also end the connections by
doing a RELEASE ALL and a COMMIT before exiting interactive SQL.
Using interactive SQL for remote access to non-DB2 for AS/400 application servers
can require some setup. For more information, see the Distributed Database
Programming book.
Note: In the output of a communications trace, there may be a reference to a
CREATE TABLE XXX statement. This is used to determine package
existence; it is part of normal processing, and can be ignored.
290
COMMENT ON
COMMIT
CREATE ALIAS
CREATE COLLECTION
CREATE INDEX
CREATE PROCEDURE
CREATE SCHEMA
v CREATE TABLE
v
v
v
v
v
CREATE VIEW
DELETE
DROP
GRANT (Package Privileges)
GRANT (Procedure Privileges)
LABEL ON
LOCK TABLE
RENAME
REVOKE (Package Privileges)
In the source member, statements end with a semicolon and do not begin with
EXEC SQL. If the record length of the source member is longer than 80, only the
first 80 characters will be read. Comments in the source member can be either line
comments or block comments. Line comments begin with a double hyphen ()
and end at the end of the line. Block comments start with /* and can continue
across many lines until the next */ is reached. Block comments can be nested. Only
SQL statements and comments are allowed in the source file. The output listing
and the resulting messages for the SQL statements are sent to a print file. The
default print file is QSYSPRT.
291
To perform syntax checking only on all statements in the source member, specify
the PROCESS(*SYN) parameter on the RUNSQLSTM command.
292
v
v
v
v
CREATE ALIAS
GRANT (Table Privileges)
COMMENT ON
LABEL ON
These statements follow directly after the first section of the statement. The
statements and sections are not separated by semicolons. If other SQL statements
follow this schema definition, the last statement in the schema must be ended by a
semicolon.
All objects created or referenced in the second part of the schema statement must
be in the collection that was created for the schema. All unqualified references are
implicitly qualified by the collection that was created. All qualified references must
be qualified by the created collection.
SCHEMA
04/01/98 15:35:18
Page
293
SEQNBR
04/01/98 15:35:18
Last change
Page
SEQNBR
04/01/98 15:35:18
Last change
Page
294
Security
All objects on the AS/400 system, including SQL objects, are managed by the
system security function. Users may authorize SQL objects through either the SQL
GRANT and REVOKE statements or the CL commands Edit Object Authority
(EDTOBJAUT), Grant Object Authority (GRTOBJAUT), and Revoke Object
Authority (RVKOBJAUT). For more information on system security and the use of
the GRTOBJAUT and RVKOBJAUT commands, see the Security - Reference book.
The SQL GRANT and REVOKE statements operate on SQL packages, SQL
procedures, tables, views, and the individual columns of tables and views.
Furthermore, SQL GRANT and REVOKE statements only grant private and public
authorities. In some cases, it is necessary to use EDTOBJAUT, GRTOBJAUT, and
RVKOBJAUT to authorize users to other objects, such as commands and programs.
For more information on the GRANT and REVOKE statements, see the DB2 for
AS/400 SQL Reference book.
The authority checked for SQL statements depends on whether the statement is
static, dynamic, or being run interactively.
For static SQL statements:
v If the USRPRF value is *USER, the authority to run the SQL statement locally is
checked using the user profile of the user running the program. The authority to
run the SQL statement remotely is checked using the user profile at the
application server. *USER is the default for system (*SYS) naming.
v If the USRPRF value is *OWNER, the authority to run the SQL statement locally
is checked using the user profiles of the user running the program and of the
owner of the program. The authority to run the SQL statement remotely is
checked using the user profiles of the application server job and the owner of
the SQL package. The higher authority is the authority that is used. *OWNER is
the default for SQL (*SQL) naming.
For dynamic SQL statements:
v If the USRPRF value is *USER, the authority to run the SQL statement locally is
checked using the user profile of the person running the program. The authority
to run the SQL statement remotely is checked using the user profile of the
application server job.
v If the USRPRF value is *OWNER and DYNUSRPRF is *USER, the authority to
run the SQL statement locally is checked using the user profile of the person
running the program. The authority to run the SQL statement remotely is
checked using the user profile of the application server job.
v If the USRPRF value is *OWNER and DYNUSRPRF is *OWNER, the authority to
run the SQL statement locally is checked using the user profiles of the user
running the program and the owner of the program. The authority to run the
SQL statement remotely is checked using the user profiles of the application
Copyright IBM Corp. 1997, 1998
295
server job and the owner of the SQL package. The highest authority is the
authority that is used. Because of security concerns, you should use the
*OWNER parameter value for DYNUSRPRF carefully. This option gives the
access authority of the owner program or package to those who run the
program.
For interactive SQL statements, authority is checked against the authority of the
person processing the statement. Adopted authority is not used for interactive SQL
statements.
Authorization ID
The authorization ID identifies a unique user and is a user profile object on the
AS/400 system. Authorization IDs can be created using the system Create User
Profile (CRTUSRPRF) command.
Views
A view can prevent unauthorized users from having access to sensitive data. The
application program can access the data it needs in a table, without having access
to sensitive or restricted data in the table. A view can restrict access to particular
columns by not specifying those columns in the SELECT list (for example,
employee salaries). A view can also restrict access to particular rows in a table by
specifying a WHERE clause (for example, allowing access only to the rows
associated with a particular department number).
Auditing
DB2 for AS/400 is designed to comply with the U.S. government C2 security level.
A key feature of that level is the ability to audit actions on the system. DB2 for
AS/400 uses the audit facilities managed by the system security function. Auditing
can be performed on an object level, user, or system level. The system value
QAUDCTL controls whether auditing is performed at the object or user level. The
Change User Audit (CHGUSRAUD) command and Change Object Audit
(CHGOBJAUD) command specify which users and objects are audited. The system
value QAUDLVL controls what types of actions are audited (for example,
authorization failures, creates, deletes, grants, revokes, etc.) For more information
on auditing see the Security - Reference book.
DB2 for AS/400 can also audit row changes by using the DB2 for AS/400 journal
support.
In some cases, entries in the auditing journal will not be in the same order as they
occured. For example, a job that is running under commitment control deletes a
table, creates a new table with the same name as the one that was deleted, then
does a commit. This will be recorded in the auditing journal as a create followed
by a delete. This is because objects that are created are journalled immediately. An
object that is deleted under commitment control is hidden and not actually deleted
until a commit is done. Once the commit is done, the action is journaled.
|
|
|
|
|
|
296
Data Integrity
Data integrity protects data from being destroyed or changed by unauthorized
persons, system operation or hardware failures (such as physical damage to a
disk), programming errors, interruptions before a job is completed (such as a
power failure), or interference from running applications at the same time (such as
serialization problems). Data integrity is ensured by the following functions:
v Concurrency
v Journaling
v Commitment control
v Atomic operations
v
v
v
v
Constraints
Save/restore
Damage tolerance
Index recovery
The DB2 for AS/400 Database Programming book and the Backup and Recovery book
contain more information about each of these functions.
Concurrency
Concurrency is the ability for multiple users to access and change data in the same
table or view at the same time without risk of losing data integrity. This ability is
automatically supplied by the DB2 for AS/400 database manager. Locks are
implicitly acquired on tables and rows to protect concurrent users from changing
the same data at precisely the same time.
Typically, DB2 for AS/400 will acquire locks on rows to ensure integrity. However,
some situations require DB2 for AS/400 to acquire a more exclusive table level lock
instead of row locks. For more information see Commitment Control on page 299
.
In some cases, the program may acquire locks that prevent other statements in the
same program from running. For example, an update (exclusive) lock on a row
currently held by one cursor can be acquired by another cursor in the same
program (or in a DELETE or UPDATE statement not associated with the cursor).
This will prevent a positioned UPDATE or positioned DELETE statement that
references the first cursor until another FETCH is performed. A read (shared
no-update) lock on a row currently held by one cursor will not prevent another
cursor in the same program (or DELETE or UPDATE statement) from acquiring a
lock on the same row.
Default and user-specifiable lock-wait time-out values are supported. DB2 for
AS/400 creates tables, views, and indexes with the default record wait time (60
seconds) and the default file wait time (*IMMED). This lock wait time is used for
DML statements. You can change these values by using the CL commands Change
Physical File (CHGPF), Change Logical File (CHGLF), and Override Database File
(OVRDBF).
The lock wait time used for all DDL statements and the LOCK TABLE statement, is
the job default wait time (DFTWAIT). You can change this value by using the CL
commands Change Job (CHGJOB) or Change Class (CHGCLS).
297
In the event that a large record wait time is specified, deadlock detection is
provided. For example, assume one job has an exclusive lock on row 1 and another
job has an exclusive lock on row 2. If the first job attempts to lock row 2, it will
wait because the second job is holding the lock. If the second job then attempts to
lock row 1, DB2 for AS/400 will detect that the two jobs are in a deadlock and an
error will be returned to the second job.
You can explicitly prevent other users from using a table at the same time by using
the SQL LOCK TABLE statement, which is described in the DB2 for AS/400 SQL
Reference book. Using COMMIT(*RR) will also prevent other users from using a
table during a unit of work.
In order to improve performance, DB2 for AS/400 will frequently leave the open
data path (ODP) open (for more information see Improving Performance by
Reducing the Number of Open Database Operations on page 376). This
performance feature also leaves a lock on tables referenced by the ODP, but does
not leave any locks on rows. A lock left on a table may prevent another job from
performing an operation on that table. In most cases, however, DB2 for AS/400
will detect that other jobs are holding locks and events will be signalled to those
jobs. The event causes DB2 for AS/400 to close any ODPs (and release the table
locks) that are associated with that table and are currently only open for
performance reasons. Note that the lock wait time out must be large enough for
the events to be signalled and the other jobs to close the ODPs or an error will be
returned.
Unless the LOCK TABLE statement is used to acquire table locks, or either
COMMIT(*ALL) or COMMIT(*RR) is used, data which has been read by one job
can be immediately changed by another job. Usually, the data that is read at the
time the SQL statement is executed and therefore it is very current (for example,
during FETCH). In the following cases, however, data is read prior to the execution
of the SQL statement and therefore the data may not be current (for example,
during OPEN).
v ALWCPYDTA(*OPTIMIZE) was specified and the optimizer determined that
making a copy of the data would perform better than not making a copy.
v Some queries require the database manager to create a temporary result table.
The data in the temporary result table will not reflect changes made after the
cursor was opened. A temporary result table is required when:
The total length in bytes of storage for the columns specified in an ORDER
BY clause exceeds 2000 bytes.
ORDER BY and GROUP BY clauses specify different columns or columns in a
different order.
UNION or DISTINCT clauses are specified.
ORDER BY or GROUP BY clauses specify columns which are not all from the
same table.
Joining a logical file defined by the JOINDFT data definition specifications
(DDS) keyword with another file.
Joining or specifying GROUP BY on a logical file which is based on multiple
database file members.
The query contains a join in which at least one of the files is a view which
contains a GROUP BY clause.
The query contains a GROUP BY clause which references a view that contains
a GROUP BY clause.
v A basic subquery is evaluated when the query is opened.
298
Journaling
The DB2 for AS/400 journal support supplies an audit trail and forward and
backward recovery. Forward recovery can be used to take an older version of a
table and apply the changes logged on the journal to the table. Backward recovery
can be used to remove changes logged on the journal from the table.
When an SQL collection is created, a journal and journal receiver are created in the
collection. When SQL creates the journal and journal receiver, they are only created
on a user auxiliary storage pool (ASP) if the ASP clause is specified on the
CREATE COLLECTION or the CREATE SCHEMA statement. However, because
placing journal receivers on their own ASPs can improve performance, the person
managing the journal might want to create all future journal receivers on a
separate ASP.
When a table is created into the collection, it is automatically journaled to the
journal DB2 for AS/400 created in the collection (QSQJRN). A table created in a
non-collection will also have journaling started if a journal named QSQJRN exists
in that library. After this point, it is your responsibility to use the journal functions
to manage the journal, the journal receivers, and the journaling of tables to the
journal. For example, if a table is moved into a collection, no automatic change to
the journaling status occurs. If a table is restored, the normal journal rules apply.
That is, if the table was journaled at the time of the save, it is journaled to the
same journal at restore time. If the table was not journaled at the time of the save,
it is not journaled at restore time.
The journal created in the SQL collection is normally the journal used for logging
all changes to SQL tables. You can, however, use the system journal functions to
journal SQL tables to a different journal. This may be necessary if a table in one
collection is a parent to a table in another collection. This is because DB2 for
AS/400 requires that the parent and dependent file in a referential constraint be
journaled to the same journal when updates or deletes are performed to the parent
table.
A user can stop journaling on any table using the journal functions, but doing so
prevents an application from running under commitment control. If journaling is
stopped on a parent table of a referential constraint with a delete rule of NO
ACTION, CASCADE, SET NULL, or SET DEFAULT, all update and delete
operations will be prevented. Otherwise, an application is still able to function if
you have specified COMMIT(*NONE); however, this does not provide the same
level of integrity that journaling and commitment control provide.
Commitment Control
The DB2 for AS/400 commitment control support provides a means to process a
group of database changes (updates, inserts, DDL operations, or deletes) as a single
unit of work (transaction). A commit operation guarantees that the group of
operations is completed. A rollback operation guarantees that the group of
operations is backed out. A commit operation can be issued through several
different interfaces. For example,
v An SQL COMMIT statement
v A CL COMMIT command
v A language commit statement (such as an RPG COMMIT statement)
299
14. Note that the LCKLVL specified is only the default lock level. After commitment control is started, the SET TRANSACTION SQL
statement and the lock level specified on the COMMIT parameter on the CRTSQLxxx, STRSQL, or RUNSQLSTM commands will
override the default lock level.
300
FETCH (read-only
cursor)
COMMIT Parameter
(See note 6)
Lock Type
*NONE
*CHG
*CS (See note 8)
*ALL (See note 2)
No locks
No locks
Row locked when read and released
From read until ROLLBACK or COMMIT
READ
READ
*NONE
*CHG
*CS (See note 8)
*ALL (See note 2)
No locks
No locks
From read until the next FETCH
From read until ROLLBACK or COMMIT
READ
READ
301
COMMIT Parameter
(See note 6)
Lock Type
UPDATE
*ALL
*NONE
*CHG
*CS
*ALL
No locks
From insert until ROLLBACK or COMMIT
From insert until ROLLBACK or COMMIT
From insert until ROLLBACK or COMMIT
UPDATE
UPDATE
UPDATE4
INSERT (tables in
subselect)
*NONE
*CHG
*CS
*ALL
No locks
No locks
Each record locked while being read
From read until ROLLBACK or COMMIT
READ
READ
UPDATE (non-cursor)
*NONE
*CHG
*CS
*ALL
updated
COMMIT
COMMIT
COMMIT
UPDATE
UPDATE
UPDATE
UPDATE
DELETE (non-cursor)
*NONE
*CHG
*CS
*ALL
deleted
COMMIT
COMMIT
COMMIT
UPDATE
UPDATE
UPDATE
UPDATE
*NONE
*CHG
*CS
*ALL
UPDATE
UPDATE
UPDATE
UPDATE
*NONE
*CHG
*CS
*ALL
UPDATE
UPDATE
UPDATE
UPDATE
Subqueries (update or
delete capable cursor or
UPDATE or DELETE
non-cursor)
*NONE
*CHG
*CS
*ALL (see note 2)
From
From
From
From
next FETCH
next FETCH
next FETCH
ROLLBACK or COMMIT
READ
READ
READ
READ
Subqueries (read-only
cursor or SELECT
INTO)
*NONE
*CHG
*CS
*ALL
No locks
No locks
Each record locked while being read
From read until ROLLBACK or COMMIT
READ
READ
FETCH (update or
delete capable cursor)
(See note 1)
*NONE
*CHG
*CS
302
read
read
read
read
until
until
until
until
UPDATE
UPDATE
UPDATE3
COMMIT Parameter
(See note 6)
Lock Type
Notes:
1. A cursor is open with UPDATE or DELETE capabilities if the result table is not read-only (see description of
DECLARE CURSOR in DB2 for AS/400 SQL Reference book) and if one of the following is true:
v The cursor is defined with a FOR UPDATE clause.
v The cursor is defined without a FOR UPDATE, FOR READ ONLY, or ORDER BY clause and the program
contains at least one of the following:
Cursor UPDATE referring to the same cursor-name
Cursor DELETE referring to the same cursor-name
An EXECUTE or EXECUTE IMMEDIATE statement and ALWBLK(*READ) or ALWBLK(*NONE) was
specified on the CRTSQLxxx command.
2. A table or view can be locked exclusively in order to satisfy COMMIT(*ALL). If a subselect is processed that
includes a UNION, or if the processing of the query requires the use of a temporary result, an exclusive lock is
acquired to protect you from seeing uncommitted changes.
3. If the row is not updated or deleted, the lock is reduced to *READ.
4. An UPDATE lock on rows of the target table and a READ lock on the rows of the subselect table.
5. A table or view can be locked exclusively in order to satisfy repeatable read. Row locking is still done under
repeatable read. The locks acquired and their duration are identical to *ALL.
6. Repeatable read (*RR) record locks will be the same as the locks indicated for *ALL.
7. For a detailed explanation of isolation levels and locking, see the section entitled Isolation Level in Chapter 1
of the DB2 for AS/400 SQL Reference book.
8. If the KEEP LOCKS clause is specified with *CS, any read locks are held until the cursor is closed or until a
COMMIT or ROLLBACK is done. If no cursors are associated with the isolation clause, then locks are held until
the completion of the SQL statement.
Atomic Operations
When running under COMMIT(*CHG), COMMIT(*CS), or COMMIT(*ALL), all
operations are guaranteed to be atomic. That is, they will complete or they will
appear not to have started. This is true regardless of when or how the function
was ended or interrupted (such as power failure, abnormal job end, or job cancel).
If COMMIT (*NONE) is specified, however, some underlying database data
definition functions are not atomic. The following SQL data definition statements
are guaranteed to be atomic:
ALTER TABLE (See note 1)
COMMENT ON (See note 2)
CREATE PROCEDURE
LABEL ON (See note 2)
GRANT (See note 3)
REVOKE (See note 3)
DROP TABLE (See note 4)
DROP VIEW (See note 4)
DROP INDEX
DROP PACKAGE
DROP PROCEDURE
303
Notes:
1. If constraints need to be added or removed, as well as column definitions
changed, the operations are processed one at a time, so the entire SQL
statement is not atomic. The order of operation is:
v remove constraints
v drop columns for which the RESTRICT option was specified
v all other column definition changes (DROP COLUMN CASCADE, ALTER
COLUMN, ADD COLUMN)
v add constraints
2. If multiple columns are specified for a COMMENT ON or LABEL ON
statement, the columns are processed one at a time, so the entire SQL statement
is not atomic, but the COMMENT ON or LABEL ON to each individual
column or object will be atomic.
3. If multiple tables, SQL packages, or users are specified for a GRANT or
REVOKE statement, the tables are processed one at a time, so the entire SQL
statement is not atomic, but the GRANT or REVOKE to each individual table
will be atomic.
4. If dependent views need to be dropped during DROP TABLE or DROP VIEW,
each dependent view is processed one at a time, so the entire SQL statement is
not atomic.
The following data definition statements are not atomic because they involve more
than one DB2 for AS/400 database operation:
CREATE ALIAS
CREATE COLLECTION
CREATE TABLE
CREATE VIEW
CREATE INDEX
CREATE SCHEMA
DROP ALIAS
DROP COLLECTION
DROP SCHEMA
RENAME (See note 1)
|
Notes:
|
|
1. RENAME is atomic only if the name or the system name is changed. When
both are changed, the RENAME is not atomic.
For example, a CREATE TABLE can be interrupted after the DB2 for AS/400
physical file has been created, but before the member has been added. Therefore,
in the case of create statements, if an operation ends abnormally, you may have to
drop the object and then create it again. In the case of a DROP COLLECTION
statement, you may have to drop the collection again or use the CL command
Delete Library (DLTLIB) to remove the remaining parts of the collection.
Constraints
DB2 for AS/400 supports unique, referential, and check constraints. A unique
constraint is a rule that guarantees that the values of a key are unique. A
referential constraint is a rule that all non-null values of foreign keys in a
304
Save/Restore
The AS/400 save/restore functions are used to save tables, views, indexes,
journals, journal receivers, SQL packages, SQL procedures, and collections on disk
(save file) or to some external media (tape or diskette). The saved versions can be
restored onto any AS/400 system at some later time. The save/restore function
allows an entire collection, selected objects, or only objects changed since a given
date and time to be saved. All information needed to restore an object to its
previous state is saved. This function can be used to recover from damage to
individual tables by restoring the data with a previous version of the table or the
entire collection.
When a program that was created for an SQL procedure is restored, it is
automatically added to the SYSPROCS and SYSPARMS catalogs, as long as a
procedure does not already exist with the same name. SQL programs created in
QSYS will not be created as SQL procedures when restored.
Either a distributed SQL program or its associated SQL package can be saved and
restored to any number of AS/400 systems. This allows any number of copies of
the SQL programs on different systems to access the same SQL package on the
same application server. This also allows a single distributed SQL program to
connect to any number of application servers that have the SQL package restored
(CRTSQLPKG can also be used). SQL packages cannot be restored to a different
library.
Attention: Restoring a collection to an existing library or to a collection that has a
different name does not restore the journal, journal receivers, or IDDU dictionary
(if one exists). If the collection is restored to a collection with a different name, the
catalog views in that collection will only reflect objects in the old collection. The
catalog views in QSYS2, however, will appropriately reflect all objects.
Damage Tolerance
The AS/400 system provides several mechanisms to reduce or eliminate damage
caused by disk errors. For example, mirroring, checksums, and RAID disks can all
305
reduce the possibility of disk problems. The DB2 for AS/400 functions also have a
certain amount of tolerance to damage caused by disk errors or system errors.
A DROP operation always succeeds, regardless of the damage. This ensures that
should damage occur, at least the table, view, SQL package, or index can be
deleted and restored or created again.
In the event that a disk error has damaged a small portion of the rows in a table,
the DB2 for AS/400 database manager allows you to read rows still accessible.
Index Recovery
DB2 for AS/400 supplies several functions to deal with index recovery.
v System managed index protection
The EDTRCYAP CL command allows a user to instruct DB2 for AS/400 to
guarantee that in the event of a system or power failure, the amount of time
required to recover all indexes on the system is kept below a specified time. The
system automatically journals enough information in a system journal to limit
the recovery time to the specified amount.
v Journaling of indexes
DB2 for AS/400 supplies an index journaling function that makes it unnecessary
to rebuild an entire index due to a power or system failure. If the index is
journaled, the system database support automatically makes sure the index is in
synchronization with the data in the tables without having to rebuild it from
scratch. SQL indexes are not journaled automatically. You can, however, use the
CL command Start Journal Access Path (STRJRNAP) to journal any index
created by DB2 for AS/400.
v Index rebuild
All indexes on the system have a maintenance option that specifies when an
index is maintained. SQL indexes are created with an attribute of *IMMED
maintenance.
In the event of a power failure or abnormal system failure, if indexes were not
protected by one of the previously described techniques, those indexes in the
process of change may need to be rebuilt by the database manager to make sure
they agree with the actual data. All indexes on the system have a recovery
option that specifies when an index should be rebuilt if necessary. All SQL
indexes with an attribute of UNIQUE are created with a recovery attribute of
*IPL (this means that these indexes are rebuilt before the OS/400 has been
started). All other SQL indexes are created with the *AFTIPL recovery option
(this means that after the operating system has been started, indexes are
asynchronously rebuilt). During an IPL, the operator can see a display showing
indexes needing to be rebuilt and their recovery option. The operator can
override the recovery options.
v Save and restore of indexes
The save/restore function allows you to save indexes when a table is saved by
using ACCPTH(*YES) on the Save Object (SAVOBJ) or Save Library (SAVLIB) CL
commands. In the event of a restore when the indexes have also been saved,
there is no need to rebuild the indexes. Any indexes not previously saved and
restored are automatically and asynchronously rebuilt by the database manager.
306
Catalog Integrity
Catalogs contain information about tables, views, SQL packages, indexes,
procedures, and parameters in a collection. The database manager ensures that the
information in the catalog is accurate at all times. This is accomplished by
preventing end users from explicitly changing any information in the catalog and
by implicitly maintaining the information in the catalog when changes occur to the
tables, views, SQL packages, indexes, procedures, and parameters described in the
catalog.
The integrity of the catalog is maintained whether objects in the collection are
changed by SQL statements, OS/400 CL commands, System/38 Environment CL
commands, System/36 Environment functions, or any other product or utility on
an AS/400 system. For example, deleting a table can be done by running an SQL
DROP statement, issuing an OS/400 DLTF CL command, issuing a System/38
DLTF CL command or entering option 4 on a WRKF or WRKOBJ display.
Regardless of the interface used to delete the table, the database manager will
remove the description of the table from the catalog at the time the delete is
performed. The following is a list of functions and the associated effect on the
catalog:
Table 37. Effect of Various Functions on Catalogs
Function
Rename of object
307
308
309
v Test tables. When your application creates, changes, or deletes data, you will
probably want to test the application by using tables that contain test data. See
Chapter 2. Getting Started with SQL for a description of how to create tables and
views.
Also, you might want to use the CL command Create Duplicate Object
(CRTDUPOBJ) to create a duplicate test table, view, or index.
Authorization
Before you can create a table, you must be authorized to create tables and to use
the collection in which the table is to reside. In addition, you must have authority
to create and run the programs you want to test.
If you intend to use existing tables and views (either directly or as the basis for a
view), you must be authorized to access those tables and views.
If you want to create a view, you must be authorized to create views and must
have authorization to each table and view on which the view is based. For more
information on specific authorities required for any specific SQL statement, see the
DB2 for AS/400 SQL Reference book.
310
SQL will always put messages in the job log for negative SQLCODEs and positive
codes other than +100 regardless of whether it is in debug mode or not.
DSPJOB
311
TRCJOB
312
v
v
v
v
v
v
v
v
v
v
v
v
v
v
v
v
v
v
CPI4330
CPI4331
CPI4332
CPI4333
CPI4334
v
v
v
v
v
v
v
CPI4335
CPI4336
CPI4337
CPI4338
CPI4341
CPI4342
CPI4345
v
v
v
v
v
v
313
314
315
If the query uses the JOIN clause or refers to a join logical file within the file
specifications, the order in which the files are specified will help determine the join
order the optimizer uses. The optimizer cannot change the file join order if the
query contains a join logical file, or if either a left outer or exception join is
specified using the JOIN clause.
CPI4327 - File &1 processed in join position 1.
This message provides the name of the first or primary file of the join when arrival
sequence is used to select records from the file.
See the previous message, CPI4326, for information on join position and join
performance tips.
CPI4328 - Access path of file &4 was used by query.
This message names an existing access path that was used by the query.
The reason the access path was used is given in the message help.
CPI4329 - Arrival sequence access was used for file &1.
No access path was used to access the data in the specified file. The records were
scanned sequentially in arrival sequence.
The use of an access path may improve the performance of the query if record
selection is specified.
If an access path does not exist, you may want to create one whose key field
matches one of the fields in the record selection. You should only create an access
path if the record selection (WHERE clause) selects 20% or fewer records in the
file.
To force the use of an existing access path, change the ORDER BY clause of the
query to specify the first key field of the access path.
CPI432A - Query optimizer timed out for file &1.
The optimizer stops considering access paths when the time spent optimizing the
query exceeds an internal value that is associated with the estimated time to run
the query and the number of records in the queried files. Generally, the more
records in the files, the greater the number of access paths that will be considered.
When the estimated time to run the query is exceeded, the optimizer uses the
current best method for running the query. Either an access path has been found to
get the best performance, or an access path will have to be created, if necessary.
Exceeding the estimated time to run the query could mean that the optimizer did
not consider the best access path to run the query.
The message help contains a list of access paths that were considered before the
optimizer exceeded the estimated time.
To ensure that an access path is considered for optimization, specify the logical file
associated with the access path as the file to be queried. The optimizer will
consider the access path of the file specified on the query or SQL statement first.
Remember that SQL indexes cannot be queried.
316
You may want to delete any access paths that are no longer needed.
CPI432B - Subselects processed as join query.
Two or more SQL subselects were combined by the query optimizer and processed
as a join query. Generally, this method of processing is a good performing option.
CPI432C - All access paths were considered for file &1.
The optimizer considered all access paths built over the specified file. Since the
optimizer examined all access paths for the file, it determined the current best
access to the file.
The message help contains a list of the access paths. With each access path a
reason code is added. The reason code explains why the access path was not used.
CPI432D - Additional access path reason codes were used.
Message CPI432A or CPI432C was issued immediately before this message.
Because of message length restrictions, some of the reason codes used by messages
CPI432A and CPI432C are explained in the message help of CPI432D. Use the
message help from this message to interpret the information returned from
message CPI432A or CPI432C.
CPI432E - Selection fields mapped to different attributes.
This message indicates that the query optimizer was not able to consider the usage
of an index to resolve one or more of the selection specifications of the query. If
there was an index available which otherwise could have been used to limit the
processing of the query to just a few rows, then the performance of this query will
be affected.
The attributes of a comparison value and a comparison column must match
otherwise a conversion will occur so that they do match. Generally, this conversion
occurs such that the value with the smallest attributes is mapped to the attributes
of the other value. When the attributes of the comparison column have to be
mapped to be compatible with that of the comparison value, the optimizer can no
longer use an index to implement this selection.
CPI4338 &1 Access path(s) used for bitmap processing of file &2.
The optimizer chooses to use one or more access paths, in conjunction with the
query selection (WHERE clause), to build a bitmap. This resulting bitmap indicates
which records will actually be selected.
Conceptually, the bitmap contains one bit per record in the underlying table.
Corresponding bits for selected records are set to 1. All other bits are set to 0.
Once the bitmap is built, it is used, as appropriate, to avoid mapping in records
from the table not selected by the query. The use of the bitmap depends on
whether the bitmap is used in combination with the arrival sequence or with a
primary access path.
When bitmap processing is used with arrival sequence, either message CPI4327 or
CPI4329 will precede this message. In this case, the bitmap will help to selectively
map only those records from the table that the query selected.
Chapter 20. Testing SQL Statements in Application Programs
317
When bitmap processing is used with a primary access path, either message
CPI4326 or CPI4328 will precede this message. Records selected by the primary
access path will be checked against the bitmap before mapping the record from the
table.
318
319
The statement now refers to different files or uses different override specifications
than are in the existing ODP. The existing ODP cannot be reused, and a new ODP
must be created. To make it possible to reuse the ODP, avoid changing the library
list or the override specifications.
SQL7919 - Data conversion required on FETCH or embedded SELECT.
When mapping data to host variables, data conversions were required. When these
statements are run in the future, they will be slower than if no data conversions
were required. The statement ran successfully, but performance could be improved
by eliminating the data conversion. For example, a data conversion that would
cause this message to occur would be the mapping of a character string of a
certain length to a host variable character string with a different length. You could
also cause this error by mapping a numeric value to a host variable that is a
different type (decimal to integer). To prevent most conversions, use host variables
that are of identical type and length as the columns that are being fetched.
SQL7939 - Data conversion required on INSERT or UPDATE.
The attributes of the INSERT or UPDATE values are different than the attributes of
the columns receiving the values. Since the values must be converted, they cannot
be directly moved into the columns. Performance could be improved if the
attributes of the INSERT or UPDATE values matched the attributes of the columns
receiving the values.
320
321
Cancelling a Query
When a query is expected to run longer than the set time limit, the governor issues
inquiry message CPA4259. The user enters a C to cancel the query or an I to ignore
the time limit and let the query run to completion. If the user enters C, escape
message CPF427F is issued to the SQL runtime code. SQL returns SQLCODE -666.
322
51) RPY(C)
The following example will add a reply list element that will cause the default
reply of C to cancel any requests for jobs whose process name is QPADEV0011.
ADDRPYLE
Examples
To set or change the query time limit for the current job or user session the
CHGQRYA command is run. To set the query time limit for 45 seconds you would
use the following CHGQRYA command:
CHGQRYA
JOB(*) QRYTIMLMT(45)
This sets the query time limit at 45 seconds. If the user runs a query with an
estimated runtime equal to or less than 45 seconds the query runs without
interruption. The time limit remains in effect for the duration of the job or user
session, or until the time limit is changed by the CHGQRYA command.
Assume that the query optimizer estimated the runtime for a query as 135 seconds.
A message would be sent to the user that stated that the estimated runtime of 135
seconds exceeds the query time limit of 45 seconds.
To set or change the query time limit for a job other than your current job, the
CHGQRYA command is run using the JOB parameter. To set the query time limit
to 45 seconds for job 123456/USERNAME/JOBNAME you would use the
following CHGQRYA command:
CHGQRYA
JOB(123456/USERNAME/JOBNAME) QRYTIMLMT(45)
Chapter 21. Using the DB2 for AS/400 Predictive Query Governor
323
324
Chapter 22. DB2 for AS/400 Data Management and the Query
Optimizer
This chapter provides guidelines for designing a program that uses SQL and
system resources more efficiently in application programs. As a general rule, most
of the guidelines can be ignored and the results will still be correct. However, if
you apply the guidelines your programs will run more efficiently.
Note: The information in this chapter is complex. It may be helpful to experiment
with an AS/400 system as you read this chapter to verify some of the
information.
If one understands how DB2 for AS/400 processes queries, it is easier to
understand the performance impacts of the guidelines discussed in this chapter.
There are two major components of DB2 for AS/400:
1. Data management methods
These methods are the algorithms used to retrieve data from the disk. The
methods include index usage and row selection techniques. In addition, parallel
access methods are available with the DB2 Symmetric Multiprocessing
operating system feature.
2. Query optimizer
The query optimizer identifies the valid techniques which could be used to
implement the query and selects the most efficient technique.
Access Path
An access path is the path used to locate data specified in a query. An access path
can be indexed, sequential, or a combination of both.
325
Access Method
The Licensed Internal Code and DB2 for AS/400 share the work on access
methods. The Licensed Internal Code does the low-level processing which includes
selection, join functions, hashing, and access path creation.
The query optimization process chooses the most efficient access method for each
query and keeps this information in the access plan. The type of access is
dependent on the number of rows, the expected number of page faults 15, and
other criteria.
The possible methods the optimizer can use to retrieve data include:
v Dataspace scan method (a dataspace is an internal object that contains the data
in a table) (page 328)
v Parallel pre-fetch method (page 330)
v Key selection method (page 333)
v Key positioning method (page 335)
v Parallel table or index pre-load (page 341)
v Index-from-index method (page 341)
v Index only access method (page 340)
v Hashing method (page 342)
v Bitmap processing method (page 343)
The DB2 Symmetric Multiprocessing feature provides the optimizer with additional
methods for retrieving data that include parallel processing.
Symmetrical multiprocessing (SMP) is a form of parallelism achieved on a single
system where multiple processors (CPU and I/O processors) that share memory
and disk resource work simultaneously towards achieving a single end result. This
parallel processing means that the database manager can have more than one (or
all) of the system processors working on a single query simultaneously. The
performance of a CPU bound query can be significantly improved with this feature
on multiple-processor systems by distributing the processor load across more than
one processor on the system.
15. An interrupt that occurs when a program refers to a 4K-byte page that is not in main storage.
326
QUERY
CPU
CPU
CPU
CPU
SHARED MEMORY
The following methods are available to the optimizer once the DB2 Symmetric
Multiprocessing feature has been installed on your system:
v Parallel data space scan method (page 331)
v Parallel key selection method (page 333)
v Parallel key positioning method (page 338)
v Parallel index only access method (parallel and non-parallel) (page 339)
v Parallel hashing method (parallel and non-parallel) (page 342)
v Parallel bitmap processing method (page 343)
Ordering
An ORDER BY clause must be specified to guarantee a particular ordering of the
results. Before parallel access methods were available, the database manager
processed table rows (and keyed sequences) in a sequential manner. This caused
the sequencing of the results to be somewhat predictable even though an ordering
was not included in the original query request. Because parallel methods cause
blocks of table rows and key values to be processed concurrently, the ordering of
the retrieved results becomes more random and unpredictable. An ORDER BY
clause is the only way to guarantee the specific sequencing of the results. However,
an ordering request should only be specified when absolutely required, because the
sorting of the results can increase both CPU utilization and response time.
327
A set of database system tasks are created at system startup for use by the
database manager. The database manager uses the tasks to process and retrieve
data from different disk devices. Since these tasks can be run on multiple
processors simultaneously, the elapsed time of a query can be reduced. Even
though much of the I/O and CPU processing of a parallel query is done by the
tasks, the accounting of the I/O and CPU resources used are transferred to the
application job. The summarized I/O and CPU resources for this type of
application continue to be accurately displayed by the Work with Active Jobs
(WRKACTJOB) command.
328
The Licensed Internal Code can use one of two algorithms for selection when a
dataspace scan is processed, intermediate buffer selection and dataspace element
selection.
The following pseudocode illustrates the intermediate buffer selection algorithm:
DO UNTIL END OF FILE
1. Address the next (or first) record
2. Map all column values to an internal buffer, performing all derived
operations.
3. Evaluate the selection criteria to a TRUE or FALSE value using
the column values as they were copied to internal buffer.
4. IF the selection is TRUE
THEN
Copy the values from the internal buffer into the
user's answer buffer.
ELSE
No operation
END
Chapter 22. DB2 for AS/400 Data Management and the Query Optimizer
329
v The loop in step 2 of the dataspace entry selection algorithm is generated into an
executable code burst. When a small percentage of records are actually selected,
DB2 for AS/400 will be running this very small program until a record is found.
No action is necessary for queries of this type to make use of the dataspace scan
method. Any query interface can utilize this improvement. However, the following
guidelines determine whether a selection predicate can be implemented as
dataspace selection:
v Neither operand of the predicate can be of any kind of a derived value, function,
substring, concatenation, or numeric expression.
v When both operands of a selection predicate are numeric columns, both columns
must have the same type, scale, and precision; otherwise, one operand is
mapped into a derived value. For example, a DECIMAL(3,1) must only be
compared against another DECIMAL(3,1) column.
v When one operand of a selection predicate is a numeric column and the other is
a literal or host variable, then the types must be the same and the precision and
scale of the literal/host variable must be less than or equal to that of the
column.
v Selection predicates involving packed decimal or numeric types of columns can
only be done if the table was created by the SQL CREATE TABLE statement.
v A varying length character column cannot be referenced in the selection
predicate.
v When one operand of a selection predicate is a character column and the other
is a literal or host variable, then the length of the host variable cannot be greater
than that of the column.
v Comparison of character column data must not require CCSID or key board shift
translation.
It can be important to avoid intermediate buffer selection because the reduction in
CPU and response time for dataspace entry selection can be large, in some cases as
high as 70-80%. The queries that will benefit the most from dataspace selection are
those where less than 60% of the file is actually selected. The lower the percentage
of records selected, the more noticeable the performance benefit will be.
330
sequential access to the data. Because of this optimization, parallel prefetch can
pre-load data to active memory faster than the SETOBJACC CL command.
Even though DB2 for AS/400 spreads data across disk devices within an ASP,
sometimes the allocation of the dataspace extents may not be spread evenly. This
occurs when there is uneven allocation of space on the devices or a new device is
added to the ASP. The allocation of the dataspace can be respread by saving,
deleting, and restoring the table.
The query optimizer selects the candidate queries which can take advantage of this
type of implementation. The optimizer selects the candidates by estimating the
CPU time required to process the query and comparing the estimate to the amount
of time required for input processing. When the estimated input processing time
exceeds the CPU time, the query optimizer indicates that the query may be
implemented with parallel I/O.
Parallel pre-fetch requires that I/O parallel processing must be enabled either by
the system value QQRYDEGREE or by the DEGREE parameter on the Change
Query Attributes (CHGQRYA) command. See Controlling Parallel Processing on
page 391 for information on how to control parallel processing. Because queries
being processed with parallel pre-fetch aggressively utilize main store and disk
I/O resources, the number of queries that use parallel pre-fetch should be limited
and controlled. Parallel prefetch utilizes multiple disk arms, but it does little
utilization of multiple CPUs for any given query. Parallel prefetch I/O will use I/O
resources intensely. Allowing a parallel prefetch query on a system with an
overcommitted I/O subsystem may intensify the over-commitment problem.
You should run the job in a shared storage pool with the *CALC paging option
because this will cause more efficient use of active memory. DB2 for AS/400 uses
the automated system tuner to determine how much memory this process is
allowed to use. At run-time, the Licensed Internal Code will allow parallel
pre-fetch to be used only if the memory statistics indicate that it will not
over-commit the memory resources. For more information on the paging option see
the Automatic System Tuning section of the Work Management book.
Parallel pre-fetch requires that enough main storage be available to cache the data
being retrieved by the multiple input streams. For large files, the typical extent size
is 1 megabyte. This means that 2 megabytes of memory must be available in order
to use 2 input streams concurrently. Increasing the amount of available memory in
the pool allows more input streams to be used. If there is plenty of available
memory, the entire dataspace for the table may be loaded into active memory
when the query is opened.
The messages created by the PRTSQLINF command to describe a query in an SQL
program which is using the parallel pre-fetch access method would appear as
follows:
SQL4023
Parallel Data Space Scan Method (available only when the DB2
Symmetric Multiprocessing feature is installed)
DB2 for AS/400 can use this parallel access method to shorten the processing time
required for long-running data space scan queries. The parallel data space scan
method reduces the I/O processing time like the parallel pre-fetch access method.
In addition, if running on a system that has more than one processor, this method
can reduce the elapsed time of a query by splitting the data space scan processing
Chapter 22. DB2 for AS/400 Data Management and the Query Optimizer
331
into tasks that can be run on the multiple processors simultaneously. All selection
and column processing is performed in the task. The applications job schedules
the work requests to the tasks and merges the results into the result buffer that is
returned to the application.
This method is most effective when the following are true:
v The data is spread across multiple disk devices.
v The system has multiple processors that are available.
v There is an ample amount of main storage available to hold the data buffers and
result buffers.
As mentioned earlier, DB2 for AS/400 automatically spreads the data across the
disk devices without user intervention, allowing the database manager to pre-fetch
table data in parallel.
The query optimizer selects the candidate queries that can take advantage of this
type of implementation. The optimizer selects the candidates by estimating the
CPU time required to process the query and comparing the estimate to the amount
of time required for input processing. The optimizer reduces its estimated elapsed
time for data space scan based on the number of tasks it calculates should be used.
It calculates the number of tasks based on the number of processors in the system,
the amount of memory available in the jobs pool, and the current value of the
DEGREE query attribute. If the parallel data space scan is the fastest access
method, it is then chosen.
Parallel data space scan requires that SMP parallel processing be enabled either by
the system value QQRYDEGREE or by the DEGREE parameter on the Change
Query Attributes (CHGQRYA) command. See Controlling Parallel Processing on
page 391 for information on how to control parallel processing.
Parallel data space scan cannot be used for queries that require any of the
following:
v Specification of the *ALL commitment control level.
v Nested loop join implementation. See Nested Loop Join Implementation on
page 351 .
v Backward scrolling. For example, parallel data space scan cannot normally be
used for queries defined by the Open Query File (OPNQRYF) command. (The
application might attempt to position to the last record and retrieve previous
records.) SQL-defined queries that are not defined as scrollable can use this
method. Parallel data space scan can be used during the creation of a temporary
result, such as a sort or hash operation, no matter what interface was used to
define the query.
v Restoration of the cursor position. For instance, a query requiring that the cursor
position be restored as the result of the SQL ROLLBACK HOLD statement or the
ROLLBACK CL command. SQL applications using a commitment control level
other than *NONE should specify *ALLREAD as the value for precompiler
parameter ALWBLK to allow this method to be used.
v Update or delete capability.
You should run the job in a shared storage pool with the *CALC paging option, as
this will cause more efficient use of active memory. For more information on the
paging option see the Automatic System Tuning section of the Work Management
book.
332
Parallel data space scan requires active memory to buffer the data being retrieved
and to separate result buffers for each task. A typical total amount of memory
needed for each task is about 2 megabytes. For example, about 8 megabytes of
memory must be available in order to use 4 parallel data space scan tasks
concurrently. Increasing the amount of available memory in the pool allows more
input streams to be used. Queries that access tables with large varying length
character columns, or queries that generate result values that are larger than the
actual record length of the table might require more memory for each task.
The performance of parallel data space scan can be severely limited if numerous
record locking conflicts or data mapping errors occur.
Chapter 22. DB2 for AS/400 Data Management and the Query Optimizer
333
If the optimizer chooses to run this query in parallel with a degree of four, the
following might be the logical key partitions that get processed concurrently:
LASTNAME values
leading character
partition start
'A'
'G'
'M'
'T'
LASTNAME values
leading character
partition end
'F'
'L'
'S'
'Z'
If there were fewer keys in the first and second partition, processing of those key
values would complete sooner than the third and fourth partitions. After the first
two partitions are finished, the remaining key values in the last two might be
further split. The following shows the four partitions that might be processed after
the first and second partition are finished and the splits have occurred:
LASTNAME values
leading character
partition start
'O'
'Q'
'V'
'X'
LASTNAME values
leading character
partition end
'P'
'S'
'W'
'Z'
Parallel key selection cannot be used for queries that require any of the following:
v Specification of the *ALL commitment control level.
v Nested loop join implementation. See Nested Loop Join Implementation on
page 351 .
v Backward scrolling. For example, parallel key selection cannot be used for
queries defined by the Open Query File (OPNQRYF) command, because the
application might attempt to position to the last record and retrieve previous
records. SQL defined queries that are not defined as scrollable can use this
method. Parallel key selection can be used during the creation of a temporary
result, such as a sort or hash operation, no matter what interface was used to
define the query.
v Restoration of the cursor position (for instance, a query requiring that the cursor
position be restored as the result of the SQL ROLLBACK HOLD statement or the
334
In this example, the database support uses X1 to position to the first index entry
with the WORKDEPT value equal to E01. For each key equal to E01, it randomly
accesses the dataspace 16 and selects the row. The query ends when the key
selection moves beyond the key value of E01.
16. random accessing occurs because the keys may not be in the same sequence as the rows in the dataspace
Chapter 22. DB2 for AS/400 Data Management and the Query Optimizer
335
Note that for this example all index entries processed and rows retrieved meet the
selection criteria. If additional selection is added that cannot be performed through
key positioning (such as selection columns which do not match the first key
columns of an index over multiple columns) the optimizer uses key selection to
perform as much additional selection as possible. Any remaining selection is
performed at the dataspace level.
The messages created by the PRTSQLINF CL command to describe this query in
an SQL program would appear as follows:
SQL4008
SQL4011
The key positioning access method has additional processing capabilities. One such
capability is to perform range selection across several values. For example:
CREATE INDEX X1 EMPLOYEE(WORKDEPT)
DECLARE BROWSE2 CURSOR FOR
SELECT * FROM EMPLOYEE
WHERE WORKDEPT BETWEEN 'E01' AND 'E11'
OPTIMIZE FOR 99999 ROWS
In the previous example, the database support positions to the first index entry
equal to value E01 and rows are processed until the last index entry for E11 is
processed.
The messages created by PRTSQLINF CL command to describe this query in an
SQL program would appear as follows:
SQL4008
SQL4011
In the previous example, the positioning and processing technique is used twice,
once for each range of values.
The messages created by PRTSQLINF CL command to describe this query in an
SQL program would appear as follows:
SQL4008
SQL4011
All of the key positioning examples have so far only used one key, the left-most
key, of the index. Key positioning also handles more than one key (although the
keys must be contiguous to the left-most key).
CREATE INDEX X2
ON EMPLOYEE(WORKDEPT,LASTNAME,FIRSTNME)
DECLARE BROWSE2 CURSOR FOR
336
Because the two selection keys (WORKDEPT and FIRSTNME) are not contiguous,
there is no multiple key position support for this example. Therefore, only the
WORKDEPT = D11 part of the selection can be applied against the index (single
key positioning). While this may be acceptable, it means that the processing of
rows starts with the first key of D11 and then uses key selection to process the
FIRSTNME = DAVID against all 9 keys with WORKDEPT key value = D11.
By creating the following index, X3, the above example query would run using
multiple key positioning.
CREATE INDEX X3
ON EMPLOYEE(WORKDEPT, FIRSTNME, LASTNAME)
Multiple key positioning support can apply both pieces of selection as key
positioning. This improves performance considerably. A starting value is built by
concatenating the two selection values into D11DAVID and selection is positioned
to the index entry whose left-most two keys have that value.
The messages created by the PRTSQLINF CL command when used to describe this
query in an SQL program would look like this:
SQL4008
SQL4011
This next example shows a more interesting use of multiple key positioning.
CREATE INDEX X3 ON EMPLOYEE(WORKDEPT,FIRSTNME)
DECLARE BROWSE2 CURSOR FOR
SELECT * FROM EMPLOYEE
WHERE WORKDEPT = 'D11'
AND FIRSTNME IN ('DAVID','BRUCE','WILLIAM')"
OPTIMIZE FOR 99999 ROWS
The query optimizer analyzes the WHERE clause and rewrites the clause into an
equivalent form:
DECLARE BROWSE2 CURSOR FOR
SELECT * FROM EMPLOYEE
WHERE (WORKDEPT = 'D11' AND FIRSTNME = 'DAVID')
OR (WORKDEPT = 'D11' AND FIRSTNME = 'BRUCE')
OR (WORKDEPT = 'D11' AND FIRSTNME = 'WILLIAM')
OPTIMIZE FOR 99999 ROWS
In the rewritten form of the query there are actually 3 separate ranges of key
values for the concatenated values of WORKDEPT and FIRSTNME:
Index X3 Start value
'D11DAVID'
'D11BRUCE'
'D11WILLIAM'
Key positioning is performed over each range, significantly reducing the number of
keys selected to just 3. All of the selection can be accomplished through key
positioning.
The complexity of this range analysis can be taken to a further degree in the
following example:
Chapter 22. DB2 for AS/400 Data Management and the Query Optimizer
337
The query optimizer analyzes the WHERE clause and rewrites the clause into an
equivalent form:
DECLARE BROWSE2 CURSOR FOR
SELECT * FROM EMPLOYEE
WHERE (WORKDEPT = 'D11'
OR (WORKDEPT = 'D11'
OR (WORKDEPT = 'D11'
OR (WORKDEPT = 'E11'
OR (WORKDEPT = 'E11'
OR (WORKDEPT = 'A00'
AND
AND
AND
AND
AND
AND
FIRSTNME
FIRSTNME
FIRSTNME
FIRSTNME
FIRSTNME
FIRSTNME
= 'DAVID')
= 'BRUCE')
= 'WILLIAM')
= 'PHILIP')
= 'MAUDE')
BETWEEN
'CHRISTINE' AND 'DELORES')
OR (WORKDEPT = 'C01' AND FIRSTNME BETWEEN
'CHRISTINE' AND 'DELORES')
OPTIMIZE FOR 99999 ROWS
In the query there are actually 7 separate ranges of key values for the concatenated
values of WORKDEPT and FIRSTNME:
Index X3 Start value
'D11DAVID'
'D11BRUCE'
'D11WILLIAM'
'E11MAUDE'
'E11PHILIP'
'A00CHRISTINE'
'C01CHRISTINE'
Key positioning is performed over each range. Only those rows whose key values
fall within one of the ranges are returned. All of the selection can be accomplished
through key positioning. This significantly improves the performance of this query.
338
OR
OR
OR
OR
OR
(WORKDEPT
(WORKDEPT
(WORKDEPT
(WORKDEPT
(WORKDEPT
=
=
=
=
=
'D11'
'D11'
'E11'
'E11'
'A00'
AND
AND
AND
AND
AND
FIRSTNME
FIRSTNME
FIRSTNME
FIRSTNME
FIRSTNME
= 'BRUCE')
= 'WILLIAM')
= 'PHILIP')
= 'MAUDE')
BETWEEN
'CHRISTINE' AND 'DELORES')
OR (WORKDEPT = 'C01' AND FIRSTNME BETWEEN
'CHRISTINE' AND 'DELORES')
OPTIMIZE FOR 99999 ROWS
The key ranges the database manager starts with are as follows:
Range
Range
Range
Range
Range
Range
Range
Chapter 22. DB2 for AS/400 Data Management and the Query Optimizer
339
In this example, the database manager uses X2 to position to the index entries for
WORKDEPT=D11 and then extracts the value for the column FIRSTNME from those
entries.
Note that the index key fields do not have to be contiguous to the leftmost key of
the index for index only access to be performed. Any key field in the index can be
used to provide data for the index only query. The index is used simply as the
source for the data so the database manager can finish processing the query after
the selection has been completed.
The messages created by the PRTSQLINF command to describe this query in an
SQL program are as follows:
SQL4008
SQL4011
SQL4022
340
For this example, a temporary select/omit index is created with the primary key
field LASTNAME. It contains index entries for only those rows where WORKDEPT
= D11. If WORKDEPT = D11, less than approximately 20% of the rows are
selected. The messages created by the PRTSQLINF CL command to describe this
query in an SQL program are as follows:
Chapter 22. DB2 for AS/400 Data Management and the Query Optimizer
341
SQL4012
SQL4011
Rather than using the index-from-index access method, you can use the query sort
routine (see Improving Performance by Using the ALWCPYDTA Parameter on
page 382 ) by specifying either of the following precompile options:
v ALWCPYDTA(*OPTIMIZE), ALWBLK(*ALLREAD), and COMMIT(*CHG or *CS)
v ALWCPYDTA(*OPTIMIZE) and COMMIT(*NONE)
342
Chapter 22. DB2 for AS/400 Data Management and the Query Optimizer
343
The bitmap processing method is used in conjunction with primary access methods
data space scan, key selection, or key positioning. Bitmap processing, like parallel
pre-fetch and parallel table/index pre-load, does not actually select the records
from the data space; it assists the primary methods.
If the bitmap is used in conjunction with the data space scan method, the bitmap
initiates a skip-sequential processing. The data space scan (and parallel data space
scan) uses the bitmap to skip over non-selected records. This has several
advantages:
v No CPU processing is used processing non-selected records.
v I/O is minimized and the memory is not filled with the contents of the entire
data space.
The following example illustrates a query where the query optimizer chooses the
bitmap processing method in conjunction with the dataspace scan:
CREATE INDEX IX1 ON EMPLOYEE (WORKDEPT)
CREATE INDEX IX2 ON EMPLOYEE (SALARY)
DECLARE C1 CURSOR FOR
SELECT * FROM EMPLOYEE
WHERE WORKDEPT = 'E01' OR SALARY>50000
OPTIMIZE FOR 99999 ROWS
In this example, both indexes IX1 and IX2 are used. The database manager first
generates a bitmap from the results of applying selection WORKDEPT = E01
against index IX1 (using key positioning). The database manager then generates a
bitmap from the results of applying selection SALARY>50000 against index IX2
(again using key positioning).
Next, the database manager combines these two bitmaps into one using OR logic.
Finally, a data space scan is initiated. The data space scan uses the bitmap to skip
through the data space records, retrieving only those selected by the bitmap.
This example also shows an additional capability provided with bitmap processing
(use of an index for ANDed selection was already possible but bitmap processing
now allows more than one index). When using bitmap processing, multiple index
usage is possible with selections where OR is the major boolean operator.
The messages created by the PRTSQLINF command when used to describe this
query would look like:
SQL4010
SQL4032
SQL4032
If the bitmap is used in conjunction with either the key selection or key positioning
method, it implies that the bitmap (generated from tertiary indexes) is being used
to aid a primary index access. The following example illustrates a query where
bitmap processing is used in conjunction with the key positioning for a primary
index:
CREATE INDEX PIX ON EMPLOYEE (LASTNAME)
CREATE INDEX TIX1 ON EMPLOYEE (WORKDEPT)
CREATE INDEX TIX2 ON EMPLOYEE (SALARY)
DECLARE C1 CURSOR FOR
SELECT * FROM EMPLOYEE
WHERE WORKDEPT = 'E01' OR SALARY>50000
ORDER BY LASTNAME
344
In this example, indexes TIX1 and TIX2 are used in bitmap processing. The
database manager first generates a bitmap from the results of applying selection
WORKDEPT = E01 against index TIX1 (using key positioning). It then generates a
bitmap from the results of applying selection SALARY>50000 against index TIX2
(again using key positioning).
The database manager then combines these two bitmaps into one using OR logic.
A key selection method is initiated using (primary) index PIX. For each entry in
index PIX, the bitmap is checked. If the entry is selected by the bitmap then the
data space record is retrieved and processed.
The messages created by the PRTSQLINF CL command, when used to describe this
query, would look like:
SQL4008
SQL4032
Selection Process
Good When
Selected When
Advantages
Dataspace
scan
No ordering,
grouping, or
joining and > 20%
rows selected.
Minimizes page
I/O through
pre-fetching.
Parallel
pre-fetch
No ordering,
grouping, or
joining and > 20%
rows selected.
Minimizes wait
time for page I/O
through parallel
pre-fetching.
1. Adequate active
memory
available.
2. Query would
otherwise be
I/O bound.
3. Data spread
across multiple
disk units.
Chapter 22. DB2 for AS/400 Data Management and the Query Optimizer
345
Selection Process
Good When
Parallel
Dataspace
Scan
Selected When
Advantages
3. DB2 Symmetric
Multiprocessing
installed.
4. Multi-processor
system.
Large number of
rows selected.
Index is required
and cannot use key
positioning
method.
Dataspace
accessed only for
rows matching
key selection
criteria.
Size of index is
Selection criteria
applied to index in much less than the
dataspace. DB2
parallel tasks.
Symmetric
Multiprocessing
must be installed.
Large number of
rows selected.
When ordering of
results not
required.
Key
positioning
Selection columns
match left-most
keys and < 20%
rows selected.
Index and
dataspace
accessed only for
rows matching
selection criteria.
Parallel Key
positioning
Large number of
rows selected.
1. When ordering
of results not
required.
Key
selection
Selection criteria
applied to index.
Parallel Key
selection
Ordering,
grouping, and
joining.
1. Index and
dataspace
accessed only
for rows
2. Selection
matching
columns match
selection
left-most keys
criteria.
and < 20% rows
2. Better I/O
selected.
overlap
because
parallel tasks
perform the
I/O.
3. Can fully
utilize a
multiprocessor
systems.
346
Selection Process
Good When
Selected When
Advantages
No existing index
to satisfy ordering
but existing index
does satisfy
selection and
selecting < 20%
rows.
Index and
dataspace
accessed only for
rows matching
selection criteria.
Index-fromindex
Sort routine
Ordering specified;
either no index
exists to satisfy the
ordering or a large
result set is
expected.
See dataspace
scan and key
positioning in this
table.
Index only
Done in
combination with
any of the other
index access
methods
Reduced I/O to
the dataspace.
Parallel
Table/Index
Pre-load
Excessive random
activity would
result from
processing the
query and active
memory is
available which can
hold the entire
object.
Hashing
method
Parallel or
non-parallel
Longer running
Rows with
common values are grouping and/or
join queries.
grouped together.
Join or grouping
specified.
Reduce random
I/O when
compared to
index methods. If
DB2 Symmetric
Multiprocessing is
installed, possible
exploitation of
SMP parallelism.
Bitmap
Processing
Key position/key
selection used to
build bitmap.
Bitmap used to
avoid touching
rows in table.
Indexes match
selection criteria.
Short running
queries.
>25% rows
Selection can be
selected.
applied to index
and either >5% or
<25% rows selected
or an OR operator
is involved in
selection that
precludes the use
of only one index.
Chapter 22. DB2 for AS/400 Data Management and the Query Optimizer
347
The Optimizer
The optimizer is an important part of DB2 for AS/400 because the optimizer:
v Makes the key decisions which affect database performance.
v Identifies the techniques which could be used to implement the query.
v Selects the most efficient technique.
Data manipulation statements such as SELECT specify only what data the user
wants, not how to get to that data. This access path to the data is chosen by the
optimizer and stored in the access plan. This section covers the techniques
employed by the query optimizer for performing this task including:
v Cost estimation
v Access plan validation
v Join optimization
v Grouping optimization
Cost Estimation
At run-time, the optimizer chooses an optimal access method for the query by
calculating an implementation cost based on the current state of the database. The
optimizer models the access cost of each of the following:
v Reading rows directly from the table (dataspace scan processing)
v Reading rows through an access path (using either key selection or key
positioning)
v Creating an access path directly from the dataspace
v Creating an access path from an existing access path (index-from-index)
v Using the query sort routine or hashing method (if conditions are satisfied)
The cost of a particular method is the sum of:
v The start-up cost
v The cost associated with the given optimization mode. The precompile option
ALWCPYDTA and the OPTIMIZE FOR n ROWS clause indicate to the query
optimizer the optimization goal to be achieved. The optimizer can optimize SQL
queries with one of two goals:
1. Minimize the time required to retrieve the first buffer of rows from the table.
This goal biases the optimization towards not creating an index.
Either a data scan or an existing index is preferred. This mode can be
specified in two ways:
a. The OPTIMIZE FOR n ROWS allows the users to specify the number of
rows they expect to retrieve from the query.
The optimizer uses this value to determine the percentage of rows that
will be returned and optimizes accordingly. A small value instructs the
optimizer to minimize the time required to retrieve the first n rows.
b. Specifying ALWCPYDTA(*NONE) or ALWCPYDTA(*YES) a precompiler
option, allows the optimizer to minimize the time required to retrieve the
first 3% of the resulting rows.
This option is effective only if the OPTIMIZE FOR n ROWS was not
specified.
348
2. Minimize the time to process the whole query assuming that all selected
rows are returned to the application. Does not bias the optimizer to any
particular access method. This mode can be specified in two ways:
a. The OPTIMIZE FOR n ROWS allows the users to specify the number of
rows they expect to retrieve from the query.
The optimizer uses this value to determine the percentage of rows that
will be returned and optimizes accordingly. A value greater than or equal
to the expected number of resulting rows instructs the optimizer to
minimize the time required to run the entire query.
b. ALWCPYDTA(*OPTIMIZE) specified as a precompiler parameter.
This option is effective only if the OPTIMIZE FOR n ROWS is not
specified.
v The cost of any access path creations
v The cost of the expected number of page faults to read the rows and the cost of
processing the expected number of rows.
Page faults and number of rows processed may be predicted by statistics the
optimizer can obtain from the database objects, including:
Table size
Row size
Index size
Key size
Page faults can also be greatly affected if index only access can be performed,
thus eliminating any random I/O to the data space.
A weighted measure of the expected number of rows to process is based on
what the relational operators in the row selection predicates, default filter factors,
are likely to retrieve:
10% for equal
33%
90%
25%
10%
for
for
for
for
Key range estimate is a method the optimizer uses to gain more accurate
estimates of the number of expected rows selected from one or more selection
predicates. The optimizer estimates by applying the selection predicates against
the left-most keys of an existing index. The default filter factors can then be
further refined by the estimate based on the key range. If an index exists whose
left-most keys match columns used in row selection predicates, that index can be
used to estimate the number of keys that match the selection criteria. The
estimate of the number of keys is based on the number of pages and key density
of the machine index and is done without actually accessing the keys. Full
indexes over columns used in selection predicates can significantly help
optimization.
Page faults and the number of rows processed are dependent on the type of
access the optimizer chooses. Refer to Data Management Methods on page 325
for more information on access methods.
Chapter 22. DB2 for AS/400 Data Management and the Query Optimizer
349
Join Optimization
A join operation is a complex function that requires special attention in order to
achieve good performance. This section describes how DB2 for AS/400 implements
join queries and how optimization choices are made by the query optimizer. It also
describes design tips and techniques which help avoid or solve performance
problems.
350
351
time. This is the reason why attention to performance considerations for join
queries can reduce the run-time of a join query from hours to minutes.
v Again, all selected rows from secondary dials are accessed through a keyed
access path. If an efficient keyed access path cannot be found, a temporary keyed
access path is created. Some join queries build temporary access paths over
secondary dials even when an access path exists for all of the join keys. Because
efficiency is very important for secondary dials of longer running queries, the
query optimizer may choose to build a temporary keyed access path which
contains only keys which pass the local row selection for that dial. This
preprocessing of row selection allows the database manager to process row
selection in one pass instead of each time rows are matched for a dial.
Hash Join
The hash join method is similar to nested loop join. Instead of using keyed access
paths to locate the matching rows in a secondary table, however, a hash temporary
result table is created that contains all of the rows selected by local selection
against the table. The structure of the hash table is such that rows with the same
join value are loaded into the same hash table partition (clustered). The location of
the rows for any given join value can be found by applying a hashing function to
the join value.
Hash join has several advantages over nested loop join:
v The structure of a hash temporary result table is simpler than that of an index,
so less CPU processing is required to build and probe a hash table.
v The rows in the hash result table contain all of the data required by the query so
there is no need to access the data space of the table with random I/O when
probing the hash table.
v Like join values are clustered, so all matching rows for a given join value can
usually be accessed with a single I/O request.
v The hash temporary result table can be built using SMP parallelism.
v Unlike indexes, entries in hash tables are not updated to reflect changes of
column values in the underlying table. The existence of a hash table does not
affect the processing cost of other updating jobs in the system.
Hash join cannot be used for queries that:
v
v
v
v
v
Perform subqueries.
Perform a UNION or UNION ALL.
Perform left outer or exception join.
Use a DDS created join logical file.
Require live access to the data as specified by the *NO or *YES parameter values
for the ALWCPYDTA precompiler parameter. Hash join is used only for queries
running with ALWCPYDTA(*OPTIMIZE). This parameter can be specified either
on precompiler commands, the STRSQL CL command, or the OPNQRYF CL
command. The Client Access/400 ODBC driver and Query Management driver
always uses this mode.
Hash join can be used with OPTIMIZE(*YES) if a temporary result is required to
run the query.
v Require that the cursor position be restored as the result of the SQL ROLLBACK
HOLD statement or the ROLLBACK CL command. For SQL applications using
commitment control level other than *NONE, this requires that *ALLREAD be
specified as the value for the ALWBLK precompiler parameter.
352
The query attribute DEGREE, which can be changed by using the Change Query
attribute CL command (CHGQRYA), does not enable or disable the optimizer from
choosing to use hash join. However, hash join queries can use SMP parallelism if
the query attribute DEGREE is set to either *OPTIMIZE, *MAX, or *NBRTASKS.
Hash join is used in many of the same cases where a temporary index would have
been built. Join queries which are most likely to be implemented using hash join
are those where either:
v All rows in the various tables of the join are involved in producing result rows.
v Significant non-join selection is specified for the tables of the join which reduces
the number of rows in the tables that are involved with the join result.
The following is an example of a join query that would process all of the rows
from the queried tables:
SELECT *
FROM EMPLOYEE, EMP_ACT
WHERE EMPLOYEE.EMPNO = EMP_ACT.EMPNO
OPTIMIZE FOR 99999999 ROWS
The following is an example of a join query that would have the queried tables of
the join queried significantly reduced by local selection:
SELECT
FROM
WHERE
AND
AND
OPTIMIZE
353
354
For any given dial, only one type of join operator is normally implemented. For
example, if one inner join join specification has a join operator of = and the other
has a join operator of >, the optimizer attempts to implement the join with the =
operator. The > join specification is processed as row selection after a matching
row for the = specification is found. In addition, multiple join specifications that
use the same operator are implemented together.
Note: Only one type of join operator is allowed for either a left outer or an
exception join.
When looking for an existing keyed access path to access a secondary dial, the
query optimizer looks at the left-most key columns of the access path. For a given
dial and keyed access path, the join specifications which use the left-most key
columns can be used. For example:
DECLARE BROWSE2 CURSOR FOR
SELECT * FROM EMPLOYEE, EMP_ACT
WHERE EMPLOYEE.EMPNO = EMP_ACT.EMPNO
AND EMPLOYEE.HIREDATE = EMP_ACT.EMSTDATE
OPTIMIZE FOR 99999 ROWS
For the keyed access path over EMP_ACT with key columns EMPNO, PROJNO,
and EMSTDATE, the join operation is performed only on column EMPNO. After
the join is processed, row selection is done using column EMSTDATE.
The query optimizer also uses local row selection when choosing the best use of
the keyed access path for the secondary dial. If the previous example had been
expressed with a local predicate as:
DECLARE BROWSE2 CURSOR FOR
SELECT * FROM EMPLOYEE, EMP_ACT
WHERE EMPLOYEE.EMPNO = EMP_ACT.EMPNO
AND EMPLOYEE.HIREDATE = EMP_ACT.EMSTDATE
AND EMP_ACT.PROJNO = '123456'
OPTIMIZE FOR 99999 ROWS
the keyed access path with key columns EMPNO, PROJNO, and EMSTDATE are
fully utilized by combining join and selection into one operation against all three
key columns.
When creating a temporary keyed access path, the left-most key columns are the
usable join columns in that dial position. All local row selection for that dial is
processed when selecting keys for inclusion into the temporary keyed access path.
A temporary keyed access path is similar to the access path created for a
select/omit keyed logical file. The temporary index for the previous example
would have key fields of EMPNO and EMSTDATE.
In the above example, either implementation, an existing index may be used or a
temporary index may be created. The implementation using the existing index is
more likely to provide faster performance because join and selection processing are
combined without the overhead of building a temporary index. In general, it is a
good idea to have existing indexes available with key columns for the combination
of join columns and columns using equal selection as the left-most keys.
355
1. Determine an access method for each individual table as candidates for the
primary dial.
2. Estimate the number of rows returned for each table based on local row
selection.
If the join query with row ordering or group by processing is being processed
in one step, then the table with the ordering or grouping columns is the
primary table.
3. Determine an access method, cost, and expected number of rows returned for
each join combination of candidate tables as primary and first secondary tables.
The join order combinations estimated for a four table join would be:
1-2
2-1
1-3
3-1
1-4
4-1
2-3
3-2
2-4
4-2
3-4
4-3
356
v The query is the only process running on the system. No allowance is given for
system CPU utilization or I/O waits which occur because of other processes
using the same resources. CPU related costs are scaled to the relative processing
speed of the system running the query.
v The values in a column are uniformly distributed across the table. For example,
if 10% of the rows in a table have the same value, then it is assumed that every
tenth row in the table contains that value.
v The values in a column are independent from the values in any other columns
in a row. For example, if a column named A has a value of 1 in 50% of the rows
in a table and a column named B has a value of 2 in 50% of the rows, then it is
expected that a query which selects rows where A = 1, and B = 2 selects 25% of
the rows in the table.
The main factors of the join cost calculations for secondary dials are the number of
rows selected in all previous dials and the number of rows which match, on
average, each of the rows selected from previous dials. Both of these factors can be
derived by estimating the number of matching rows for a given dial.
When the join operator is something other than equal, the expected number of
matching rows is based on the following default filter factors:
v
v
v
v
33%
90%
25%
10%
for
for
for
for
For example, when the join operator is less-than, the expected number of matching
rows is .33 * (number of rows in the dial). If no join specifications are active for the
current dial, the cartesian product is assumed to be the operator. For cartesian
products, the number of matching rows is every row in the dial, unless local row
selection can be applied to the keyed access path.
When the join operator is equal, the expected number of rows is the average
number of duplicate rows for a given value.
The AS/400 performs index maintenance (insertion and deletion of key values in
an index) and maintains a running count of the number of unique values for the
given key columns in the index. These statistics are bound with the index object
and are always maintained. The query optimizer uses these statistics when it is
optimizing a query. Maintaining these statistics adds no measurable amount of
overhead to index maintenance. This statistical information is only available for
indexes which:
v Contain no varying length character keys.
Note: If you have varying length character columns used as join columns, you
can create an index which maps the varying length character column to a
fixed character key using the CRTLF CL command. An index that contains
fixed length character keys defined over varying length data supplies
average number of duplicate values statistics.
v Were created or rebuilt on an AS/400 system on which Version 2 Release 3 or a
later version is installed.
Note: The query optimizer can use indexes created on earlier versions of
OS/400 to estimate if the join key values have a high or low average
number of duplicate values. If the index is defined with only the join
Chapter 22. DB2 for AS/400 Data Management and the Query Optimizer
357
keys, the estimate is done based on the size of the index. In many cases,
additional keys in the index cause matching row estimates through that
index to not be valid. The performance of some join queries may be
improved by rebuilding these access paths.
Average number of duplicate values statistics are maintained only for the first 4
left-most keys of the index. For queries which specify more than 4 join columns, it
might be beneficial to create multiple additional indexes so that an index can be
found with average number of duplicate values statistics available within the 4
left-most key columns. This is particularly important if some of the join columns
are somewhat unique (low average number of duplicate values).
3 column Key
number
of unique
keys for
Key 1
number
of unique
keys for
Key 1 and
key 2
combination
number
of unique
keys for
Key 1, key
2, and key 3
combination
(in other words
the full key)
NPREV
The number of join rows from all previous dials.
358
Rp
M2
FF2
Filtering reduction factor for predicates local to dial 2 that are not already
applied using M2 above.
Mn
FFn
Filtering reduction factor for predicates local to dial n that are not already
applied using Mn above.
Note: Multiply the pair of matching rows (Mn) and filter reduction filter
factors (FFn) for each secondary dial preceding the current dial.
Now that it has calculated the number of join rows from previous dials, the
optimizer is ready to generate a cost for the access method.
CRTDSI +
NPREV *((MATCH * FF * KeyAccess)
+ (MATCH * FF * FCost)) *
FirstIO
JSCOST
Join Secondary cost
CRTDSI
Cost to build the temporary keyed access path or a hash temporary result
table
NPREV
The number of join rows from all previous dials
MATCH
The number of matching rows (usually average duplicates)
KeyAccess
The cost to access a key in a keyed access path or a hash table
FF
The filtering factor for local predicates of this dial (excluding selection
performed on earlier dials because of transitive closure)
359
method is used for join secondary dial access for the same reason. However, the
creation from a keyed access path might be less costly.
JSCOST
Join Secondary cost
NPREV
The number of join rows from all previous dials
MATCH
The number of matching keys which will be found in this keyed access
path (usually average duplicates)
KeyAccess
The cost to access a key in a keyed access path
FCost The cost to access a row from the table
FirstIO
A reduction ratio to reduce the non-startup cost because of an optimization
goal to optimize for the first buffer retrieval. For more information, see
Cost Estimation on page 348.
If I/O optimization is used first, this is a likely access method because the entire
cost is reduced. Also, if the number of join rows from all previous dials (NPREV),
and the number of matching keys (MATCH) is low, this may be the most efficient
method.
The query optimizer considers using an index which only has a subset of the join
columns as the left-most leading keys when:
v It is able to determine from the average number of duplicate values statistics
that the average number of rows with duplicate values is quite low.
v The number of rows being selected from the previous dials is small.
360
The following rules determine which predicates are added to other join dials:
v The dials affected must have join operators of equal.
v The predicate is isolatable, which means that a false condition from this
predicate would omit the row.
v One operand of the predicate is an equal join column and the other is a literal or
host variable.
v The predicate operator is not LIKE or IN.
v The predicate is not connected to other predicates by OR.
v The join type for the dial is an inner join.
The query optimizer generates a new predicate, whether or not a predicate already
exists in the WHERE clause.
Some predicates are redundant. This occurs when a previous evaluation of other
predicates in the query already determines the result that predicate provides.
Redundant predicates can be specified by you or generated by the query optimizer
during predicate manipulation. Redundant predicates with predicate operators of
=, >, >=, <, <=, or BETWEEN are merged into a single predicate to reflect the most
selective range.
Chapter 22. DB2 for AS/400 Data Management and the Query Optimizer
361
362
Grouping Optimization
This section describes how DB2 for AS/400 implements grouping techniques and
how optimization choices are made by the query optimizer.
Chapter 22. DB2 for AS/400 Data Management and the Query Optimizer
363
In this example, the optimizer can remove EMPNO from the list of grouping fields
because of the EMPNO = '000190' selection predicate. An index that only has
LASTNAME and WORKDEPT specified as key fields can be considered to
implement the query and if a temporary index or hash is required then EMPNO
will not be used.
Note: Even though EMPNO can be removed from the list of grouping columns,
the optimizer might still choose to use that index if a permanent index exists
with all three grouping columns.
364
For this query request, the optimizer can add EMPNO as an additional grouping
column when considering X1 for the query.
How It Helps
Chapter 22. DB2 for AS/400 Data Management and the Query Optimizer
365
Table 39. Checklist for Creating an Application that Uses Join Queries (continued)
What to Do
How It Helps
instead of
... WHERE EDUCLVL < 1.1E1 AND
EDUCLVL > 1.3
instead of
... WHERE EMPNO > '000300 ' AND
DEPTNO < 'E20 '
366
The percent sign (%), and the underline (_), when used in the pattern of a LIKE
predicate, specify a character string that is similar to the column value of rows
you want to select. When used to denote characters in the middle or at the end
of a character string, as in
... WHERE LASTNAME LIKE 'J%SON%'
they can take advantage of indexes. However, when used at the beginning of a
character string, as in
... WHERE LASTNAME LIKE '%SON'
they can prevent DB2 for AS/400 from using any indexes that might be defined
on the LASTNAME column to limit the number of rows scanned. You should
therefore avoid using these symbols at the beginning of character strings,
especially if you are accessing a particularly large table.
4. Be aware that DB2 for AS/400 does not use an index in the following
instances:
v For a column that is expected to be updated; for example, your program
might include
EXEC SQL
DECLARE DEPTEMP CURSOR FOR
SELECT EMPNO, LASTNAME, WORKDEPT
FROM CORPDATA.EMPLOYEE
WHERE (WORKDEPT = 'D11' OR
WORKDEPT = 'D21') AND
EMPNO = '000190'
FOR UPDATE OF EMPNO, WORKDEPT
END-EXEC.
Even if you do not intend to update the employees department, DB2 for
AS/400 cannot use an index with a key of WORKDEPT.
DB2 for AS/400 can use an index if all of the updateable columns used
within the index are also used within the query as an isolatable selection
predicate with an equal operator. In the previous example DB2 for AS/400
would use an index with a key of EMPNO.
DB2 for AS/400 can operate more efficiently if the FOR UPDATE OF column
list only names the column you intend to update: WORKDEPT. Therefore, do
not specify a column in the FOR UPDATE OF column list unless you intend
to update the column.
If you have an updateable cursor because of dynamic SQL or the FOR
UPDATE clause was not specified and the program contains an UPDATE
statement then all columns can be updated.
v For a column being compared with another column from the same row. For
example:
EXEC SQL
DECLARE DEPTDATA CURSOR FOR
SELECT WORKDEPT, DEPTNAME
FROM CORPDATA.EMPLOYEE
WHERE WORKDEPT = ADMRDEPT
END-EXEC.
Even though there is an index for WORKDEPT and another index for
ADMRDEPT, DB2 for AS/400 will not use either index. The index has no
added benefit because every row of the table needs to be looked at.
Chapter 22. DB2 for AS/400 Data Management and the Query Optimizer
367
Ordering
Unless the optimizer chooses to do a sort to satisfy the ordering request, the sort
sequence table associated with the index must match the sort sequence table
associated with the query.
When a sort is used, the translation is done during the sort. Since the sort is
handling the sort sequence requirement, this allows DB2 for AS/400 to use any
existing index that meets the selection criteria.
368
Example Indexes
For the purposes of the examples, assume three indexes are created.
Assume an index HEXIX was created with *HEX as the sort sequence.
CREATE INDEX HEXIX ON STAFF (JOB)
Example 1
Equals selection with no sort sequence table (SRTSEQ(*HEX)).
SELECT * FROM STAFF
WHERE JOB = 'MGR'
DB2 for AS/400 could use either index HEXIX or index UNQIX.
Example 2
Equals selection with a unique-weight sort sequence table
(SRTSEQ(*LANGIDUNQ) LANGID(ENU)).
SELECT * FROM STAFF
WHERE JOB = 'MGR'
DB2 for AS/400 could use either index HEXIX or index UNQIX.
Example 3
Equal selection with a shared-weight sort sequence table (SRTSEQ(*LANGIDSHR)
LANGID(ENU)).
SELECT * FROM STAFF
WHERE JOB = 'MGR'
Example 4
Greater than selection with a unique-weight sort sequence table
(SRTSEQ(*LANGIDUNQ) LANGID(ENU)).
SELECT * FROM STAFF
WHERE JOB > 'MGR'
Example 5
Join selection with a unique-weight sort sequence table (SRTSEQ(*LANGIDUNQ)
LANGID(ENU)).
SELECT * FROM STAFF S1, STAFF S2
WHERE S1.JOB = S2.JOB
369
SELECT *
FROM STAFF S1 INNER JOIN STAFF S2
ON S1.JOB = S2.JOB
DB2 for AS/400 could use either index HEXIX or index UNQIX for either query.
Example 6
Join selection with a shared-weight sort sequence table (SRTSEQ(*LANGIDSHR)
LANGID(ENU)).
SELECT * FROM STAFF S1, STAFF S2
WHERE S1.JOB = S2.JOB
DB2 for AS/400 could only use index SHRIX for either query.
Example 7
Ordering with no sort sequence table (SRTSEQ(*HEX)).
SELECT * FROM STAFF
WHERE JOB = 'MGR'
ORDER BY JOB
Example 8
Ordering with a unique-weight sort sequence table (SRTSEQ(*LANGIDUNQ)
LANGID(ENU)).
SELECT * FROM STAFF
WHERE JOB = 'MGR'
ORDER BY JOB
Example 9
Ordering with a shared-weight sort sequence table (SRTSEQ(*LANGIDSHR)
LANGID(ENU)).
SELECT * FROM STAFF
WHERE JOB = 'MGR'
ORDER BY JOB
Example 10
Ordering with ALWCPYDTA(*OPTIMIZE) and a unique-weight sort sequence table
(SRTSEQ(*LANGIDUNQ) LANGID(ENU)).
SELECT * FROM STAFF
WHERE JOB = 'MGR'
ORDER BY JOB
370
DB2 for AS/400 could use either index HEXIX or index UNQIX for selection.
Ordering would be done during the sort using the *LANGIDUNQ sort sequence
table.
Example 11
Grouping with no sort sequence table (SRTSEQ(*HEX)).
SELECT * FROM STAFF
GROUP BY JOB
DB2 for AS/400 could use either index HEXIX or index UNQIX.
Example 12
Grouping with a unique-weight sort sequence table (SRTSEQ(*LANGIDUNQ)
LANGID(ENU)).
SELECT * FROM STAFF
GROUP BY JOB
DB2 for AS/400 could use either index HEXIX or index UNQIX.
Example 13
Grouping with a shared-weight sort sequence table (SRTSEQ(*LANGIDSHR)
LANGID(ENU)).
SELECT * FROM STAFF
GROUP BY JOB
Assume an index UNQIX2 was created and the sort sequence is a unique-weight
sort sequence.
CREATE INDEX UNQIX2 ON STAFF (JOB, SALARY)
Example 14
Ordering and grouping on the same columns with a unique-weight sort sequence
table (SRTSEQ(*LANGIDUNQ) LANGID(ENU)).
SELECT * FROM STAFF
GROUP BY JOB, SALARY
ORDER BY JOB, SALARY
DB2 for AS/400 could use UNQIX2 to satisfy both the grouping and ordering
requirements. If index UNQIX2 did not exist, DB2 for AS/400 would create an
index using a sort sequence table of *LANGIDUNQ.
Chapter 22. DB2 for AS/400 Data Management and the Query Optimizer
371
Example 15
Ordering and grouping on the same columns with ALWCPYDTA(*OPTIMIZE) and
a unique-weight sort sequence table (SRTSEQ(*LANGIDUNQ) LANGID(ENU)).
SELECT * FROM STAFF
GROUP BY JOB, SALARY
ORDER BY JOB, SALARY
DB2 for AS/400 could use UNQIX2 to satisfy both the grouping and ordering
requirements. If index UNQIX2 did not exist, DB2 for AS/400 would either:
v Create an index using a sort sequence table of *LANGIDUNQ or
v Use index HEXIX2 to satisfy the grouping and to perform a sort to satisfy the
ordering
Example 16
Ordering and grouping on the same columns with a shared-weight sort sequence
table (SRTSEQ(*LANGIDSHR) LANGID(ENU)).
SELECT * FROM STAFF
GROUP BY JOB, SALARY
ORDER BY JOB, SALARY
DB2 for AS/400 could use SHRIX2 to satisfy both the grouping and ordering
requirements. If index SHRIX2 did not exist, DB2 for AS/400 would create an
index using a sort sequence table of *LANGIDSHR.
Example 17
Ordering and grouping on the same columns with ALWCPYDTA(*OPTIMIZE) and
a shared-weight sort sequence table (SRTSEQ(*LANGIDSHR) LANGID(ENU).
SELECT * FROM STAFF
GROUP BY JOB, SALARY
ORDER BY JOB, SALARY
DB2 for AS/400 could use SHRIX2 to satisfy both the grouping and ordering
requirements. If index SHRIX2 did not exist, DB2 for AS/400 would create an
index using a sort sequence table of *LANGIDSHR.
Example 18
Ordering and grouping on different columns with a unique-weight sort sequence
table (SRTSEQ(LANGIDUNQ) LANGID(ENU)).
SELECT * FROM STAFF
GROUP BY JOB, SALARY
ORDER BY SALARY, JOB
DB2 for AS/400 could use index HEXIX2 or index UNQIX2 to satisfy the grouping
requirements. A temporary result would be created containing the grouping
results. A temporary index would then be built over the temporary result using a
*LANGIDUNQ sort sequence table to satisfy the ordering requirements.
Example 19
Ordering and grouping on different columns with ALWCPYDTA(*OPTIMIZE) and
a unique-weight sort sequence table (SRTSEQ(*LANGIDUNQ) LANGID(ENU)).
372
DB2 for AS/400 could use index HEXIX2 or index UNQIX2 to satisfy the grouping
requirements. A sort would be performed to satisfy the ordering requirements.
Example 20
Ordering and grouping on different columns with ALWCPYDTA(*OPTIMIZE) and
a shared-weight sort sequence table (SRTSEQ(*LANGIDSHR) LANGID(ENU)).
SELECT * FROM STAFF
GROUP BY JOB, SALARY
ORDER BY SALARY, JOB
DB2 for AS/400 could use index SHRIX2 to satisfy the grouping requirements. A
sort would be performed to satisfy the ordering requirements.
Number of
Records in
Overflow
Space
Variety of
Support
Last Name
Max/Alloc
First Name
Max/Alloc
Middle
Name
Max/Alloc
Fixed Length
22
22
22
567 K
Variable
Length
40/10
40/10
40/7
408 K
73
Chapter 22. DB2 for AS/400 Data Management and the Query Optimizer
373
Variety of
Support
Last Name
Max/Alloc
First Name
Max/Alloc
Middle
Name
Max/Alloc
VariableLength
Default
40/0
40/0
40/0
Total
Physical File
Size
Number of
Records in
Overflow
Space
373 K
8600
If you are using host variables to insert or update variable-length columns, the
host variables should be variable length. Because blanks are not truncated from
fixed-length host variables, using fixed-length host variables would cause more
rows to spill into the overflow space. This would increase the size of the table.
In this example, fixed-length host variables are used to insert a row into a table:
01
VLAST-NAME.
49 LAST-NAME-LEN PIC S9(4) BINARY.
49 LAST-NAME-DATA PIC X(40).
...
MOVE "SMITH" TO LAST-NAME-DATA.
MOVE 5 TO LAST-NAME-LEN.
EXEC SQL
INSERT INTO PHONEDIR
VALUES(:VLAST-NAME, :VFIRST-NAME, :VMIDDLE-NAME, :PHONE)
END-EXEC.
The host variable VLAST-NAME is variable length. The actual length of the data is
set to 5. The value is shorter than the allocated length. It can be placed in the fixed
portion of the column.
374
For more information about using variable-length host variables, see Chapter 10.
Coding SQL Statements in C and C++ Applications, through Chapter 15. Coding
SQL Statements in REXX Applications.
Running the RGZPFM command against tables that contain variable-length
columns can improve performance. The fragments in the overflow area that are not
in use are compacted by the RGZPFM command. This reduces the read time for
rows that overflow, increases the locality of reference, and produces optimal order
for serial batch processing.
Choose the appropriate maximum length for variable-length columns. Selecting
lengths that are too long increases the process access group (PAG). A large PAG
slows performance. A large maximum length makes SEQONLY(*YES) less effective.
Variable-length columns longer than 2000 bytes are not eligible as key columns.
Provide the optimizer with a little more data in the WHERE clause and code:
EXEC SQL
DECLARE EMPACTDATA CURSOR FOR
SELECT LASTNAME, DEPTNAME, PROJNO, ACTNO
FROM CORPDATA.DEPARTMENT, CORPDATA.EMPLOYEE,
CORPDATA.EMP_ACT
WHERE DEPARTMENT.MGRNO = EMPLOYEE.EMPNO
AND EMPLOYEE.EMPNO = EMP_ACT.EMPNO
AND DEPARTMENT.MGRNO = EMP_ACT.EMPNO
END-EXEC.
Chapter 22. DB2 for AS/400 Data Management and the Query Optimizer
375
An OPEN statement
SELECT INTO statement
An INSERT statement with a VALUES clause
An UPDATE statement with a WHERE condition
An UPDATE statement with a WHERE CURRENT OF cursor and SET clauses
that refer to operators or functions
v A DELETE statement with a WHERE condition
An INSERT statement with a select-statement requires two open operations.
Certain forms of subqueries may also require one open per subselect.
To minimize the number of opens, DB2 for AS/400 leaves the open data path
(ODP) open and reuses the ODP if the statement is run again, unless:
v GROUP BY contains columns from more than one table.
v The ODP used a host variable to build a subset temporary index. The OS/400
database support may choose to build a temporary index with entries for only
the rows that match the row selection specified in the SQL statement. If a host
variable was used in the row selection, the temporary index will not have the
entries required for a different value contained in the host variable.
v Ordering was specified on a host variable value.
v A host variable is used to specify the pattern of a LIKE predicate. The host
variable value has either underscores (_) or involves more than one search
pattern: for %ABC%DEF, two patterns are involved, ABC and DEF.
v An Override Database File (OVRDBF) or Delete Override (DLTOVR) CL
command has been issued since the ODP was opened, which would affect the
SQL statement execution.
v
v
v
v
Note: Only overrides that affect the name of the table being referred to will
cause the ODP to be closed within a given program invocation.
A change to the library list since the last open has occurred, which would
change the file selected by an unqualified referral in system naming mode.
The file being queried is a join logical file and its join type (JDFTVAL) does not
match the join type specified in the query.
The format specified for a logical file references more than one physical file.
The file is a complex SQL view that requires a temporary file to contain the
results of the SQL view.
DB2 for AS/400 only reuses ODPs opened by the same statement. An identical
statement coded later in the program does not reuse an ODP from any other
statement. If the identical statement must be run in the program many times, code
it once in a subroutine and call the subroutine to run the statement.
376
The ODPs opened by DB2 for AS/400 are closed when any of the following occurs:
v A CLOSE, INSERT, UPDATE, DELETE, or SELECT INTO statement completes
and the ODP required a temporary result or a subset temporary index.
v The Reclaim Resources (RCLRSC) command is issued. A RCLRSC is issued
when:
The first COBOL program on the call stack ends
A COBOL program issues the STOP RUN COBOL statement
For interaction of RCLRSC with non-default activation groups, see the ILE C for
AS/400 Programmers Guide, ILE COBOL for AS/400 Programmers Guide, and ILE
RPG for AS/400 Programmers Guide books. RCLRSC will not close ODPs created
for programs precompiled using CLOSQLCSR(*ENDJOB).
v When the last program that contains SQL statements on the call stack exits,
except for ODPs created for programs precompiled using
CLOSQLCSR(*ENDJOB) or modules precompiled using
CLOSQLCSR(*ENDACTGRP).
v When a CONNECT (Type 1) statement changes the application server for an
activation group, all ODPs created for the activation group are closed.
v When a DISCONNECT statement ends a connection to the application server, all
ODPs for that application server are closed.
v When a released connection is ended by a successful COMMIT, all ODPs for that
application server are closed.
You can control whether DB2 for AS/400 keeps the ODPs open by:
v Designing the application so a program that issues an SQL statement is always
on the call stack
v Using the CLOSQLCSR(*ENDJOB) or CLOSQLCSR(*ENDACTGRP) parameter
DB2 for AS/400 does an open operation for the first execution of each UPDATE
WHERE CURRENT OF when any expression in the SET clause contains an
operator or function. The open can be avoided by coding the function or operation
in the host language code.
For example, the following UPDATE causes DB2 for AS/400 to do an open
operation:
EXEC SQL
FETCH EMPT INTO :SALARY
END-EXEC.
EXEC SQL
UPDATE CORPDATA.EMPLOYEE
SET SALARY = :SALARY + 1000
WHERE CURRENT OF EMPT
END-EXEC.
:SALARY
Chapter 22. DB2 for AS/400 Data Management and the Query Optimizer
377
UPDATE CORPDATA.EMPLOYEE
SET SALARY = :SALARY
WHERE CURRENT OF EMPT
END-EXEC.
The CL commands Trace Job (TRCJOB) or Display Journal (DSPJRN) can be used
to determine the number of opens being performed by an SQL statement.
378
Multiple-Row FETCH
Statement
Chapter 22. DB2 for AS/400 Data Management and the Query Optimizer
379
FETCH, all fetches against that cursor are treated as multiple-row fetches. In that
case, each of the single-row FETCH requests would be treated as a multiple-row
FETCH of one row.
v The PRIOR, CURRENT, and RELATIVE scroll options should not be used with
multiple-row FETCH statements. To allow random movement of the cursor by
the application, the database manager must maintain the same cursor position as
the application. Therefore, the SQL run-time treats all FETCH requests against a
scrollable cursor with these options specified as multiple-row FETCH requests.
Multiple-Row INSERT
Statement
380
PERFORM FETCH-C1-PARA
20 TIMES.
Show the display and wait for the user to indicate that
the next 20 rows should be displayed.
EXEC SQL
DECLARE C2 CURSOR FOR
SELECT EMPNO, LASTNAME, WORKDEPT
FROM CORPDATA.EMPLOYEE
WHERE EMPNO > :LAST-EMPNO
ORDER BY EMPNO
END-EXEC.
Chapter 22. DB2 for AS/400 Data Management and the Query Optimizer
381
EXEC SQL
OPEN C2
END-EXEC.
*
PERFORM FETCH-C21-PARA
20 TIMES.
EXEC SQL
CLOSE C2
END-EXEC.
PERFORM FETCH-C1-PARA
*
*
Show the display and wait for the user to indicate that
the next 20 rows should be displayed.
PERFORM FETCH-C1-PARA
20 TIMES.
20 TIMES.
EXEC SQL
CLOSE C1
END-EXEC.
In the above example, the query could perform better if the FOR 20 ROWS clause
was used on the multiple-row FETCH statement. Then, the 20 rows would be
retrieved in one operation.
382
383
* optimize ratio
In the previous examples, the estimated cost to sort or to create an index is not
adjusted by the optimize ratio. This enables the optimizer to balance the
optimization and preprocessing requirements. If the optimize number is larger than
the number of rows in the result table, no adjustments are made to the cost
estimates. If the OPTIMIZE clause is not specified for a query, a default value is
used based on the statement type, value of ALWCPYDTA specified, or output
device.
Statement Type
ALWCPYDTA(*OPTIMIZE)
ALWCPYDTA(*YES or *NO)
DECLARE CURSOR
Embedded Select
384
*ENDPGM
This is the default for all non-ILE precompilers. With this option, a cursor
remains open and accessible only while the program that opened it is on
the call stack. When the program ends, the SQL cursor can no longer be
used. Prepared statements are also lost when the program ends. Locks,
however, remain until the last SQL program on the call stack has
completed.
*ENDSQL
With this option, SQL cursors and prepared statements created by a
program remain open until the last SQL program on the call stack has
completed. They cannot be used by other programs, only by a different call
to the same program. Locks remain until the last SQL program in the call
stack completes.
*ENDJOB
This option allows you to keep SQL cursors, prepared statements, and
locks active for the duration of the job. When the last SQL program on the
stack has completed, any SQL resources created by *ENDJOB programs are
still active. The locks remain in effect. The SQL cursors that were not
explicitly closed by the CLOSE, COMMIT, or ROLLBACK statements
remain open. The prepared statements are still usable on subsequent calls
to the same program.
Chapter 22. DB2 for AS/400 Data Management and the Query Optimizer
385
General Rules for Retaining Cursor Positions For All Program Calls
When using programs compiled with either CLOSQLCSR(*ENDPGM) or
CLOSQLCSR(*ENDMOD), a cursor must be opened every time the program or
module is called, in order to access the data. If the SQL program or module is
going to be called several times, and you want to take advantage of a reusable
ODP, then the cursor must be explicitly closed before the program or module exits.
Using the CLOSQLCSR parameter and specifying *ENDSQL, *ENDJOB, or
*ENDACTGRP, you may not need to run an OPEN and a CLOSE statement on
every call. In addition to having fewer statements to run, you can maintain the
cursor position between calls to the program or module.
The following examples of SQL statements help demonstrate the advantage of
using the CLOSQLCSR parameter:
EXEC SQL
DECLARE DEPTDATA CURSOR FOR
SELECT EMPNO, LASTNAME
FROM CORPDATA.EMPLOYEE
WHERE WORKDEPT = :DEPTNUM
END-EXEC.
EXEC SQL
OPEN DEPTDATA
END-EXEC.
EXEC SQL
FETCH DEPTDATA INTO :EMPNUM, :LNAME
END-EXEC.
EXEC SQL
CLOSE DEPTDATA
END-EXEC.
If this program is called several times from another SQL program, it will be able to
use a reusable ODP. This means that, as long as SQL remains active between the
calls to this program, the OPEN statement will not require a database open
operation. However, the cursor is still positioned to the first result row after each
OPEN statement, and the FETCH statement will always return the first row.
In the following example, the CLOSE statement has been removed:
EXEC SQL
DECLARE DEPTDATA CURSOR FOR
SELECT EMPNO, LASTNAME
FROM CORPDATA.EMPLOYEE
WHERE WORKDEPT = :DEPTNUM
END-EXEC.
IF CURSOR-CLOSED IS = TRUE THEN
EXEC SQL
OPEN DEPTDATA
END-EXEC.
EXEC SQL
FETCH DEPTDATA INTO :EMPNUM, :LNAME
END-EXEC.
386
387
Optimal Value
Improvements
Considerations
Related Topics
ALWCPYDTA
*OPTIMIZE
See Improving
Performance by Using
the ALWCPYDTA
Parameter on
page 382 .
ALWBLK
*ALLREAD
Additional read-only
cursors use blocking.
ROLLBACK HOLD
may not change the
position of a
read-only
cursor.Dynamic
processing of
positioned updates or
deletes might fail.
See Improving
Performance by Using
Database Manager
Blocking
Considerations on
page 378 .
CLOSQLCSR
*ENDJOB *ENDSQL
or *ENDACTGRP
Implicit closing of
SQL cursor is not
done when the
program invocation
ends.
See Improving
Performance by
Retaining Cursor
Positions for Non-ILE
Program Calls on
page 384 .
DLYPRP
*YES
Complete validation
of the prepared
statement is delayed
until the statement is
run or opened.
See Improving
Performance of SQL
PREPARE Statements
on page 387.
TGTRLS
*CURRENT (the
default)
See Improved
Performance by
Structure Parameter
Passing Techniques
on page 389.
Some of these options may be suitable for most of your applications. Use the
command CRTDUPOBJ to create a copy of the SQL CRTSQLxxx command and the
CHGCMDDFT command to customize the optimal values for the precompile
parameters. The DSPPGM, DSPSRVPGM, DSPMOD, or PRTSQLINF commands
can be used to show the precompile options used for an existing program object.
388
The second method is to create a data structure with an element for each host
variable referenced in the statement. Then that data structure could be passed as a
parameter. For example:
CALL QSQROUTE
(SQLCA, hostvariable structure)
Chapter 22. DB2 for AS/400 Data Management and the Query Optimizer
389
DS
1
2
1
1 A
2 B
2 C
In the above example, if ATABLE has only one or two columns, the SQLCODE
will be set to +326. When the assignment to C from the SQL structure is done,
the contents of A and B will be blank instead of the value of the column
corresponding to A and B.
v With the original parameter passing technique, SQLCODE -302 or -304 is
returned when a conversion error occurs (because of numeric data that is not
valid) while processing the data for a host variable. However, with the structure
parameter passing technique, SQL does not detect this error. The conversion
error occurs in the host language statements that reference the host variable. For
example, if a DECIMAL(5,2) input host variable contains the invalid data
FFFFFFX, an error will occur in the host language when the data is moved into
the data structure.
v The structure created by SQL uses names that start with the letters SQL. If
existing programs use variable names starting with SQL, those names may
conflict with the SQL-created names.
v The contents of the SQL-created data structure must not be changed by the
application programs.
390
v
v
v
v
v
Chapter 22. DB2 for AS/400 Data Management and the Query Optimizer
391
*MAX
The query optimizer can choose to use either I/O or SMP parallel processing
to process the query. SMP parallel processing can be used only if the DB2
Symmetric Multiprocessing feature is installed. The choices made by the query
optimizer are similar to those made for parameter value *OPTIMIZE, except
the optimizer assumes that all active memory in the pool can be used to
process the query.
The default value of the QQRYDEGREE system value is *NONE, so the value must
be changed if parallel query processing is desired as the default for jobs run on the
system.
Changing this system value affects all jobs that will be run or are currently running
on the system whose DEGREE query attribute is *SYSVAL. However, queries that
have already been started or queries using reusable ODPs are not affected.
392
Job: B,I
Pgm: B,I
(1)
REXX: B,I
Exec
(2)
CHGQRYA
*
JOB(
user-name/
job-name
job-number/
QRYTIMLMT(
*SAME
*NOMAX
*SYSVAL
seconds
DEGREE (
*SAME
*NONE
*IO
*OPTIMIZE
*MAX
*SYSVAL
*ANY
*NBRTASKS number-of-tasks
ASYNCJ (
*SAME
*LOCAL
*DIST
*NONE
*ANY
APYRMT (
*SAME
*YES
*NO
Notes:
1. Value *ANY is equivalent to value *IO.
2. All parameters preceding this point can be specified in positional form.
393
optimizer are similar to those made for parameter value *OPTIMIZE except the
optimizer assumes that all active memory in the pool can be used to process
the query.
*NBRTASKS number-of-tasks
Specifies the number of tasks to be used when the query optimizer chooses to
use SMP parallel processing to process a query. I/O parallelism is also allowed.
SMP parallel processing can be used only if the DB2 Symmetric
Multiprocessing feature is installed.
Using a number of tasks less than the number of processors available on the
system restricts the number of processors used simultaneously for running a
given query. A larger number of tasks ensures that the query is allowed to use
all of the processors available on the system to run the query. Too many tasks
can degrade performance because of the overcommitment of active memory
and the overhead cost of managing all of the tasks.
*SYSVAL
Specifies that the processing option used should be set to the current value of
the QQRYDEGREE system value.
*ANY
Parameter value *ANY has the same meaning as *IO. The *ANY value is
maintained for compatibility with prior releases.
The initial value of the DEGREE attribute for a job is *SYSVAL.
See the CL Reference (Abridged) book for more information about the CHGQRYA
command.
394
To retrieve the same rows in reverse order, simply specify that the order is
descending, as in this statement:
SELECT * FROM DEPARTMENT
WHERE LOCATION = 'MINNESOTA'
ORDER BY DEPTNO DESC
A cursor on the second statement would retrieve rows in exactly the opposite
order from a cursor on the first statement. But that is guaranteed only if the first
statement specifies a unique ordering.
If both statements are required in the same program, it might be useful to have
two indexes on the DEPTNO column, one in ascending order and one in
descending order.
395
Once the cursor is positioned at the end of the table, the program can use the
PRIOR or RELATIVE scroll options to position and fetch data starting from the end
of the table.
Comments
EXEC SQL
DECLARE THISEMP DYNAMIC SCROLL CURSOR FOR
SELECT EMPNO, WORKDEPT, BONUS
FROM CORPDATA.EMPLOYEE
WHERE WORKDEPT = D11
FOR UPDATE OF BONUS
END-EXEC.
EXEC SQL
OPEN THISEMP
END-EXEC.
EXEC SQL
WHENEVER NOT FOUND
GO TO CLOSE-THISEMP
END-EXEC.
EXEC SQL
FETCH NEXT FROM THISEMP
FOR 5 ROWS
INTO :DEPTINFO :IND-ARRAY
END-EXEC.
... determine if any employees in department D11 receive a
bonus less than $500.00. If so, update that record to the new
minimum of $500.00.
396
DEPTINFO and
IND-ARRAY are declared
in the program as a host
structure array and an
indicator array.
Comments
EXEC SQL
FETCH RELATIVE :NUMBACK FROM THISEMP
END-EXEC.
EXEC SQL
UPDATE CORPDATA.EMPLOYEE
SET BONUS = 500
WHERE CURRENT OF THISEMP
END-EXEC.
EXEC SQL
FETCH RELATIVE :NUMBACK FROM THISEMP
FOR 5 ROWS
INTO :DEPTINFO :IND-ARRAY
END-EXEC.
Restrictions
You cannot use FOR UPDATE OF with a select-statement that includes any of
these elements:
v
v
v
v
v
v
v
The first FROM clause identifies more than one table or view.
The first FROM clause identifies a read-only view.
The first SELECT clause specifies the keyword DISTINCT.
The outer subselect contains a GROUP BY clause.
The outer subselect contains a HAVING clause.
The first SELECT clause contains a column function.
The select-statement contains a subquery such that the base object of the outer
subselect and of the subquery is the same table.
v The select-statement contains a UNION or UNION ALL operator.
v The select-statement includes a FOR READ ONLY clause.
v The SCROLL keyword is specified without DYNAMIC.
If a FOR UPDATE OF clause is specified, you cannot update columns that were
not named in the FOR UPDATE OF clause. But you can name columns in the FOR
UPDATE OF clause that are not in the SELECT list, as in this example:
SELECT A, B, C FROM TABLE
FOR UPDATE OF A,E
Do not name more columns than you need in the FOR UPDATE OF clause;
indexes on those columns are not used when you access the table.
397
398
399
400
To call the first display that allows you to customize the sample program, specify
the following command on the command line.
========> CALL QSQ8HC3
The following display appears. From this display, you can customize your database
sample program.
DB2 for OS/400 ORGANIZATION APPLICATION
ACTION...........:
D (DISPLAY)
OBJECT...........:
DS (DEPT STRUCTURE)
__
A (ADD)
U (UPDATE)
E (ERASE)
DE (DEPARTMENT)
SEARCH CRITERIA..:
__
DI (DEPARTMENT ID)
DN (DEPARTMENT NAME)
EI (EMPLOYEE ID)
MI (MANAGER ID)
EN (EMPLOYEE NAME)
EM (EMPLOYEE)
MN (MANAGER NAME)
LOCATION.........:
________________
DATA.............:
_______________________________
Bottom
F3=Exit
401
CRTSQLPKG Authorization
When creating an SQL package on an AS/400 system the authorization ID used
must have *USE authority to the CRTSQLPKG command.
402
v SRTSEQ(*LANGIDUNQ)
v SRTSEQ(*LANGIDSHR)
v SRTSEQ(library-name/table-name)
Note: When connecting to a DB2 Universal Database application server, the
following additional rules apply:
v
v
v
v
The specified date and time formats must be the same format
A value of *BLANK must be used for the TEXT parameter
Default collections (DFTRDBCOL) are not supported
The CCSID of the source program from which the package is being created must
not be 65535; if 65535 is used, an empty package is created.
DESCRIBE TABLE
COMMIT
ROLLBACK
CONNECT
SET CONNECTION
DISCONNECT
RELEASE
403
Unit of Work
Because package creation implicitly performs a commit or rollback, the commit
definition must be at a unit of work boundary before the package creation is
attempted. The following conditions must all be true for a commit definition to be
at a unit of work boundary:
v SQL is at a unit of work boundary.
v There are no local or DDM files open using commitment control and no closed
local or DDM files with pending changes.
v There are no API resources registered.
v There are no LU 6.2 resources registered that are not associated with DRDA or
DDM.
Labels
You can use the LABEL ON statement to create a description for the SQL package.
Consistency Token
The program and its associated SQL package contain a consistency token that is
checked when a call is made to the SQL package. The consistency tokens must
match or the package cannot be used. It is possible for the program and SQL
package to appear to be uncoordinated. Assume the program is on the AS/400
system and the application server is another AS/400 system. The program is
running in session A and it is recreated in session B (where the SQL package is
also recreated). The next call to the program in session A could result in a
consistency token error. To avoid locating the SQL package on each call, SQL
maintains a list of addresses for SQL packages that are used by each session. When
session B re-creates the SQL package, the old SQL package is moved to the
QRPLOBJ library. The address to the SQL package in session A is still valid. (This
situation can be avoided by creating the program and SQL package from the
session that is running the program, or by submitting a remote command to delete
the old SQL package before creating the program.)
404
To use the new SQL package, you should end the connection with the remote
system. You can either sign off the session and then sign on again, or you can use
the interactive SQL (STRSQL) command to issue a DISCONNECT for unprotected
network connections or a RELEASE followed by a COMMIT for protected
connections. RCLDDMCNV should then be used to end the network connections.
Call the program again.
405
APPC conversation may or may not have been kept up, depending on the jobs
DDMCNV attribute value, and whether the conversation was with an AS/400 or
other type of system.
TCP/IP terminology does not include the term conversation. A similar concept
exists, however. With the advent of TCP/IP support by DRDA, use of the term
conversation will be replaced, in this book, by the more general term connection,
unless the discussion is specifically about an APPC conversation. Therefore, there
are now two different types of connections about which the reader must be aware:
SQL connections of the type described above, and network connections which
replace the term conversation.
Where there would be the possibility of confusion between the two types of
connections, the word will be qualified by SQL or network to allow the reader
to understand the intended meaning.
SQL connections are managed at the activation group level. Each activation group
within a job manages its own connections and these connections are not shared
across activation groups. For programs that run in the default activation group,
connections are still managed as they were prior to Version 2 Release 3.
The following is an example of an application that runs in multiple activation
groups. This example is used to illustrate the interaction between activation
groups, connection management, and commitment control. It is not a
recommended coding style.
406
....
EXEC SQL
CONNECT TO SYSC;
EXEC SQL
DECLARE C1 CURSOR FOR
SELECT ....;
EXEC SQL
OPEN C1;
do {
EXEC SQL
FETCH C1 INTO :st1;
EXEC SQL
UPDATE ...
SET COL1 = COL1+10
WHERE CURRENT OF C1;
PGM3(st1);
} while SQLCODE == 0;
EXEC SQL
CLOSE C1;
EXEC SQL COMMIT;
407
SYSA
SYSB (Remote)
Job:
Call
Job:
Default Activation
Group:
Default Activation
Group:
SQL Package
for PGM1
Connect
PGM1
Call
SYSC (Remote)
Job:
System-Named
Activation Group:
PGM2
Call
Default Activation
Group:
Connect
SQL Package
for PGM2
Return Call
Activation Group
APPGRP:
SYSD (Remote)
Job:
PGM3
Connect
Default Activation
Group:
SQLPackage
for PGM3
RV2W577-3
408
SYSB
SYSA
Job:
Job:
Default ActivationGroup:
Connect
Job:
System-Named
Activation Group:
Connect
RV2W578-2
409
For a distributed program, the implicit SQL connection is to the relational database
specified on the RDB parameter. For a nondistributed program, the implicit SQL
connection is to the local relational database.
SQL will end any active connections in the default activation group when SQL
becomes not active. SQL becomes not active when:
v The application requester detects the first active SQL program for the process
has ended and the following are all true:
There are no pending SQL changes
There are no connections using protected connections
A SET TRANSACTION statement is not active
No programs that were precompiled with CLOSQLCSR(*ENDJOB) were run.
If there are pending changes, protected connections, or an active SET
TRANSACTION statement, SQL is placed in the exited state. If programs
precompiled with CLOSQLCSR(*ENDJOB) were run, SQL will remain active for
the default activation group until the job ends.
v At the end of a unit of work if SQL is in the exited state. This occurs when you
issue a COMMIT or ROLLBACK command outside of an SQL program.
v At the end of a job.
Distributed Support
DB2 for AS/400 supports two levels of distributed relational database:
v Remote unit of work (RUW)
Remote unit of work is where the preparation and running of SQL statements
occurs at only one application server during a unit of work. An activation group
with an application process at an application requester can connect to an
application server and, within one or more units of work, run any number of
410
static or dynamic SQL statements that refer to objects on the application server.
Remote unit of work is also referred to as DRDA level 1.
v Distributed unit of work (DUW)
Distributed unit of work is where the preparation and running of SQL
statements can occur at multiple applications servers during a unit of work.
However, a single SQL statement can only refer to objects located at a single
application server. Distributed unit of work is also referred to as DRDA level 2.
Distributed unit of work allows:
Update access to multiple application servers in one logical unit of work
or
Update access to a single application server with read access to multiple
application servers, in one logical unit of work.
Whether multiple application servers can be updated in a unit of work is
dependent on the existence of a sync point manager at the application requester,
sync point managers at the application servers, and two-phase commit protocol
support between the application requester and the application servers.
The sync point manager is a system component that coordinates commit and
rollback operations among the participants in the two-phase commit protocol.
When running distributed updates, the sync point managers on the different
systems cooperate to ensure that resources reach a consistent state. The protocols
and flows used by sync point managers are also referred to as two-phase
commit protocols.
If two-phase commit protocols will be used, the connection is a protected
resource; otherwise the connection is an unprotected resource.
The type of data transport protocols used between systems affects whether the
network connection is protected or unprotected. In OS/400 V4R2, TCP/IP
connections are always unprotected; thus they can participate in a distributed
unit of work in only a limited way.
For example, if the first connection made from the program is to an AS/400 over
TCP/IP, updates can be performed over it, but any subsequent connections, even
over APPC, will be read only.
Note that when using Interactive SQL, the first SQL connection is to the local
system. Therefore in order to make updates to a remote system using TCP/IP,
you must do a RELEASE ALL followed by a COMMIT to end all SQL
connections before doing the CONNECT TO remote-tcp-system.
411
412
413
Application
Server Supports
Two-phase
Commit
Application
Server Supports
Distributed Unit
of Work
No
No
No
No
No
No
No
Yes
No
No
Yes
No
No
No
Yes
Yes
No
Yes
No
No
No
Yes
No
Yes
No
Yes
Yes
No
No
Yes
Yes
Yes
Yes
No
No
No
Yes
No
No
Yes
Yes
No
Yes
No
Yes
No
Yes
Yes
Yes
Yes
No
No
N/A *
Yes
Yes
No
Yes
N/A *
Yes
Yes
Yes
No
Yes
Yes
Yes
Yes
Connect under
Commitment
Control
SQLERRD(4)
*DRDA does not allow protected connections to be used to application servers which only
support remote unit of work (DRDA1). This includes all DB2 for AS/400 TCP/IP
connections.
414
415
SQLERRD(4)
Connection Exists to
Updateable Remote
Unit of Work
Application Server
Where First
Committable Update
Occurred *
SQLERRD(3)
--
--
--
--
Yes
--
No
no updates
No
one-phase
No
this connection
No
two-phase
Yes
--
No
no updates
No
one-phase
No
this connection
No
two-phase
Yes
--
No
no updates
No
one-phase
No
this connection
No
two-phase
416
v If the unit of work will perform updates at more than one application server and
commitment control will be used, all connections over which updates will be
done should be made using commitment control. If the connections are done not
using commitment control and later committable updates are performed,
read-only connections for the unit of work are likely to result.
v Other non-SQL commit resources, such as local files, DDM files, and
commitment control API resources, will affect the updateable and read-only
status of a connection.
v If connecting using commitment control to an application server that does not
support distributed unit of work (for example, a V4R2 AS/400 using TCP/IP),
that connection will be either updateable or read-only. If the connection is
updateable it is the only updateable connection.
Ending Connections
Because remote connections use resources, connections that are no longer going to
be used should be ended as soon as possible. Connections can be ended implicitly
or explicitly. For a description of when connections are implicitly ended see
Implicit Connection Management for the Default Activation Group on page 409
and Implicit Connection Management for Nondefault Activation Groups on
page 410 . Connections can be explicitly ended by either the DISCONNECT
statement or the RELEASE statement followed by a successful COMMIT. The
DISCONNECT statement can only be used with connections that use unprotected
connections or with local connections. The DISCONNECT statement will end the
connection when the statement is run. The RELEASE statement can be used with
either protected or unprotected connections. When the RELEASE statement is run,
the connection is not ended but instead placed into the released state. A connection
that is in the release stated can still be used. The connection is not ended until a
successful COMMIT is run. A ROLLBACK or an unsuccessful COMMIT will not
end a connection in the released state.
When a remote SQL connection is established, a DDM network connection (APPC
conversation or TCP/IP connection) is used. When the SQL connection is ended,
the network connection may either be placed in the unused state or dropped.
Whether a network connection is dropped or placed in the unused state depends
on the DDMCNV job attribute. If the job attribute value is *KEEP and the
connection is to another AS/400, the connection becomes unused. If the job
attribute value is *DROP and the connection is to another AS/400, the connection
is dropped. If the connection is to a non-AS/400, the connection is always
dropped. *DROP is desirable in the following situations:
v When the cost of maintaining the unused connection is high and the connection
will not be used relatively soon.
v When running with a mixture of programs, some compiled with RUW
connection management and some programs compiled with DUW connection
management. Attempts to run programs compiled with RUW connection
management to remote locations will fail when protected connections exist.
v When running with protected connections using either DDM or DRDA.
Additional overhead is incurred on commits and rollbacks for unused protected
connections.
The Reclaim DDM connections (RCLDDMCNV) command may be used to end all
unused connections.
417
418
while (SQLCODE==0)
{
/* Fetch the first row */
EXEC SQL FETCH C1 INTO :partnumber,:price;
/* Update the row which indicates that the updates have been
propagated to the other sites */
EXEC SQL UPDATE PARTS SET SITES_UPDATED='Y'
WHERE CURRENT OF C1;
/* Check if the part data is on SYSB */
if ((partnumber > 10) && (partnumber < 100))
{
/* Make SYSB the current connection and update the price */
EXEC SQL SET CONNECTION SYSB;
EXEC SQL UPDATE PARTS
SET PRICE=:price
WHERE PARTNO=:partnumber;
}
CONTINUE;
that are no longer being used */
In this program, there are 3 application servers active: LOCALSYS which the local
system, and 2 remote systems, SYSB and SYSC. SYSB and SYSC also support
distributed unit of work and two-phase commit. Initially all connections are made
active by using the CONNECT statement for each of the application servers
involved in the transaction. When using DUW, a CONNECT statement does not
disconnect the previous connection, but instead places the previous connection in
Chapter 24. Distributed Relational Database Function
419
the dormant state. After all the application servers, have been connected, the local
connection is made the current connection using the SET CONNECTION
statement. The cursor is then opened and the first row of data fetched. It is then
determined at which application servers the data needs to be updated. If SYSB
needs to be updated, then SYSB is made the current connection using the SET
CONNECTION statement and the update is run. The same is done for SYSC. The
changes are then committed. Because two-phase commit is being used, it is
guaranteed that the changes are committed at the local system and the two remote
systems. Because the cursor was declared WITH HOLD, it remains open after the
commit. The current connection is then changed to the local system so that the
next row of data can be fetched. This set of fetches, updates, and commits is
repeated until all the data has been processed. After all the data has been fetched,
the connections for both remote systems are released. They can not be
disconnected because they use protected connections. After the connections are
released, a commit is issued to end the connections. The local system is still
connected and continues processing.
420
.....
EXEC SQL DECLARE C1 CURSOR FOR
SELECT * FROM CORPDATA.EMPLOYEE;
/* Connect to local and open C1 */
EXEC SQL CONNECT TO LOCALSYS;
EXEC SQL OPEN C1;
/* Connect to the remote system and open C1 */
EXEC SQL CONNECT TO SYSA;
EXEC SQL OPEN C1;
/* Keep processing until done */
while (NOT_DONE) {
/* Fetch a row of data from the local system */
EXEC SQL SET CONNECTION LOCALSYS;
EXEC SQL FETCH C1 INTO :local_emp_struct;
/* Fetch a row of data from the remote system */
EXEC SQL SET CONNECTION SYSA;
EXEC SQL FETCH C1 INTO :rmt_emp_struct;
/* Process the data */
.....
}
/* Close the cursor on the remote system */
EXEC SQL CLOSE C1;
/* Close the cursor on the local system */
EXEC SQL SET CONNECTION LOCALSYS;
EXEC SQL CLOSE C1;
.....
Problem Handling
The primary strategy for capturing and reporting error information for the AS/400
distributed database function is called first failure data capture (FFDC). The
purpose of FFDC support is to provide accurate information on errors detected in
the DDM components of the OS/400 system from which an APAR 17 can be
421
created. By means of this function, key structures and the DDM data stream are
automatically dumped to a spool file. The first 1024 bytes of the error information
are also logged in the system error log. This automatic dumping of error
information on the first occurrence of an error means that the failure should not
have to be recreated to be reported by the customer. FFDC is active in both the
application requester and application server functions of the OS/400 DDM
component. However, for the FFDC data to be logged, the system value
QSFWERRLOG must be set to *LOG.
Note: Not all negative SQLCODEs are dumped; only those that can be used to
produce an APAR are dumped. For more information on handling problems
on distributed relational database operations, see the Distributed Database
Problem Determination Guide
When an SQL error is detected, an SQLCODE with a corresponding SQLSTATE is
returned in the SQLCA. For more information on these codes, see Appendix B.
SQLCODEs and SQLSTATEs.
422
NOT NULL,
NOT NULL,
,
NOT NULL )
Description
DEPTNO
DEPTNAME
MGRNO
ADMRDEPT
423
DEPARTMENT
DEPTNO
DEPTNAME
MGRNO
ADMRDEPT
A00
000010
A00
B01
PLANNING
000020
A00
C01
INFORMATION CENTER
000030
A00
D01
DEVELOPMENT CENTER
A00
D11
MANUFACTURING SYSTEMS
000060
D01
D21
ADMINISTRATION SYSTEMS
000070
D01
E01
SUPPORT SERVICES
000050
A00
E11
OPERATIONS
000090
E01
E21
SOFTWARE SUPPORT
000100
E01
NOT NULL,
NOT NULL,
NOT NULL,
NOT NULL,
,
,
,
,
NOT NULL,
,
,
,
,
)
424
Column Name
Description
EMPNO
Employee number
FIRSTNME
MIDINIT
LASTNAME
WORKDEPT
PHONENO
HIREDATE
Date of hire
JOB
EDLEVEL
SEX
BIRTHDATE
Date of birth
EMP NO
000010
000020
000030
000050
000060
000070
000090
000100
000110
000120
000130
000140
000150
000160
000170
000180
000190
000200
000210
000220
000230
000240
000250
000260
000270
000280
000290
000300
000310
000320
000330
000340
FIRST
NAME
CHRISTINE
MICHAEL
SALLY
JOHN
IRVING
EVA
EILEEN
THEODORE
VINCENZO
SEAN
DOLORES
HEATHER
BRUCE
ELIZABETH
MASATOSHI
MARILYN
JAMES
DAVID
WILLIAM
JENNIFER
JAMES
SALVATORE
DANIEL
SYBIL
MARIA
ETHEL
JOHN
PHILIP
MAUDE
RAMLAL
WING
JASON
MID
INIT
I
L
A
B
F
D
W
Q
G
M
A
R
J
S
H
T
K
J
M
S
P
L
R
R
X
F
V
R
Column Name
Description
SALARY
BONUS
COMM
LASTNAME
HAAS
THOMPSON
KWAN
GEYER
STERN
PULASKI
HENDERSON
SPENSER
LUCCHESSI
O'CONNELL
QUINTANA
NICHOLLS
ADAMSON
PIANKA
YOSHIMURA
SCOUTTEN
WALKER
BROWN
JONES
LUTZ
JEFFERSON
MARINO
SMITH
JOHNSON
PEREZ
SCHNEIDER
PARKER
SMITH
SETRIGHT
MEHTA
LEE
GOUNOT
WORK
DEPT
A00
B01
C01
E01
D11
D21
E11
E21
A00
A00
C01
C01
D11
D11
D11
D11
D11
D11
D11
D11
D21
D21
D21
D21
D21
E11
E11
E11
E11
E21
E21
E21
PHONE
NO
3978
3476
4738
6789
6423
7831
5498
0972
3490
2167
4578
1793
4510
3782
2890
1682
2986
4501
0942
0672
2094
3780
0961
8953
9001
8997
4502
2095
3332
9990
2103
5698
HIRE DATE
1965-01-01
1973-10-10
1975-04-05
1949-08-17
1973-09-14
1980-09-30
1970-08-15
1980-06-19
1958-05-16
1963-12-05
1971-07-28
1976-12-15
1972-02-12
1977-10-11
1978-09-15
1973-07-07
1974-07-26
1966-03-03
1979-04-11
1968-08-29
1966-11-21
1979-12-05
1969-10-30
1975-09-11
1980-09-30
1967-03-24
1980-05-30
1972-06-19
1964-09-12
1965-07-07
1976-02-23
1947-05-05
JOB
PRES
MANAGER
MANAGER
MANAGER
MANAGER
MANAGER
MANAGER
MANAGER
SALESREP
CLERK
ANALYST
ANALYST
DESIGNER
DESIGNER
DESIGNER
DESIGNER
DESIGNER
DESIGNER
DESIGNER
DESIGNER
CLERK
CLERK
CLERK
CLERK
CLERK
OPERATOR
OPERATOR
OPERATOR
OPERATOR
FILEREP
FILEREP
FILEREP
ED
LEVEL
18
18
20
16
16
16
16
14
19
14
16
18
16
17
16
17
16
16
17
18
14
17
15
16
15
17
12
14
12
16
14
16
SEX
F
M
F
M
M
F
F
M
M
M
F
F
M
F
M
F
M
M
M
F
M
M
M
F
F
F
M
M
F
M
M
M
BIRTH DATE
1933-08-24
1948-02-02
1941-05-11
1925-09-15
1945-07-07
1953-05-26
1941-05-15
1956-12-18
1929-11-05
1942-10-18
1925-09-15
1946-01-19
1947-05-17
1955-04-12
1951-01-05
1949-02-21
1952-06-25
1941-05-29
1953-02-23
1948-03-19
1935-05-30
1954-03-31
1939-11-12
1936-10-05
1953-05-26
1936-03-28
1946-07-09
1936-10-27
1931-04-21
1932-08-11
1941-07-18
1926-05-17
SALARY
52750
41250
38250
40175
32250
36170
29750
26150
46500
29250
23800
28420
25280
22250
24680
21340
20450
27740
18270
29840
22180
28760
19180
17250
27380
26250
15340
17750
15900
19950
25370
23840
BONUS
1000
800
800
800
500
700
600
500
900
600
500
600
500
400
500
500
400
600
400
600
400
600
400
300
500
500
300
400
300
400
500
500
COMM
4220
3300
3060
3214
2580
2893
2380
2092
3720
2340
1904
2274
2022
1780
1974
1707
1636
2217
1462
2387
1774
2301
1534
1380
2190
2100
1227
1420
1272
1596
2030
1907
NOT NULL,
NOT NULL,
NOT NULL,
,
,
)
Description
EMPNO
Employee ID number
PROJNO
ACTNO
425
Description
EMPTIME
EMSTDATE
EMENDATE
EMP_ACT
EMPNO
PROJNO
ACTNO
EMPTIME
EMSTDATE
EMENDATE
000010
AD3100
10
.50
1982-01-01
1982-07-01
000070
AD3110
10
1.00
1982-01-01
1983-02-01
000230
AD3111
60
1.00
1982-01-01
1982-03-15
000230
AD3111
60
.50
1982-03-15
1982-04-15
000230
AD3111
70
.50
1982-03-15
1982-10-15
000230
AD3111
80
.50
1982-04-15
1982-10-15
000230
AD3111
180
1.00
1982-10-15
1983-01-01
000240
AD3111
70
1.00
1982-02-15
1982-09-15
000240
AD3111
80
1.00
1982-09-15
1983-01-01
000250
AD3112
60
1.00
1982-01-01
1982-02-01
000250
AD3112
60
.50
1982-02-01
1982-03-15
000250
AD3112
60
.50
1982-12-01
1983-01-01
000250
AD3112
60
1.00
1983-01-01
1983-02-01
000250
AD3112
70
.50
1982-02-01
1982-03-15
000250
AD3112
70
1.00
1982-03-15
1982-08-15
000250
AD3112
70
.25
1982-08-15
1982-10-15
000250
AD3112
80
.25
1982-08-15
1982-10-15
000250
AD3112
80
.50
1982-10-15
1982-12-01
000250
AD3112
180
.50
1982-08-15
1983-01-01
000260
AD3113
70
.50
1982-06-15
1982-07-01
000260
AD3113
70
1.00
1982-07-01
1983-02-01
000260
AD3113
80
1.00
1982-01-01
1982-03-01
000260
AD3113
80
.50
1982-03-01
1982-04-15
000260
AD3113
180
.50
1982-03-01
1982-04-15
000260
AD3113
180
1.00
1982-04-15
1982-06-01
000260
AD3113
180
.50
1982-06-01
1982-07-01
000270
AD3113
60
.50
1982-03-01
1982-04-01
000270
AD3113
60
1.00
1982-04-01
1982-09-01
000270
AD3113
60
.25
1982-09-01
1982-10-15
000270
AD3113
70
.75
1982-09-01
1982-10-15
426
EMPNO
PROJNO
ACTNO
EMPTIME
EMSTDATE
EMENDATE
000270
AD3113
70
1.00
1982-10-15
1983-02-01
000270
AD3113
80
1.00
1982-01-01
1982-03-01
000270
AD3113
80
.50
1982-03-01
1982-04-01
000030
IF1000
10
.50
1982-06-01
1983-01-01
000130
IF1000
90
1.00
1982-01-01
1982-10-01
000130
IF1000
100
.50
1982-10-01
1983-01-01
000140
IF1000
90
.50
1982-10-01
1983-01-01
000030
IF2000
10
.50
1982-01-01
1983-01-01
000140
IF2000
100
1.00
1982-01-01
1982-03-01
000140
IF2000
100
.50
1982-03-01
1982-07-01
000140
IF2000
110
.50
1982-03-01
1982-07-01
000140
IF2000
110
.50
1982-10-01
1983-01-01
000010
MA2100
10
.50
1982-01-01
1982-11-01
000110
MA2100
20
1.00
1982-01-01
1982-03-01
000010
MA2110
10
1.00
1982-01-01
1983-02-01
000200
MA2111
50
1.00
1982-01-01
1982-06-15
000200
MA2111
60
1.00
1982-06-15
1983-02-01
000220
MA2111
40
1.00
1982-01-01
1983-02-01
000150
MA2112
60
1.00
1982-01-01
1982-07-15
000150
MA2112
180
1.00
1982-07-15
1983-02-01
000170
MA2112
60
1.00
1982-01-01
1983-06-01
000170
MA2112
70
1.00
1982-06-01
1983-02-01
000190
MA2112
70
1.00
1982-02-01
1982-10-01
000190
MA2112
80
1.00
1982-10-01
1983-10-01
000160
MA2113
60
1.00
1982-07-15
1983-02-01
000170
MA2113
80
1.00
1982-01-01
1983-02-01
000180
MA2113
70
1.00
1982-04-01
1982-06-15
000210
MA2113
80
.50
1982-10-01
1983-02-01
000210
MA2113
180
.50
1982-10-01
1983-02-01
000050
OP1000
10
.25
1982-01-01
1983-02-01
000090
OP1010
10
1.00
1982-01-01
1983-02-01
000280
OP1010
130
1.00
1982-01-01
1983-02-01
000290
OP1010
130
1.00
1982-01-01
1983-02-01
000300
OP1010
130
1.00
1982-01-01
1983-02-01
000310
OP1010
130
1.00
1982-01-01
1983-02-01
000050
OP2010
10
.75
1982-01-01
1983-02-01
000100
OP2010
10
1.00
1982-01-01
1983-02-01
000320
OP2011
140
.75
1982-01-01
1983-02-01
427
EMPNO
PROJNO
ACTNO
EMPTIME
EMSTDATE
EMENDATE
000320
OP2011
150
.25
1982-01-01
1983-02-01
000330
OP2012
140
.25
1982-01-01
1983-02-01
000330
OP2012
160
.75
1982-01-01
1983-02-01
000340
OP2013
140
.50
1982-01-01
1983-02-01
000340
OP2013
170
.50
1982-01-01
1983-02-01
000020
PL2100
30
1.00
1982-01-01
1982-09-15
NOT
NOT
NOT
NOT
NULL,
NULL,
NULL,
NULL,
,
,
,
)
Description
PROJNO
Project number
PROJNAME
Project name
DEPTNO
RESPEMP
PRSTAFF
PRSTDATE
PRENDATE
MAJPROJ
PROJECT
PROJNO
PROJNAME
AD3100
RESPEMP
PRSTAFF
PRSTDATE
PRENDATE MAJPROJ
000010
6.5
1982-01-01
1983-02-01
AD3110
GENERAL
ADMIN SYSTEMS
D21
000070
1982-01-01
1983-02-01
AD3100
AD3111
PAYROLL
PROGRAMMING
D21
000230
1982-01-01
1983-02-01
AD3110
AD3112
PERSONNEL
PROGRAMMING
D21
000250
1982-01-01
1983-02-01
AD3110
428
DEPTNO
PROJNO
PROJNAME
DEPTNO
RESPEMP
PRSTAFF
PRSTDATE
PRENDATE MAJPROJ
AD3113
ACCOUNT
PROGRAMMING
D21
000270
1982-01-01
1983-02-01
AD3110
IF1000
000030
1982-01-01
1983-02-01
IF2000
USER
EDUCATION
C01
000030
1982-01-01
1983-02-01
MA2100
WELD LINE
AUTOMATION
D01
000010
12
1982-01-01
1983-02-01
MA2110
WL
PROGRAMMING
D11
000060
1982-01-01
1983-02-01
MA2100
MA2111
W L PROGRAM
DESIGN
D11
000220
1982-01-01
1982-12-01
MA2110
MA2112
W L ROBOT
DESIGN
D11
000150
1982-01-01
1982-12-01
MA2110
MA2113
W L PROD CONT
PROGS
D11
000160
1982-02-15
1982-12-01
MA2110
OP1000
OPERATION
SUPPORT
E01
000050
1982-01-01
1983-02-01
OP1010
OPERATION
E11
000090
1982-01-01
1983-02-01
OP1000
OP2000
GEN SYSTEMS
SERVICES
E01
000050
1982-01-01
1983-02-01
OP2010
SYSTEMS
SUPPORT
E21
000100
1982-01-01
1983-02-01
OP2000
OP2011
SCP SYSTEMS
SUPPORT
E21
000320
1982-01-01
1983-02-01
OP2010
OP2012
APPLICATIONS
SUPPORT
E21
000330
1982-01-01
1983-02-01
OP2010
OP2013
DB/DC SUPPORT
E21
000340
1982-01-01
1983-02-01
OP2010
PL2100
WELD LINE
PLANNING
B01
000020
1982-01-01
1982-09-15
MA2100
CHAR(7),
SMALLINT,
TIME,
TIME)
Description
CLASS_CODE
429
Column Name
Description
DAY
STARTING
ENDING
TIMESTAMP,
CHAR(8),
CHAR(64),
VARCHAR(3000))
Description
RECEIVED
SOURCE
SUBJECT
NOTE_TEXT
The note
430
431
v
v
v
v
v
v
v
v
v
v
v
v
23 Constraint Violation
24 Invalid Cursor State
25 Invalid Transaction State
26 Invalid SQL Statement Identifier
27 Triggered Data Change Violation
28 Invalid Authorization Specification
2B Dependent Privilege Descriptors Still Exist
v
v
v
v
v
v
v
v
v
v
v
v
v
v
42
44
51
53
54
55
56
57
v 58 System Error
For a list of SQLSTATEs that are used by the DB2 family of products, see IBM SQL
Reference, Version 2, SC26-8416. Also available on CD-ROM as a part of the
Transaction Processing Collection Kit CD-ROM, SK2T-0730-11.
When an SQLSTATE other than '00000' is returned from a non-DB2 for AS/400
application server, DB2 for AS/400 attempts to map the SQLSTATE to a DB2 for
AS/400 SQLCODE and message:
v If the SQLSTATE is not recognized by DB2 for AS/400, the common message for
the class is issued.
432
Positive SQLCODEs
N/A
SQLCODE 0
SQL0088
SQLCODE +88
SQLSTATE 01504
SQL0100
SQLCODE +100
SQLSTATE 02000
SQL0138
SQLCODE +114
SQLCODE +138
SQLSTATE 01536
SQLSTATE 01544
SQLCODE +12
SQLSTATE 01545
SQLCODE +30
SQLSTATE 01503
SQL0177
SQLCODE +177
SQLSTATE 01009
SQLCODE +178
SQLSTATE 0100A
SQLCODE +180
SQLSTATE 01534
SQLCODE +181
SQLSTATE 01534
433
SQL0183
SQLCODE +183
SQLSTATE 01535
SQL0551
SQLCODE +551
SQLSTATE 01548
SQL0191
SQL0552
SQLCODE +191
SQLSTATE 01547
SQLCODE +552
SQLSTATE 01542
SQL0204
SQL0569
SQLCODE +204
SQLSTATE 01532
SQLCODE +304
01547, 01565
SQLCODE +569
SQLSTATE 01006
SQLSTATE 01515,
SQL0570
SQLCODE +570
SQLSTATE 01007
SQL0326
SQL0595
SQLCODE +326
SQLSTATE 01557
SQLCODE +595
SQLSTATE 01526
SQL0331
SQL0596
SQLCODE +331
SQLSTATE 01520
SQLSTATE 01517
SQLCODE +403
SQLSTATE 01522
SQLCODE +420
SQLSTATE 01565
SQLSTATE 01528
SQLCODE +802
SQLSTATE 01519,
01547, 01564, 01565
SQL0420
SQLCODE +645
SQLSTATE 01002
SQL0335
SQLCODE +596
SQLCODE +863
SQLSTATE 01539
SQL0445
SQL0990
SQLCODE +445
SQLSTATE 01004
SQLSTATE 01593
SQLSTATE 01587
SQL0460
SQLCODE +990
SQLCODE +7905
SQLSTATE 01567
Negative SQLCODEs
SQL0007
SQLCODE -07
SQLSTATE 42601
434
SQL0010
SQLCODE -10
SQLSTATE 42603
SQL0029
SQLCODE -29
SQLSTATE 42601
SQL0105
SQLCODE -105
SQLSTATE 42604
SQL0051
SQL0106
SQLCODE -51
SQLSTATE 3C000
SQLCODE -106
SQLSTATE 42611
SQL0060
SQL0107
SQLCODE -60
SQLSTATE 42815
SQLSTATE 42978
SQLCODE -84
SQLSTATE 42612
SQLSTATE 42622
SQL0080
SQLCODE -107
SQLCODE -109
SQLSTATE 42601
SQLCODE -110
SQLSTATE 42606
SQLCODE -90
SQLSTATE 42618
SQLCODE -112
SQLSTATE 42607
SQL0099
SQL0113
SQLCODE -99
SQLSTATE 42992
SQLCODE -113
2E000, 42602
SQLSTATE 28000,
SQLCODE -101
54010, 54011
SQLSTATE 54001,
SQL0114
SQLCODE -102
SQLCODE -103
SQLSTATE 42604
SQLCODE -104
SQLSTATE 42961
SQLSTATE 54002
SQLCODE -114
SQL0115
SQLCODE -115
SQLSTATE 42601
SQLCODE -117
SQLSTATE 42802
SQLSTATE 42601
SQL0118
SQLCODE -118
SQLSTATE 42902
435
SQL0119
SQLCODE -119
SQLSTATE 42803
SQL0134
SQLCODE -120
SQLSTATE 42903
SQLSTATE 42907
SQL0120
SQLCODE -134
SQLCODE -136
SQLSTATE 54005
SQL0121
SQL0137
SQLCODE -121
SQLSTATE 42701
SQLSTATE 42803
SQLSTATE 42805
SQLCODE -128
SQLSTATE 42601
SQLCODE -138
SQLSTATE 22011
SQL0125
SQLSTATE 54006
SQL0122
SQLCODE -137
SQLCODE -144
SQLSTATE 58003
SQLCODE -145
SQLSTATE 55005
SQLCODE -129
SQLSTATE 54004
SQLCODE -150
SQLSTATE 42807
SQLCODE -130
22025
SQLSTATE 22019,
SQLCODE -131
SQLSTATE 42818
SQLCODE -151
SQLSTATE 42808
SQLCODE -152
SQLSTATE 42809
SQLCODE -153
SQLSTATE 42908
SQLCODE -132
SQLSTATE 42824
SQLCODE -133
SQLSTATE 42906
SQL0154
SQLCODE -154
SQLSTATE 42909
SQLCODE -156
SQLSTATE 42809
436
SQL0157
SQLCODE -157
SQLSTATE 42810
SQL0183
SQLCODE -183
SQLSTATE 22008
SQL0158
SQL0184
SQLCODE -158
SQLSTATE 42811
SQLCODE -184
SQLSTATE 42610
SQL0159
SQL0187
SQLCODE -159
SQLSTATE 42809
SQLCODE -187
SQLSTATE 42816
SQL0160
SQL0188
SQLCODE -160
SQLSTATE 42813
SQLCODE -161
SQLCODE -170
SQLCODE -171
SQLCODE -189
SQLSTATE 22522
SQLSTATE 42605
SQLSTATE 22503,
SQLSTATE 44000
SQLCODE -188
28000, 2E000
SQL0190
SQLCODE -190
SQLSTATE 42837
SQLSTATE 42815
SQL0191
SQLCODE -191
SQLSTATE 22504
SQLCODE -175
SQLSTATE 58028
SQL0192
SQLCODE -180
SQLSTATE 22007
SQLCODE -192
SQLSTATE 42937
SQLCODE -194
SQLSTATE 42848
SQLCODE -181
SQLSTATE 22007
SQLCODE -182
SQL0195
SQLCODE -195
SQLSTATE 42814
SQLSTATE 42816
SQL0196
SQLCODE -196
SQLSTATE 42817
437
SQL0197
SQLCODE -197
SQLSTATE 42877
SQLCODE -198
SQLCODE -199
SQLSTATE 42601
SQLCODE -203
SQLSTATE 42702
SQLCODE -204
SQLCODE -226
SQLSTATE 24507
SQLSTATE 42617
SQL0226
SQLSTATE 42704
SQL0227
SQLCODE -227
SQLSTATE 24513
SQLCODE -228
SQLSTATE 42620
SQLCODE -231
SQLSTATE 22006
SQLCODE -205
SQLSTATE 42703
SQLCODE -250
SQLSTATE 42718
SQL0206
SQL0251
SQLCODE -206
SQLSTATE 42703
SQLCODE -208
SQLSTATE 42707
SQLCODE -251
42602
SQLSTATE 2E000,
SQLCODE -255
SQLSTATE 42999
SQLCODE -212
SQLSTATE 42712
SQLCODE -214
SQLSTATE 42822
SQLCODE -221
SQLSTATE 42873
SQL0256
SQLCODE -256
SQLSTATE 42998
SQLCODE -270
SQLSTATE 42997
SQL0301
SQL0225
SQLCODE -225
SQLSTATE 42872
438
SQLCODE -301
07006,42895
SQLSTATE
SQL0302
SQL0331
SQLCODE -303
42806
SQLSTATE 22001,
SQLCODE -304
22023, 22504
SQLSTATE 22003,
SQLSTATE 22021
SQL0303
SQLCODE -331
SQLCODE -332
SQLSTATE 57017
SQLCODE -334
SQLSTATE 22524
SQLCODE -338
SQLSTATE 42972
SQLCODE -305
SQLSTATE 22002
SQLCODE -306
SQLSTATE 42863
SQLCODE -311
SQLSTATE 22501
SQLCODE -312
SQLSTATE 42618
SQL0351
SQLCODE -351
SQLSTATE 56084
SQLCODE -401
SQLSTATE 42818
SQLCODE -402
SQLSTATE 42819
SQLCODE -404
SQLSTATE 22001
SQLCODE -313
07004
SQLSTATE 07001,
SQL0405
SQLCODE -405
SQLSTATE 42820
SQL0328
SQL0406
SQLCODE -328
SQLSTATE 42996
SQLCODE -330
SQLCODE -406
22023, 22504
SQLSTATE 22003,
SQLSTATE 22021
SQL0407
SQLCODE -407
SQLSTATE 23502
439
SQL0408
SQLCODE -408
SQLSTATE 42821
SQL0440
SQLCODE -440
SQLSTATE 42884
SQL0410
SQL0442
SQLCODE -410
SQLSTATE 42820
SQLCODE -412
SQLCODE -414
SQLSTATE 42824
SQLCODE -415
SQLSTATE 42825
SQLCODE -417
SQLSTATE 42609
SQLCODE -418
SQLSTATE 54023
SQLSTATE 42823
SQLCODE -442
SQLSTATE 42610
SQL0443
SQLCODE -443
38501
SQLSTATE 2Fxxx,
SQLCODE -444
SQLSTATE 42724
SQLCODE -446
SQLSTATE 22003
SQLCODE -448
SQLSTATE 54023
SQLCODE -419
SQLSTATE 42911
SQLCODE -449
SQLSTATE 42878
SQL0420
SQL0451
SQLCODE -420
SQLSTATE 22018
SQLCODE -421
SQLCODE -428
SQLSTATE 25501
SQLCODE -433
SQLSTATE 42815
SQLSTATE 42826
SQLCODE -451
SQLSTATE 22001
SQL0455
SQLCODE -455
SQLSTATE 42882
SQLCODE -461
SQLSTATE 42846
SQLCODE -469
SQLSTATE 42886
440
SQL0470
SQLCODE -470
SQLSTATE 39002
SQL0513
SQLCODE -513
SQLSTATE 42924
SQL0487
SQL0514
SQLCODE -487
SQLSTATE 38001
SQLCODE -514
SQLSTATE 26501
SQL0490
SQL0516
SQLCODE -490
SQLSTATE 428B7
SQLCODE -516
SQLSTATE 26501
SQL0501
SQL0517
SQLCODE -501
SQLSTATE 24501
SQLCODE -502
SQLCODE -517
SQLSTATE 07005
SQLSTATE 24502
SQL0518
SQLCODE -518
SQLSTATE 07003
SQLCODE -503
SQLSTATE 42912
SQL0519
SQLCODE -519
SQLSTATE 24506
SQLCODE -504
SQLSTATE 34000
SQLCODE -507
SQLSTATE 24501
SQLCODE -508
SQLSTATE 24504
SQL0520
SQLCODE -520
SQLSTATE 42828
SQLCODE -525
SQLSTATE 51015
SQLCODE -509
SQLSTATE 42827
SQLSTATE 42828
SQLSTATE 42874
SQL0510
SQLCODE -527
SQLCODE -530
SQLSTATE 23503
SQL0511
SQL0531
SQLCODE -511
SQLSTATE 42829
SQLCODE -531
23504
SQLSTATE 23001,
441
SQL0532
SQLCODE -532
23504
SQLSTATE 23001,
SQLCODE -536
SQLSTATE 42914
SQLCODE -537
SQLCODE -552
SQLSTATE 42502
SQL0552
SQLSTATE 42709
SQL0557
SQLCODE -557
SQLSTATE 42852
SQLCODE -573
SQLSTATE 42890
SQLCODE -574
SQLSTATE 42894
SQLCODE -538
SQLSTATE 42830
SQL0577
SQLCODE -577
2F002
SQLSTATE 38002,
SQLCODE -539
SQLSTATE 42888
SQLCODE -541
SQLSTATE 42891
SQLCODE -543
SQLSTATE 23511
SQLCODE -544
SQLSTATE 23512
SQLCODE -545
SQLSTATE 23513
SQL0579
SQLCODE -579
2F004
SQLSTATE 38004,
SQLCODE -580
SQLSTATE 42625
SQLCODE -581
SQLSTATE 42804
SQLCODE -590
SQLSTATE 42734
SQLCODE -601
SQLSTATE 42710
SQLCODE -546
SQLSTATE 42621
SQLCODE -551
SQLSTATE 42501
442
SQL0602
SQLCODE -602
SQLSTATE 54008
SQL0603
SQLCODE -603
SQLSTATE 23515
SQL0631
SQLCODE -631
SQLSTATE 54008
SQL0604
SQL0637
SQLCODE -604
SQLSTATE 42611
SQLCODE -637
SQLSTATE 42614
SQL0607
SQL0642
SQLCODE -607
SQLSTATE 42832
SQLCODE -642
SQLSTATE 54021
SQL0612
SQL0666
SQLCODE -612
SQLSTATE 42711
SQLCODE -613
SQLCODE -614
SQLCODE -615
SQLCODE -616
SQLCODE -624
SQLCODE -667
SQLSTATE 23520
SQLCODE -675
SQLSTATE 42892
SQLCODE -679
SQLSTATE 57006
SQLSTATE 42893
SQL0667
SQLSTATE 55006
SQLSTATE 54008
SQLSTATE 57005
SQLSTATE 54008
SQLCODE -666
SQL0683
SQLCODE -683
SQLSTATE 42842
SQLSTATE 42889
SQL0724
SQLCODE -724
SQLSTATE 54038
SQLCODE -628
SQLSTATE 42613
SQLCODE -629
SQLSTATE 42834
SQL0751
SQLCODE -751
SQLSTATE 42987
SQLCODE -752
SQLSTATE 0A001
443
SQL0773
SQLCODE -773
SQLSTATE 20000
SQL0784
SQLCODE -784
SQLSTATE 42860
SQL0774
SQL0785
SQLCODE -774
SQLSTATE 2D522
SQLCODE -785
SQLSTATE 428D8
SQL0775
SQL0802
SQLCODE -775
SQLSTATE 42910
SQLCODE -802
SQLSTATE 22003,
22012, 22023, 22504
SQL0776
SQL0803
SQLCODE -776
SQLSTATE 428D4
SQLSTATE 42919
SQLCODE -778
SQLSTATE 428D5
SQLCODE -779
SQLSTATE 42736
SQLCODE -780
SQLSTATE 428D6
SQLSTATE 23505
SQL0777
SQLCODE -803
SQLCODE -804
SQLSTATE 07002
SQLCODE -805
SQLSTATE 51002
SQLCODE -811
SQLSTATE 21000
SQLCODE -818
SQLSTATE 51003
SQLCODE -822
SQLSTATE 51004
SQLCODE -781
SQLSTATE 42737
SQLCODE -782
SQLCODE -783
SQLSTATE 42738
444
SQLCODE -827
SQLSTATE 42862
SQLSTATE 428D7
SQL0827
SQL0840
SQLCODE -840
SQLSTATE 54004
SQLCODE -842
SQLSTATE 08002
SQL0843
SQLCODE -843
SQLSTATE 08003
SQL0918
SQLCODE -918
SQL0858
SQL0950
SQLCODE -858
SQLSTATE 08501
SQLCODE -950
SQLSTATE 51021
SQLSTATE 42705
SQL0862
SQL0951
SQLCODE -862
SQLSTATE 55029
SQLSTATE 54019
SQLSTATE 55007
SQL0871
SQLCODE -951
SQLCODE -952
SQLSTATE 57014
SQL0900
SQL0969
SQLCODE -900
SQLSTATE 08003
SQLSTATE 58004
SQLCODE -904
SQLSTATE 57011
SQLSTATE 58033
SQL0901
SQLCODE -969
SQLCODE -971
SQLSTATE 57011
SQLCODE -5001
SQLSTATE 42703
SQL0906
SQL5002
SQLCODE -906
SQLSTATE 24514
SQLSTATE 27000
SQLSTATE 42812
SQL0907
SQLCODE -5002
SQLCODE -5003
SQLSTATE 42922
SQL0910
SQL5005
SQLCODE -910
SQLSTATE 57007
SQLCODE -5005
SQLSTATE 42815
SQL0913
SQL5012
SQLCODE -913
SQLSTATE 57033
SQLCODE -917
SQLCODE -5012
SQLSTATE 42618
SQLSTATE 42969
445
SQL5016
SQLCODE -5016
SQLSTATE 42833
SQL7010
SQLCODE -7010
SQLSTATE 42850
SQL5021
SQL7011
SQLCODE -5021
SQLSTATE 42930
SQLSTATE 26510
SQLSTATE 42618
SQLCODE -7017
SQLSTATE 42971
SQL5024
SQLSTATE 42851
SQL5023
SQLCODE -7011
SQLCODE -7018
SQLSTATE 42970
SQL5047
SQL7021
SQLCODE -5047
SQLSTATE 42616
SQLCODE -7021
SQLSTATE 57043
SQL5051
SQL7022
SQLCODE -5051
SQLSTATE 42875
SQLCODE -7001
SQLCODE -7002
SQLSTATE 42858
SQLSTATE 42847
SQLCODE -7003
SQLSTATE 42857
SQLCODE -7006
SQLSTATE 55018
SQLCODE -7007
SQLSTATE 42977
SQLCODE -7022
SQLSTATE 51009
SQL7024
SQLCODE -7024
SQLSTATE 42876
SQLCODE -7026
SQLSTATE 42896
SQLCODE -7027
SQLSTATE 42984
SQLCODE -7028
SQLSTATE 42944
SQLCODE -7008
SQLSTATE 55019
446
SQLCODE -7029
SQLSTATE 428B8
SQL7031
SQLCODE -7031
SQLSTATE 54044
SQLCODE -7032
SQL7033
SQLCODE -7033
SQLSTATE 42923
SQLCODE -7941
SQLSTATE 42981
SQLCODE -9012
SQLSTATE 42968
SQLCODE -30000
SQLSTATE 58008
SQLCODE -30001
SQLSTATE 57042
SQLCODE -30020
SQLSTATE 58009
SQLCODE -30021
SQLSTATE 58010
SQLCODE -30040
SQLSTATE 57012
SQLCODE -30041
SQLCODE -30050
SQLSTATE 58011
SQLSTATE 42904
SQ30050
SQLSTATE 57013
SQ30051
SQLCODE -30051
SQLSTATE 58012
SQLCODE -30052
SQLSTATE 42932
SQLCODE -30053
SQLSTATE 42506
SQLCODE -30060
SQLSTATE 08004
SQLCODE -30061
SQLSTATE 08004
SQLCODE -30070
SQLSTATE 58014
SQLCODE -30071
SQLSTATE 58015
SQLCODE -30072
SQLSTATE 58016
SQLCODE -30073
SQLSTATE 58017
SQLCODE -30074
SQLSTATE 58018
447
SQ30080
SQLCODE -30080
SQLSTATE 08001
SQLCODE -30089
SQLSTATE 08001
448
SQ30090
SQLCODE -30090
2D528, 2D529
SQLSTATE 25000,
This host language statement retrieves the external definitions for the SQL
table PROJECT. These definitions can be used as host variables or as a host
structure.
Notes:
1. In RPG for AS/400, field names in an externally described structure
that are longer than 6 characters must be renamed.
2. REXX does not support the retrieval of external definitions.
The SQL INCLUDE SQLCA statement is used to include the SQLCA for
PL/I, C, and COBOL programs. For RPG programs, the SQL precompiler
automatically places the SQLCA data structure into the source at the end
of the Input specification section. For REXX, the SQLCA fields are
maintained in separate variables rather than in a contiguous data area
mapped by the SQLCA.
This SQL WHENEVER statement defines the host language label to which
control is passed if an SQLERROR (SQLCODE < 0) occurs in an SQL
statement. This WHENEVER SQLERROR statement applies to all the
following SQL statements until the next WHENEVER SQLERROR
statement is encountered. REXX does not support the WHENEVER
statement. Instead, REXX uses the SIGNAL ON ERROR facility.
This SQL UPDATE statement updates the SALARY column, which contains
the employee salary by the percentage in the host variable PERCENTAGE
(PERCNT for RPG). The updated rows are those that have employee
commissions greater than 2000. For REXX, this is PREPARE and EXECUTE
since UPDATE cannot be executed directly if there is a host variable.
This SQL COMMIT statement commits the changes made by the SQL
UPDATE statement. Record locks on all changed rows are released.
Note: The program was precompiled using COMMIT(*CHG). (For REXX,
*CHG. is the default.)
This SQL DECLARE CURSOR statement defines cursor C1, which joins
two tables, EMPLOYEE and EMP_ACT, and returns rows for employees
who received a raise (commission > 2000). Rows are returned in ascending
449
This SQL OPEN statement opens cursor C1 so that the rows can be
fetched.
This SQL WHENEVER statement defines the host language label to which
control is passed when all rows are fetched (SQLCODE = 100). For REXX,
the SQLCODE must be explicitly checked.
This SQL FETCH statement returns all columns for cursor C1 and places
the returned values into the corresponding elements of the host structure.
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, EMP_ACT, 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
(EMP_ACT.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
14
This SQL ROLLBACK statement restores the table to its original condition
if an error occurred during the update.
|
|
|
|
450
CEX
04/01/98 15:52:26
Page
451
5769ST1
Record
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
V4R3M0 980729
Create SQL ILE C Object
CEX
*...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
#include "string.h"
#include "stdlib.h"
#include "stdio.h"
main()
{
/* A sample program which updates the salaries for those employees */
/* whose current commission total is greater than or equal to the
*/
/* value of 'commission'. The salaries of those who qualify are
*/
/* increased by the value of 'percentage' retroactive to 'raise_date'*/
/* A report is generated showing the projects which these employees */
/* have contributed to ordered by project number and employee ID.
*/
/* A second report shows each project having an end date occurring */
/* after 'raise_date' (is potentially affected by the retroactive
*/
/* raises) with its total salary expenses and a count of employees */
/* who contributed to the project.
*/
short work_days = 253;
/* work days during in one year
float commission = 2000.00;
/* cutoff to qualify for raise
float percentage = 1.04;
/* raised salary as percentage
char raise_date??(12??) = "1982-06-01"; /* effective raise date
/* File declaration for qprint */
FILE *qprint;
/* Structure for report 1 */
1 #pragma mapinc ("project","CORPDATA/PROJECT(PROJECT)","both","p z")
#include "project"
struct {
CORPDATA_PROJECT_PROJECT_both_t Proj_struct;
char empno??(7??);
char name??(30??);
float salary;
} rpt1;
/* Structure for report 2 */
struct {
char projno??(7??);
char project_name??(37??);
short employee_count;
double total_proj_cost;
} rpt2;
2 exec sql include SQLCA;
qprint=fopen("QPRINT","w");
/* Update the selected projects by the new percentage. If an error */
/* occurs during the update, ROLLBACK the changes.
*/
3 EXEC SQL WHENEVER SQLERROR GO TO update_error;
4 EXEC SQL
UPDATE CORPDATA/EMPLOYEE
SET SALARY = SALARY * :percentage
WHERE COMM >= :commission ;
/* Commit changes */
5 EXEC SQL
COMMIT;
EXEC SQL WHENEVER SQLERROR GO TO report_error;
/* Report the updated statistics for each employee assigned to the */
/* selected projects.
*/
/* Write out the header for Report 1 */
fprintf(qprint,"
REPORT OF PROJECTS AFFECTED \
452
*/
*/
*/
*/
04/01/98 15:52:26
SEQNBR Last change
100
200
300
400
500
600
700
800
900
1000
1100
1200
1300
1400
1500
1600
1700
1800
1900
2000
2100
2200
2300
2400
2500
2600
2700
2800
2900
3000
3100
3200
3300
3400
3500
3600
3700
3800
3900
4000
4100
4200
4300
4400
4500
4600
4700
4800
4900
5000
5100
5200
5300
5400
5500
5600
5700
5800
5900
6000
6100
6200
6300
6400
6500
Page
5769ST1
Record
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
V4R3M0 980729
Create SQL ILE C Object
CEX
*...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
BY RAISES");
fprintf(qprint,"\n\nPROJECT EMPID
EMPLOYEE NAME
");
fprintf(qprint, "
SALARY\n");
6 exec sql
declare c1 cursor for
select distinct projno, emp_act.empno,
lastname||', '||firstnme, salary
from corpdata/emp_act, corpdata/employee
where emp_act.empno = employee.empno and comm >= :commission
order by projno, empno;
7 EXEC SQL
OPEN C1;
/* Fetch and write the rows to QPRINT */
8 EXEC SQL WHENEVER NOT FOUND GO TO done1;
do {
10 EXEC SQL
FETCH C1 INTO :Proj_struct.PROJNO, :rpt1.empno,
:rpt1.name,:rpt1.salary;
fprintf(qprint,"\n%6s
%6s
%-30s
%8.2f",
rpt1.Proj_struct.PROJNO,rpt1.empno,
rpt1.name,rpt1.salary);
}
while (SQLCODE==0);
done1:
EXEC SQL
CLOSE C1;
/*
/*
/*
/*
/*
* /
*/
*/
*/
*/
04/01/98 15:52:26
SEQNBR Last change
6600
6700
6800
6900
7000
7100
7200
7300
7400
7500
7600
7700
7800
7900
8000
8100
8200
8300
8400
8500
8600
8700
8800
8900
9000
9100
9200
9300
9400
9500
9600
9700
9800
9900
10000
10100
10200
10300
10400
10500
10600
10700
10800
10900
11000
11100
11200
11300
11400
11500
11600
11700
11800
11900
12000
12100
12200
12300
12400
12500
12600
12700
12800
12900
13000
Page
453
5769ST1
Record
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
* * * *
V4R3M0 980729
Create SQL ILE C Object
CEX
*...+... 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
fprintf(qprint,"\n%6s
%-36s %6d
%9.2f",
rpt2.projno,rpt2.project_name,rpt2.employee_count,
rpt2.total_proj_cost);
}
while (SQLCODE==0);
done2:
EXEC SQL
CLOSE C2;
goto finished;
/* Error occured while updating table. Inform user and rollback */
/* changes.
*/
update_error:
13 EXEC SQL WHENEVER SQLERROR CONTINUE;
fprintf(qprint,"*** ERROR Occurred while updating table. SQLCODE="
"%5d\n",SQLCODE);
14 EXEC SQL
ROLLBACK;
goto finished;
/* Error occured while generating reports. Inform user and exit.
report_error:
fprintf(qprint,"*** ERROR Occurred while generating reports. "
"SQLCODE=%5d\n",SQLCODE);
goto finished;
/* All done */
finished:
fclose(qprint);
exit(0);
}
*
E N D
O F
S O U R C E
* * * * *
454
*/
04/01/98 15:52:26
SEQNBR Last change
13100
13200
13300
13400
13500
13600
13700
13800
13900
14000
14100
14200
14300
14400
14500
14600
14700
14800
14900
15000
15100
15200
15300
15400
15500
15600
15700
15800
15900
16000
16100
16200
16300
Page
done1
****
done2
****
employee_count
empno
40
31
name
32
percentage
20
project_name
projno
raise_date
39
38
21
report_error
****
rpt1
rpt2
34
42
salary
33
total_proj_cost
update_error
41
****
work_days
18
ACTNO
BIRTHDATE
BONUS
COMM
74
74
74
****
COMM
CORPDATA
74
****
C1
71
C2
112
DEPTNO
DEPTNO
EDLEVEL
EMENDATE
EMENDATE
27
116
74
74
****
EMP_ACT
****
EMP_ACT
****
CEX
04/01/98 15:52:26
Page
Reference
FLOAT(24)
54 75
LABEL
81
LABEL
126
SMALL INTEGER PRECISION(4,0) IN rpt2
VARCHAR(7) IN rpt1
85
VARCHAR(30) IN rpt1
86
FLOAT(24)
53
VARCHAR(37) IN rpt2
VARCHAR(7) IN rpt2
VARCHAR(12)
119
LABEL
59
STRUCTURE
130
FLOAT(24) IN rpt1
86
FLOAT(53) IN rpt2
LABEL
50
SMALL INTEGER PRECISION(4,0)
115
SMALL INTEGER PRECISION(4,0) COLUMN (NOT NULL) IN CORPDATA.EMP_ACT
DATE(10) COLUMN IN CORPDATA.EMPLOYEE
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
COLUMN
54 75
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
COLLECTION
52 74 74 116 116 116
CURSOR
78 85 95
CURSOR
123 130 139
VARCHAR(3) IN Proj_struct
CHARACTER(3) COLUMN (NOT NULL) IN CORPDATA.PROJECT
SMALL INTEGER PRECISION(4,0) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
DATE(10) COLUMN IN CORPDATA.EMP_ACT
COLUMN
114
TABLE
72 75 113 117 118 120
TABLE IN CORPDATA
74 116
455
****
EMPLOYEE
****
EMPNO
****
EMPNO
****
EMPNO
EMPNO
EMPTIME
EMPTIME
74
74
74
****
EMSTDATE
EMSTDATE
74
****
FIRSTNME
****
FIRSTNME
HIREDATE
JOB
LASTNAME
74
74
74
****
LASTNAME
MAJPROJ
MAJPROJ
MIDINIT
Proj_struct
PHONENO
PRENDATE
PRENDATE
74
27
116
74
30
74
27
****
PRENDATE
PROJECT
116
****
PROJECT
****
PROJNAME
PROJNAME
27
****
PROJNAME
PROJNO
116
27
PROJNO
****
PROJNO
PROJNO
74
****
CEX
04/01/98 15:52:26
Page
04/01/98 15:52:26
Page
TABLE IN CORPDATA
52 74 116
TABLE
75 118
COLUMN IN EMP_ACT
72 75 76 118
COLUMN IN EMPLOYEE
75 118
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMP_ACT
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
DECIMAL(5,2) COLUMN IN CORPDATA.EMP_ACT
COLUMN
114
DATE(10) COLUMN IN CORPDATA.EMP_ACT
COLUMN
114
COLUMN
73
VARCHAR(12) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
DATE(10) COLUMN IN CORPDATA.EMPLOYEE
CHARACTER(8) COLUMN IN CORPDATA.EMPLOYEE
COLUMN
73
VARCHAR(15) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
VARCHAR(6) IN Proj_struct
CHARACTER(6) COLUMN IN CORPDATA.PROJECT
CHARACTER(1) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
STRUCTURE IN rpt1
CHARACTER(4) COLUMN IN CORPDATA.EMPLOYEE
DATE(10) IN Proj_struct
COLUMN
119
DATE(10) COLUMN IN CORPDATA.PROJECT
TABLE IN CORPDATA
116
TABLE
117
VARCHAR(24) IN Proj_struct
COLUMN
113 120
VARCHAR(24) COLUMN (NOT NULL) IN CORPDATA.PROJECT
VARCHAR(6) IN Proj_struct
85
COLUMN
72 76
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMP_ACT
COLUMN IN EMP_ACT
PROJNO
****
PROJNO
PRSTAFF
PRSTAFF
PRSTDATE
PRSTDATE
RESPEMP
RESPEMP
SALARY
116
27
116
27
116
27
116
****
SALARY
SEX
WORKDEPT
No errors found in source
163 Source records processed
* * * * * E N D O F L I S T I
74
74
74
N G
CEX
456
CBLEX
04/01/98 11:09:13
Page
457
458
SEQNBR
04/01/98 11:09:13
Last change
Page
SEQNBR
04/01/98 11:09:13
Last change
Page
459
460
SEQNBR
04/01/98 11:09:13
Last change
Page
SEQNBR
04/01/98 11:09:13
Last change
Page
461
462
SEQNBR
04/01/98 11:09:13
Last change
Page
A200-DONE2
****
BIRTHDATE
BONUS
CODE-EDIT
COMM
134
134
69
****
COMM
COMMISSION
134
43
CORPDATA
****
C1
165
C2
209
DEPTNO
DEPTNO
EDLEVEL
EMENDATE
EMENDATE
50
213
134
168
****
EMP_ACT
****
EMP_ACT
****
EMPLOYEE
****
EMPLOYEE
****
EMPLOYEE-COUNT
EMPLOYEE-COUNT
EMPNO
63
114
51
EMPNO
EMPNO
EMPNO
103
134
****
EMPNO
****
EMPNO
EMPTIME
EMPTIME
168
168
****
EMSTDATE
168
CBLEX
04/01/98 11:09:13
Page
Reference
SMALL INTEGER PRECISION(4,0) COLUMN (NOT NULL) IN CORPDATA.EMP_ACT
LABEL
247
LABEL
267
DATE(10) COLUMN IN CORPDATA.EMPLOYEE
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
COLUMN
136 170
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
DECIMAL(7,2)
136 170
COLLECTION
134 168 168 213 213 214
CURSOR
174 182 250
CURSOR
222 230 270
CHARACTER(3) IN PROJECT
CHARACTER(3) COLUMN (NOT NULL) IN CORPDATA.PROJECT
SMALL INTEGER PRECISION(4,0) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
DATE(10) COLUMN IN CORPDATA.EMP_ACT
COLUMN
211
TABLE
166 169 210 215 216 218
TABLE IN CORPDATA
168 213
TABLE IN CORPDATA
134 168 214
TABLE
169 216
SMALL INTEGER PRECISION(4,0) IN RPT2
IN RPT2-DATA
CHARACTER(6) IN RPT1
250
CHARACTER(6) IN RPT1-DATA
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
COLUMN IN EMP_ACT
166 169 171 216
COLUMN IN EMPLOYEE
169 216
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMP_ACT
DECIMAL(5,2) COLUMN IN CORPDATA.EMP_ACT
COLUMN
212
DATE(10) COLUMN IN CORPDATA.EMP_ACT
463
****
E010-UPDATE-ERROR
****
E020-REPORT-ERROR
****
FIRSTNME
FIRSTNME
134
****
HIREDATE
JOB
LASTNAME
LASTNAME
134
134
134
****
MAJPROJ
MAJPROJ
MIDINIT
NAME
50
213
134
52
NAME
PERCENTAGE
105
42
PHONENO
PRENDATE
PRENDATE
134
50
****
PRENDATE
PRINT-RECORD
PROJECT
PROJECT
213
37
50
****
PROJECT
****
PROJECT-NAME
PROJECT-NAME
PROJNAME
PROJNAME
62
112
50
****
PROJNAME
PROJNO
213
50
PROJNO
PROJNO
PROJNO
PROJNO
61
101
110
****
CBLEX
COLUMN
211
LABEL
131
LABEL
148
VARCHAR(12) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
COLUMN
167
DATE(10) COLUMN IN CORPDATA.EMPLOYEE
CHARACTER(8) COLUMN IN CORPDATA.EMPLOYEE
VARCHAR(15) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
COLUMN
167
CHARACTER(6) IN PROJECT
CHARACTER(6) COLUMN IN CORPDATA.PROJECT
CHARACTER(1) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
CHARACTER(30) IN RPT1
251
CHARACTER(30) IN RPT1-DATA
DECIMAL(5,2)
135
CHARACTER(4) COLUMN IN CORPDATA.EMPLOYEE
DATE(10) IN PROJECT
COLUMN
217
DATE(10) COLUMN IN CORPDATA.PROJECT
CHARACTER(132)
STRUCTURE IN RPT1
TABLE IN CORPDATA
213
TABLE
215
CHARACTER(36) IN RPT2
CHARACTER(36) IN RPT2-DATA
VARCHAR(24) IN PROJECT
COLUMN
210 218
VARCHAR(24) COLUMN (NOT NULL) IN CORPDATA.PROJECT
CHARACTER(6) IN PROJECT
250
CHARACTER(6) IN RPT2
CHARACTER(6) IN RPT1-DATA
CHARACTER(6) IN RPT2-DATA
COLUMN
464
04/01/98 11:09:13
Page
PROJNO
PROJNO
168
****
PROJNO
****
PROJNO
PRSTAFF
PRSTAFF
PRSTDATE
PRSTDATE
RAISE-DATE
213
50
213
50
213
41
RESPEMP
RESPEMP
RPT1
RPT1-DATA
RPT1-HEADERS
RPT1-HEADER1
RPT1-HEADER2
RPT2
50
213
49
100
75
76
80
60
RPT2-DATA
RPT2-HEADERS
RPT2-HEADER1
RPT2-HEADER2
RPT2-HEADER3
SALARY
109
85
86
90
95
53
SALARY
SALARY
107
****
SALARY
SEX
TOTAL-PROJ-COST
TOTAL-PROJ-COST
WORK-DAYS
134
134
64
116
40
WORKDEPT
No errors found in source
307 Source records processed
134
* * * * *
CBLEX
04/01/98 11:09:13
Page
166 171
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMP_ACT
COLUMN IN EMP_ACT
210 215 218
COLUMN IN PROJECT
215
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.PROJECT
DECIMAL(5,2) IN PROJECT
DECIMAL(5,2) COLUMN IN CORPDATA.PROJECT
DATE(10) IN PROJECT
DATE(10) COLUMN IN CORPDATA.PROJECT
CHARACTER(11)
217
CHARACTER(6) IN PROJECT
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.PROJECT
IN RPT1-HEADERS
IN RPT1-HEADERS
STRUCTURE
270
IN RPT2-HEADERS
IN RPT2-HEADERS
IN RPT2-HEADERS
DECIMAL(8,2) IN RPT1
251
IN RPT1-DATA
COLUMN
135 135 167 212
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
CHARACTER(1) COLUMN IN CORPDATA.EMPLOYEE
DECIMAL(12,2) IN RPT2
IN RPT2-DATA
SMALL INTEGER PRECISION(4,0)
212
CHARACTER(3) COLUMN IN CORPDATA.EMPLOYEE
E N D
O F
L I S T I N G
* * * * *
465
PLIEX
466
04/01/98 12:53:36
Page
04/01/98 12:53:36
SEQNBR Last change
100
200
300
400
500
600
700
800
900
1000
1100
1200
1300
1400
1500
1600
1700
1800
1900
2000
2100
2200
2300
2400
2500
2600
2700
2800
2900
3000
3100
3200
3300
3400
3500
3600
3700
3800
3900
4000
4100
4200
4300
4400
4500
4600
4700
4800
4900
5000
5100
5200
5300
5400
5500
5600
5700
5800
5900
6000
6100
6200
6300
6400
6500
Page
467
468
04/01/98 12:53:36
SEQNBR Last change
6600
6700
6800
6900
7000
7100
7200
7300
7400
7500
7600
7700
7800
7900
8000
8100
8200
8300
8400
8500
8600
8700
8800
8900
9000
9100
9200
9300
9400
9500
9600
9700
9800
9900
10000
10100
10200
10300
10400
10500
10600
10700
10800
10900
11000
11100
11200
11300
11400
11500
11600
11700
11800
11900
12000
12100
12200
12300
12400
12500
12600
12700
12800
12900
13000
Page
04/01/98 12:53:36
SEQNBR Last change
13100
13200
13300
13400
13500
13600
13700
13800
13900
14000
14100
14200
14300
14400
14500
14600
14700
14800
14900
15000
15100
15200
15300
15400
15500
15600
15700
15800
15900
16000
16100
16200
16300
16400
16500
Page
469
CORPDATA
****
C1
71
C2
114
DEPTNO
DEPTNO
DONE1
26
118
****
DONE2
****
EDLEVEL
EMENDATE
EMENDATE
74
74
****
EMP_ACT
****
EMP_ACT
****
EMPLOYEE
****
EMPLOYEE
****
EMPLOYEE_COUNT
EMPNO
35
27
EMPNO
****
EMPNO
****
EMPNO
EMPNO
EMPTIME
EMPTIME
74
74
74
****
EMSTDATE
EMSTDATE
74
****
FIRSTNME
****
FIRSTNME
74
PLIEX
470
04/01/98 12:53:36
Reference
SMALL INTEGER PRECISION(4,0) COLUMN (NOT NULL) IN CORPDATA.EMP_ACT
DATE(10) COLUMN IN CORPDATA.EMPLOYEE
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
COLUMN
52 76
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
DECIMAL(8,2)
52 76
COLLECTION
50 74 74 118 118 118
CURSOR
79 86 95
CURSOR
125 132 141
CHARACTER(3) IN RPT1
CHARACTER(3) COLUMN (NOT NULL) IN CORPDATA.PROJECT
LABEL
82
LABEL
128
SMALL INTEGER PRECISION(4,0) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
DATE(10) COLUMN IN CORPDATA.EMP_ACT
COLUMN
116
TABLE
72 75 115 119 120 122
TABLE IN CORPDATA
74 118
TABLE IN CORPDATA
50 74 118
TABLE
75 120
SMALL INTEGER PRECISION(4,0) IN RPT2
CHARACTER(6) IN RPT1
86
COLUMN IN EMP_ACT
72 75 77 120
COLUMN IN EMPLOYEE
75 120
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMP_ACT
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
DECIMAL(5,2) COLUMN IN CORPDATA.EMP_ACT
COLUMN
116
DATE(10) COLUMN IN CORPDATA.EMP_ACT
COLUMN
116
COLUMN
73
VARCHAR(12) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
Page
74
74
****
LASTNAME
MAJPROJ
MAJPROJ
MIDINIT
NAME
74
26
118
74
28
PERCENTAGE
19
PHONENO
PRENDATE
PRENDATE
74
26
****
PRENDATE
PROJECT
118
****
PROJECT
****
PROJECT_NAME
PROJNAME
PROJNAME
34
26
****
PROJNAME
PROJNO
118
26
PROJNO
PROJNO
33
****
PROJNO
PROJNO
74
****
PROJNO
****
PROJNO
PRSTAFF
PRSTAFF
PRSTDATE
PRSTDATE
RAISE_DATE
118
26
118
26
118
16
REPORT_ERROR
****
PLIEX
04/01/98 12:53:36
Page
04/01/98 12:53:36
Page
26
118
25
32
SALARY
29
SALARY
****
SALARY
SEX
SYSPRINT
TOTL_PROJ_COST
UPDATE_ERROR
74
74
22
36
****
WORK_DAYS
17
WORKDEPT
No errors found in source
165 Source records processed
74
* * * * *
CHARACTER(6)
CHARACTER(6)
STRUCTURE
STRUCTURE
132
DECIMAL(8,2)
87
COLUMN
51 51 73 117
DECIMAL(9,2)
CHARACTER(1)
PLIEX
IN RPT1
COLUMN (NOT NULL) IN CORPDATA.PROJECT
IN RPT1
COLUMN IN CORPDATA.EMPLOYEE
COLUMN IN CORPDATA.EMPLOYEE
DECIMAL(10,2) IN RPT2
LABEL
48
SMALL INTEGER PRECISION(4,0)
117
CHARACTER(3) COLUMN IN CORPDATA.EMPLOYEE
E N D
O F
L I S T I N G
* * * * *
471
RPGEX
Figure 24. Sample RPG for AS/400 Program Using SQL Statements (Part 1 of 8)
472
04/01/98 12:55:22
Page
04/01/98 12:55:22
SEQNBR Last change
100
200
300
400
500
600
700
800
900
1000
1100
1200
1300
1400
1500
1600
1700
1800
1900
2000
2100
2200
2300
2400
2500
2600
2700
2800
2900
3000
3100
3200
3300
3400
3500
3600
3700
3800
3900
3901 02/03/93
4000
4100
4200
4300
4400
4500
4600
4700
4800
4900
5000
5100
5200
5300
5400
5500
5600
5700
5800
5900
6000
6100
6200
6300
6400
Page
Figure 24. Sample RPG for AS/400 Program Using SQL Statements (Part 2 of 8)
473
Figure 24. Sample RPG for AS/400 Program Using SQL Statements (Part 3 of 8)
474
04/01/98 12:55:22
SEQNBR Last change
6500
6600
6700 02/03/93
6800 02/03/93
6900 02/03/93
7000 02/03/93
7100 02/03/93
7200 02/03/93
7300 02/03/93
7400
7500
7600
7700
7800
7900
8000
8100
8200
8300
8400
8500
8600
8700
8800
8900
9000
9100
9200
9300
9400
9500
9600
9700
9800
9900
10000
10100
10200
10300
10400
10500
10600
10700
10800
10900
11000
11100
11200
11300
11400
11500
11600
11700
11800
11900
12000
12100
12200
12300
12400
12500
12600
12700
12800
12900
Page
04/01/98 12:55:22
SEQNBR Last change
13000
13100
13200
13300 02/03/93
13400
13500
13600
13700
13800
13900
14000
14100
14200
14300
14400
14500
14600 02/03/93
14700
14800
14900
15000
15100
15200
15300
15400
15500
15700
15800
15900
16000
16100
16200
16300
16400
16500
16600
16700
16800
16900
17000
17100
17200
17300
17400
17500
17600
17700
17800
17900
18000
18100
18200
19500
18300
18400
18500
18600
18700
18800
18900
19000
19100
19200
19300
19400
Page
04/01/98 12:55:22
SEQNBR Last change
19600
Page
Figure 24. Sample RPG for AS/400 Program Using SQL Statements (Part 4 of 8)
Program
RPGEX
...+... 5 ...+... 6 ...+... 7 ...+... 8
67
O F S O U R C E * * * * *
Figure 24. Sample RPG for AS/400 Program Using SQL Statements (Part 5 of 8)
475
CORPDATA
****
C1
68
C2
105
DEPTNO
DEPTNO
DONE1
8
105
91
DONE2
131
EDLEVEL
EMENDATE
EMENDATE
48
68
****
EMP_ACT
****
EMP_ACT
****
EMPCNT
EMPLOYEE
26
****
EMPLOYEE
****
EMPNO
17
EMPNO
EMPNO
48
****
EMPNO
****
EMPNO
EMPTIME
EMPTIME
68
68
****
EMSTDATE
EMSTDATE
68
****
FINISH
FIRSTNME
156
48
RPGEX
Figure 24. Sample RPG for AS/400 Program Using SQL Statements (Part 6 of 8)
476
04/01/98 12:55:22
Reference
SMALL INTEGER PRECISION(4,0) COLUMN (NOT NULL) IN CORPDATA.EMP_ACT
DATE(10) COLUMN IN CORPDATA.EMPLOYEE
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
COLUMN
48 68
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
DECIMAL(7,2)
48 68
COLLECTION
48 68 68 105 105 105
CURSOR
77 86 92
CURSOR
118 126 132
CHARACTER(3) IN RPT1
CHARACTER(3) COLUMN (NOT NULL) IN CORPDATA.PROJECT
LABEL
83
LABEL
123
SMALL INTEGER PRECISION(4,0) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
DATE(10) COLUMN IN CORPDATA.EMP_ACT
COLUMN
105
TABLE
68 68 105 105 105 105
TABLE IN CORPDATA
68 105
SMALL INTEGER PRECISION(4,0) IN RPT2
TABLE IN CORPDATA
48 68 105
TABLE
68 105
CHARACTER(6)
86
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
COLUMN IN EMP_ACT
68 68 68 105
COLUMN IN EMPLOYEE
68 105
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMP_ACT
DECIMAL(5,2) COLUMN IN CORPDATA.EMP_ACT
COLUMN
105
DATE(10) COLUMN IN CORPDATA.EMP_ACT
COLUMN
105
LABEL
VARCHAR(12) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
Page
****
HIREDATE
JOB
LASTNAME
LASTNAME
48
48
48
****
MAJPRJ
MAJPROJ
MIDINIT
NAME
8
105
48
18
PERCNT
33
PHONENO
PNAME
PRCOST
PREND
PRENDATE
48
25
27
8
****
PRENDATE
PRJNUM
PROJECT
105
24
****
PROJECT
****
PROJNAME
****
PROJNAME
PROJNM
PROJNO
105
8
8
PROJNO
****
PROJNO
PROJNO
68
****
PROJNO
****
PROJNO
PRSTAFF
PRSTD
PRSTDATE
RDATE
105
105
8
105
32
RPGEX
04/01/98 12:55:22
Page
04/01/98 12:55:22
Page
COLUMN
68
DATE(10) COLUMN IN CORPDATA.EMPLOYEE
CHARACTER(8) COLUMN IN CORPDATA.EMPLOYEE
VARCHAR(15) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
COLUMN
68
CHARACTER(6) IN RPT1
CHARACTER(6) COLUMN IN CORPDATA.PROJECT
CHARACTER(1) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
CHARACTER(30)
86
DECIMAL(7,2)
48
CHARACTER(4) COLUMN IN CORPDATA.EMPLOYEE
CHARACTER(36) IN RPT2
DECIMAL(9,2) IN RPT2
DATE(10) IN RPT1
COLUMN
105
DATE(10) COLUMN IN CORPDATA.PROJECT
CHARACTER(6) IN RPT2
TABLE IN CORPDATA
105
TABLE
105
COLUMN
105 105
VARCHAR(24) COLUMN (NOT NULL) IN CORPDATA.PROJECT
VARCHAR(24) IN RPT1
CHARACTER(6) IN RPT1
86
COLUMN
68 68
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMP_ACT
COLUMN IN EMP_ACT
105 105 105
COLUMN IN PROJECT
105
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.PROJECT
DECIMAL(5,2) COLUMN IN CORPDATA.PROJECT
DATE(10) IN RPT1
DATE(10) COLUMN IN CORPDATA.PROJECT
CHARACTER(10)
105
Figure 24. Sample RPG for AS/400 Program Using SQL Statements (Part 7 of 8)
8
105
151
RPT1
RPT2
8
23
SALARY
19
SALARY
****
SALARY
SEX
STAFF
UPDERR
48
48
8
139
WORKDEPT
WRKDAY
48
30
* * * * *
RPGEX
CHARACTER(6) IN RPT1
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.PROJECT
LABEL
59
STRUCTURE
STRUCTURE
126
DECIMAL(9,2)
86
COLUMN
48 48 68 105
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
CHARACTER(1) COLUMN IN CORPDATA.EMPLOYEE
DECIMAL(5,2) IN RPT1
LABEL
45
CHARACTER(3) COLUMN IN CORPDATA.EMPLOYEE
SMALL INTEGER PRECISION(4,0)
105
E N D
O F
L I S T I N G
* * * * *
Figure 24. Sample RPG for AS/400 Program Using SQL Statements (Part 8 of 8)
477
RPGLEEX
Figure 25. Sample ILE RPG for AS/400 Program Using SQL Statements (Part 1 of 7)
478
04/01/98 16:03:02
Page
Figure 25. Sample ILE RPG for AS/400 Program Using SQL Statements (Part 2 of 7)
479
Figure 25. Sample ILE RPG for AS/400 Program Using SQL Statements (Part 3 of 7)
480
Figure 25. Sample ILE RPG for AS/400 Program Using SQL Statements (Part 4 of 7)
481
CORPDATA
****
C1
62
C2
99
DEPTNO
DEPTNO
DONE1
DONE1
8
99
85
****
DONE2
DONE2
125
****
EDLEVEL
EMENDATE
EMENDATE
42
62
****
EMP_ACT
****
EMP_ACT
****
EMPCNT
EMPLOYEE
20
****
EMPLOYEE
****
EMPNO
11
EMPNO
EMPNO
42
****
EMPNO
****
EMPNO
EMPTIME
EMPTIME
62
62
****
EMSTDATE
EMSTDATE
62
****
FINISH
150
RPGLEEX
LABEL
77
LABEL
117
SMALL INTEGER PRECISION(4,0) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
DATE(10) COLUMN IN CORPDATA.EMP_ACT
COLUMN
99
TABLE
62 62 99 99 99 99
TABLE IN CORPDATA
62 99
SMALL INTEGER PRECISION(4,0) IN RPT2
TABLE IN CORPDATA
42 62 99
TABLE
62 99
CHARACTER(6) DBCS-open
80
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE
COLUMN IN EMP_ACT
62 62 62 99
COLUMN IN EMPLOYEE
62 99
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMP_ACT
DECIMAL(5,2) COLUMN IN CORPDATA.EMP_ACT
COLUMN
99
DATE(10) COLUMN IN CORPDATA.EMP_ACT
COLUMN
99
Figure 25. Sample ILE RPG for AS/400 Program Using SQL Statements (Part 5 of 7)
482
04/01/98 16:03:02
Reference
SMALL INTEGER PRECISION(4,0) COLUMN (NOT NULL) IN CORPDATA.EMP_ACT
DATE(10) COLUMN IN CORPDATA.EMPLOYEE
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
COLUMN
42 62
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
DECIMAL(7,2)
42 62
COLLECTION
42 62 62 99 99 99
CURSOR
71 80 86
CURSOR
112 120 126
CHARACTER(3) IN RPT1
CHARACTER(3) COLUMN (NOT NULL) IN CORPDATA.PROJECT
Page
42
****
HIREDATE
JOB
LASTNAME
LASTNAME
42
42
42
****
MAJPROJ
MAJPROJ
MIDINIT
NAME
8
99
42
12
PERCNT
27
PHONENO
PNAME
PRCOST
PRENDATE
PRENDATE
42
19
21
8
****
PRENDATE
PRJNUM
PROJECT
99
18
****
PROJECT
****
PROJNAME
PROJNAME
8
****
PROJNAME
PROJNO
99
8
PROJNO
****
PROJNO
PROJNO
62
****
PROJNO
****
PROJNO
PRSTAFF
PRSTAFF
PRSTDATE
PRSTDATE
99
8
99
8
99
RPGLEEX
04/01/98 16:03:02
Page
04/01/98 16:03:02
Page
Figure 25. Sample ILE RPG for AS/400 Program Using SQL Statements (Part 6 of 7)
26
RESPEMP
RESPEMP
RPTERR
RPTERR
8
99
145
****
RPT1
RPT2
8
17
SALARY
13
SALARY
****
SALARY
SEX
UPDERR
UPDERR
42
42
133
****
WORKDEPT
WRKDAY
42
24
RPGLEEX
CHARACTER(10) DBCS-open
99
CHARACTER(6) IN RPT1
CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.PROJECT
LABEL
53
STRUCTURE
STRUCTURE
120
DECIMAL(9,2)
80
COLUMN
42 42 62 99
DECIMAL(9,2) COLUMN IN CORPDATA.EMPLOYEE
CHARACTER(1) COLUMN IN CORPDATA.EMPLOYEE
LABEL
39
CHARACTER(3) COLUMN IN CORPDATA.EMPLOYEE
SMALL INTEGER PRECISION(4,0)
99
E N D
O F
L I S T I N G
* * * * *
Figure 25. Sample ILE RPG for AS/400 Program Using SQL Statements (Part 7 of 7)
483
484
Record
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
for Report 1 */
SALARY'
------'
EXECSQL,
'PREPARE S2 FROM :SELECT_STMT'
6EXECSQL,
'DECLARE C1 CURSOR FOR S2'
7EXECSQL,
'OPEN C1 USING :COMMISSION'
',
',
',
',
',
'
*/
*/
/* Stop the loop when we hit the EOF. Don't try to print out the */
/* fetched values.
*/
8IF SQLCODE = 100 THEN
LEAVE
/* Print out the fetched row */
SAY RPT1.PROJNO '
' RPT1.EMPNO '
END;
' RPT1.SALARY
10EXECSQL,
'CLOSE C1'
/*
/*
/*
/*
/*
NUMBER OF
EMPLOYEES
---------
*/
*/
*/
*/
*/
TOTAL'
COST'
-----'
485
Record
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
190
191
192
193
194
195
*/
*/
/* Stop the loop when we hit the EOF. Don't try to print out the */
/* fetched values.
*/
IF SQLCODE = 100 THEN
LEAVE
/* Print out the fetched row */
SAY RPT2.PROJNO '
' RPT2.PROJNAME ' ' ,
RPT2.EMPCOUNT '
' RPT2.TOTAL_COST
END;
EXECSQL,
'CLOSE C2'
/* Delete the OVRDBF so that we will continue writing to the output
/* display.
ADDRESS '*COMMAND',
'DLTOVR FILE(STDOUT)'
*/
*/
486
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
*/
*/
* * * * *
EMPID
EMPLOYEE NAME
AD3100
AD3110
AD3111
AD3113
IF1000
IF1000
IF2000
IF2000
MA2100
MA2100
MA2110
MA2111
MA2111
MA2112
OP1000
OP1010
OP1010
OP2010
OP2010
OP2012
PL2100
000010
000070
000240
000270
000030
000140
000030
000140
000010
000110
000010
000200
000220
000150
000050
000090
000280
000050
000100
000330
000020
HAAS, CHRISTINE
PULASKI, EVA
MARINO, SALVATORE
PEREZ, MARIA
KWAN, SALLY
NICHOLLS, HEATHER
KWAN, SALLY
NICHOLLS, HEATHER
HAAS, CHRISTINE
LUCCHESSI, VICENZO
HAAS, CHRISTINE
BROWN, DAVID
LUTZ, JENNIFER
ADAMSON, BRUCE
GEYER, JOHN
HENDERSON, EILEEN
SCHNEIDER, ETHEL
GEYER, JOHN
SPENSER, THEODORE
LEE, WING
THOMPSON, MICHAEL
SALARY
54860.00
37616.80
29910.40
28475.20
39780.00
29556.80
39780.00
29556.80
54860.00
48360.00
54860.00
28849.60
31033.60
26291.20
41782.00
30940.00
27300.00
41782.00
27196.00
26384.80
42900.00
PROJECT NAME
AD3100
AD3110
AD3111
AD3112
AD3113
IF1000
IF2000
MA2100
MA2110
MA2111
MA2112
MA2113
OP1000
ADMIN SERVICES
GENERAL ADMIN SYSTEMS
PAYROLL PROGRAMMING
PERSONNEL PROGRAMMING
ACCOUNT PROGRAMMING
QUERY SERVICES
USER EDUCATION
WELD LINE AUTOMATION
W L PROGRAMMING
W L PROGRAM DESIGN
W L ROBOT DESIGN
W L PROD CONT PROGS
OPERATION SUPPORT
NUMBER OF
EMPLOYEES
TOTAL
COST
1
1
8
9
14
4
5
2
1
3
6
5
1
19623.11
58877.28
72806.74
28845.70
72114.52
52205.66
55212.61
114001.52
85864.68
93729.24
166945.84
71509.11
16348.86
487
OP1010
OP2010
OP2011
OP2012
OP2013
PL2100
488
OPERATION
SYSTEMS SUPPORT
SCP SYSTEMS SUPPORT
APPLICATIONS SUPPORT
DB/DC SUPPORT
WELD LINE PLANNING
5
2
2
2
2
1
167828.76
91612.62
31224.60
41294.88
37311.12
43576.92
Pgm: B,I
REXX: B,I
Exec
*CURLIB/
CRTSQLCBL
PGM(
program-name )
library-name/
*LIBL/
QLBLSRC
source-file-name
SRCFILE(
*CURLIB/
library-name/
(1)
SRCMBR(
*PGM
source-file-member-name
OPTION(
OPTION Details
*CURRENT
*PRV
VxRxMx
TGTRLS(
*LIBL/
*SRCFILE
source-file-name
INCFILE(
*CURLIB/
library-name/
COMMIT(
*UR
*CHG
*ALL
*RS
*CS
*NONE
*NC
*RR
CLOSQLCSR(
)
*ENDPGM
*ENDSQL
*ENDJOB
ALWCPYDTA(
*YES
*OPTIMIZE
*NO
ALWBLK(
*READ
*NONE
*ALLREAD
489
CRTSQLCBL
*NO
*YES
DLYPRP(
10
severity-level
GENLVL(
*JOB
*USA
*ISO
*EUR
*JIS
*MDY
*DMY
*YMD
*JUL
DATFMT(
*JOB
'/'
'.'
','
'-'
' '
*BLANK
DATSEP(
*HMS
*USA
*ISO
*EUR
*JIS
TIMFMT(
*JOB
':'
'.'
','
' '
*BLANK
TIMSEP(
*YES
*NO
REPLACE(
RDB(
*LOCAL
relational-database-name
*NONE
*CURRENT
user-name
USER(
*NONE
password
PASSWORD(
RDBCNNMTH(
*DUW
*RUW
*NONE
collection-name
DFTRDBCOL(
*PGMLIB/
*PGM
package-name
SQLPKG(
library-name/
SAAFLAG(
*NOFLAG
*FLAG
FLAGSTD(
*NONE
*ANS
*LIBL/
PRTFILE(
*CURLIB/
library-name/
490
QSYSPRT
printer-file-name
CRTSQLCBL
*JOB
*JOBRUN
*LANGIDUNQ
*LANGIDSHR
*HEX
*LIBL/
SRTSEQ(
table-name
*CURLIB/
library-name/
*JOB
*JOBRUN
language-ID
LANGID(
USRPRF(
*NAMING
*OWNER
*USER
DYNUSRPRF(
*USER
*OWNER
QTEMP/
QSQLTEMP
source-file-name
TOSRCFILE(
*LIBL/
*CURLIB/
library-name/
TEXT(
*SRCMBRTXT
*BLANK
'description'
OPTION Details
*NOSRC
*NOSOURCE
*NOXREF
*GEN
*JOB
*QUOTESQL
*XREF
*NOGEN
*PERIOD
*SYSVAL
*COMMA
*APOSTSQL
*SOURCE
*SRC
*QUOTE
*SYS
*NOSECLVL
*NOLSTDBG
*APOST
*SQL
*SECLVL
*LSTDBG
Notes:
1. All parameters preceding this point can be specified in positional form.
Purpose
The Create Structured Query Language COBOL (CRTSQLCBL) command calls the
Structured Query Language (SQL) precompiler, which precompiles COBOL source
containing SQL statements, produces a temporary source member, and then
optionally calls the COBOL compiler to compile the program.
491
CRTSQLCBL
Parameters
PGM
Specifies the qualified name of the compiled program.
The name of the compiled COBOL program can be qualified by one of the
following library values:
*CURLIB The compiled COBOL program is created in the current library
for the job. If no library is specified as the current library for the job, the
QGPL library is used.
library name: Specify the name of the library where the compiled COBOL
program is created.
program-name: Specify the name of the compiled COBOL program.
SRCFILE
Specifies the qualified name of the source file that contains the COBOL source
with SQL statements.
The name of the source file can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
QLBLSRC: If a COBOL source file name is not specified, the IBM-supplied
source file QLBLSRC contains the COBOL source.
source-file-name: Specify the name of the source file that contains the COBOL
source. This source file should have a record length of 92 bytes. The source file
can be a database file, device file, or an inline data file.
SRCMBR
Specifies the name of the source file member that contains the COBOL source.
This parameter is specified only if the source file name in the SRCFILE
parameter is a database file. If this parameter is not specified, the PGM name
specified on the PGM parameter is used.
*PGM: Specifies that the COBOL source is in the member of the source file that
has the same name as that specified on the PGM parameter.
source-file-member-name: Specify the name of the member that contains the
COBOL source.
OPTION
Specifies whether one or more of the following options are used when the
COBOL source is precompiled. If an option is specified more than once, or if
two options conflict, the last option specified is used.
Element 1: Source Listing Options
*NOSOURCE or *NOSRC: A source printout is not produced by the
precompiler unless errors are detected during precompile or create package.
492
CRTSQLCBL
*SOURCE or *SRC: The precompiler produces a source printout consisting of
COBOL source input.
Element 2: Cross-Reference Options
*NOXREF: The precompiler does not cross-reference names.
*XREF: The precompiler cross-references items in the program to the statement
numbers in the program that refer to those items.
Element 3: Program Creation Options
*GEN: The compiler creates a program that can run after the program is
compiled. An SQL package object is created if a relational database name is
specified on the RDB parameter.
*NOGEN: The precompiler does not call the COBOL compiler, and a program
and SQL package are not created.
Element 4: Decimal Point Options
*JOB: The value used as the decimal point for numeric constants in SQL is the
representation of decimal point specified for the job at precompile time.
*SYSVAL: The value used as the decimal point for numeric constants in SQL
statements is the QDECFMT system value.
Note: If QDECFMT specifies that the value used as the decimal point is a
comma, any numeric constants in lists (such as in the SELECT clause or
the VALUES clause) must be separated by a comma followed by a
blank. For example, VALUES(1,1, 2,23, 4,1) is equivalent to
VALUES(1.1,2.23,4.1) in which the decimal point is a period.
*PERIOD: The value used as the decimal point for numeric constants in SQL
statements is a period.
*COMMA: The value used as the decimal point for numeric constants in SQL
statements is a comma.
Note: Any numeric constants in lists (such as in the SELECT clause or the
VALUES clause) must be separated by a comma followed by a blank.
For example, VALUES(1,1, 2,23, 4,1) is equivalent to
VALUES(1.1,2.23,4.1) where the decimal point is a period.
Element 5: String Delimiter Options
*QUOTESQL: A double quote (") is the string delimiter in the SQL statements.
*APOSTSQL: An apostrophe (') is the string delimiter in the SQL statements.
Element 6: Literal Options
*QUOTE: A double quote (") is used for non-numeric literals and Boolean
literals in the COBOL statements.
493
CRTSQLCBL
*APOST: An apostrophe (') is used for non-numeric literals and Boolean
literals in the COBOL statements.
Element 7: Naming Convention Option
*SYS: The system naming convention (library-name/file-name) is used.
*SQL: The SQL naming convention (collection-name.table-name) is used. When
creating a program on a remote database other than an AS/400 system, *SQL
must be specified as the naming convention.
Element 8: Second-Level Message Text Option
*NOSECLVL: Second-level text descriptions are not added to the listing.
*SECLVL: Second-level text with replacement data is added for all messages
on the listing.
Element 9: Debug Listing View
*NOLSTDBG: Error and debug information is not generated.
*LSTDBG: The SQL precompiler generates a listing view, and error and debug
information required for this view. You can use *LSTDBG only if you are using
the CODE/400 product to compile your program.
TGTRLS
Specifies the release of the operating system on which the user intends to use
the object being created.
In the examples given for the *CURRENT and *PRV values, and when
specifying the release-level value, the format VxRxMx is used to specify the
release, where Vx is the version, Rx is the release, and Mx is the modification
level. For example, V2R3M0 is version 2, release 3, modification level 0.
*CURRENT: The object is to be used on the release of the operating system
currently running on the users system. For example, if V2R3M5 is running on
the system, *CURRENT means the user intends to use the object on a system
with V2R3M5 installed. The user can also use the object on a system with any
subsequent release of the operating system installed.
Note: If V2R3M5 is running on the system, and the object is to be used on a
system with V2R3M0 installed, specify TGTRLS(V2R3M0) not
TGTRLS(*CURRENT).
*PRV: The object is to be used on the previous release with modification level 0
of the operating system. For example, if V2R3M5 is running on the users
system, *PRV means the user intends to use the object on a system with
V2R2M0 installed. The user can also use the object on a system with any
subsequent release of the operating system installed.
release-level: Specify the release in the format VxRxMx. The object can be used
on a system with the specified release or with any subsequent release of the
operating system installed.
Valid values depend on the current version, release, and modification level,
and they change with each new release. If you specify a release-level which is
494
CRTSQLCBL
earlier than the earliest release level supported by this command, an error
message is sent indicating the earliest supported release.
INCFILE
Specifies the qualified name of the source file that contains members included
in the program with any SQL INCLUDE statement.
The name of the source file can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
*SRCFILE: The qualified source file specified in the SRCFILE parameter
contains the source file member(s) specified on any SQL INCLUDE statement.
source-file-name: Specify the name of the source file that contains the source file
member(s) specified on any SQL INCLUDE statement. The record length of the
source file specified here must be no less than the record length of the source
file specified for the SRCFILE parameter.
COMMIT
Specifies whether SQL statements in the compiled program are run under
commitment control. Files referred to in the host language source are not
affected by this option. Only SQL tables, SQL views, and SQL packages
referred to in SQL statements are affected.
Note: Files referenced in the COBOL source are not affected by this option.
*CHG or *UR: Specifies the objects referred to in SQL ALTER, CALL,
COMMENT ON, CREATE, DROP, GRANT, LABEL ON, RENAME, and
REVOKE statements and the rows updated, deleted, and inserted are locked
until the end of the unit of work (transaction). Uncommitted changes in other
jobs can be seen.
*ALL or *RS: Specifies the objects referred to in SQL ALTER, CALL,
COMMENT ON, CREATE, DROP, GRANT, LABEL ON, RENAME, and
REVOKE statements and the rows selected, updated, deleted, and inserted are
locked until the end of the unit of work (transaction). Uncommitted changes in
other jobs cannot be seen.
*CS: Specifies the objects referred to in SQL ALTER, CALL, COMMENT ON,
CREATE, DROP, GRANT, LABEL ON, RENAME, and REVOKE statements and
the rows updated, deleted, and inserted are locked until the end of the unit of
work (transaction). A row that is selected, but not updated, is locked until the
next row is selected. Uncommitted changes in other jobs cannot be seen.
*NONE or *NC: Specifies that commitment control is not used. Uncommitted
changes in other jobs can be seen. If the SQL DROP COLLECTION statement
is included in the program, *NONE or *NC must be used. If a relational
database is specified on the RDB parameter and the relational database is on a
system that is not on an AS/400, *NONE or *NC cannot be specified.
495
CRTSQLCBL
*RR: Specifies the objects referred to in SQL ALTER, CALL, COMMENT ON,
CREATE, DROP, GRANT, LABEL ON, RENAME, and REVOKE statements and
the rows selected, updated, deleted, and inserted are locked until the end of
the unit of work (transaction). Uncommitted changes in other jobs cannot be
seen. All tables referred to in SELECT, UPDATE, DELETE, and INSERT
statements are locked exclusively until the end of the unit of work
(transaction).
CLOSQLCSR
Specifies when SQL cursors are implicitly closed, SQL prepared statements are
implicitly discarded, and LOCK TABLE locks are released. SQL cursors are
explicitly closed when you issue the CLOSE, COMMIT, or ROLLBACK
(without HOLD) SQL statements.
*ENDPGM: SQL cursors are closed and SQL prepared statements are
discarded when the program ends. LOCK TABLE locks are released when the
first SQL program on the call stack ends.
*ENDSQL: SQL cursors remain open between calls and can be fetched without
running another SQL OPEN. One of the programs higher on the call stack
must have run at least one SQL statement. SQL cursors are closed, SQL
prepared statements are discarded, and LOCK TABLE locks are released when
the first SQL program on the call stack ends. If *ENDSQL is specified for a
program that is the first SQL program called (the first SQL program on the call
stack), the program is treated as if *ENDPGM was specified.
*ENDJOB: SQL cursors remain open between calls and can be fetched without
running another SQL OPEN. The programs higher on the call stack do not
need to have run SQL statements. SQL cursors are left open, SQL prepared
statements are preserved, and LOCK TABLE locks are held when the first SQL
program on the call stack ends. SQL cursors are closed, SQL prepared
statements are discarded, and LOCK TABLE locks are released when the job
ends.
ALWCPYDTA
Specifies whether a copy of the data can be used in a SELECT statement.
*YES: A copy of the data is used only when necessary.
*OPTIMIZE: The system determines whether to use the data retrieved directly
from the database or to use a copy of the data. The decision is based on which
method provides the best performance. If COMMIT is *CHG or *CS and
ALWBLK is not *ALLREAD, or if COMMIT is *ALL or *RR, then a copy of the
data is used only when it is necessary to run a query.
*NO: A copy of the data is not allowed. If a temporary copy of the data is
required to perform the query, an error message is returned.
ALWBLK
Specifies whether the database manager can use record blocking, and the
extent to which blocking can be used for read-only cursors.
*READ: Records are blocked for read-only retrieval of data for cursors when:
v *NONE is specified on the COMMIT parameter, which indicates that
commitment control is not used.
496
CRTSQLCBL
v The cursor is declared with a FOR READ ONLY clause or there are no
dynamic statements that could run a positioned UPDATE or DELETE
statement for the cursor.
Specifying *READ can improve the overall performance of queries that meet
the above conditions and retrieve a large number of records.
*NONE: Rows are not blocked for retrieval of data for cursors.
Specifying *NONE:
v Guarantees that the data retrieved is current.
v May reduce the amount of time required to retrieve the first row of data for
a query.
v Stops the database manager from retrieving a block of data rows that is not
used by the program when only the first few rows of a query are retrieved
before the query is closed.
v Can degrade the overall performance of a query that retrieves a large
number of rows.
*ALLREAD: Rows are blocked for read-only cursors if *NONE or *CHG is
specified on the COMMIT parameter. All cursors in a program that are not
explicitly able to be updated are opened for read-only processing even though
EXECUTE or EXECUTE IMMEDIATE statements may be in the program.
Specifying *ALLREAD:
v Allows record blocking under commitment control level *CHG in addition to
the blocking allowed for *READ.
v Can improve the performance of almost all read-only cursors in programs,
but limits queries in the following ways:
The Rollback (ROLLBACK) command, a ROLLBACK statement in host
languages, or the ROLLBACK HOLD SQL statement does not reposition a
read-only cursor when *ALLREAD is specified.
Dynamic running of a positioned UPDATE or DELETE statement (for
example, using EXECUTE IMMEDIATE), cannot be used to update a row
in a cursor unless the DECLARE statement for the cursor includes the
FOR UPDATE clause.
DLYPRP
Specifies whether the dynamic statement validation for a PREPARE statement
is delayed until an OPEN, EXECUTE, or DESCRIBE statement is run. Delaying
validation improves performance by eliminating redundant validation.
*NO: Dynamic statement validation is not delayed. When the dynamic
statement is prepared, the access plan is validated. When the dynamic
statement is used in an OPEN or EXECUTE statement, the access plan is
revalidated. Because the authority or the existence of objects referred to by the
dynamic statement may change, you must still check the SQLCODE or
SQLSTATE after issuing the OPEN or EXECUTE statement to ensure that the
dynamic statement is still valid.
*YES: Dynamic statement validation is delayed until the dynamic statement is
used in an OPEN, EXECUTE, or DESCRIBE SQL statement. When the dynamic
statement is used, the validation is completed and an access plan is built. If
you specify *YES on this parameter, you should check the SQLCODE and
Appendix D. DB2 for AS/400 CL Command Descriptions
497
CRTSQLCBL
SQLSTATE after running an OPEN, EXECUTE, or DESCRIBE statement to
ensure that the dynamic statement is valid.
Note: If you specify *YES, performance is not improved if the INTO clause is
used on the PREPARE statement or if a DESCRIBE statement uses the
dynamic statement before an OPEN is issued for the statement.
GENLVL
Specifies the severity level at which the create operation fails. If errors occur
that have a severity level greater than or equal to this value, the operation
ends.
10: The default severity level is 10.
severity-level: Specify a value ranging from 0 through 40.
DATFMT
Specifies the format used when accessing date result columns. All output date
fields are returned in the specified format. For input date strings, the specified
value is used to determine whether the date is specified in a valid format.
Note: An input date string that uses the format *USA, *ISO, *EUR, or *JIS is
always valid.
If a relational database is specified on the RDB parameter and the
database is on a system that is not an AS/400 system, then *USA, *ISO,
*EUR, or *JIS must be specified.
*JOB: The format specified for the job is used. Use the Display Job (DSPJOB)
command to determine the current date format for the job.
*USA: The United States date format (mm/dd/yyyy) is used.
*ISO: The International Organization for Standardization (ISO) date format
(yyyy-mm-dd) is used.
*EUR: The European date format (dd.mm.yyyy) is used.
*JIS: The Japanese Industrial Standard date format (yyyy-mm-dd) is used.
*MDY: The date format (mm/dd/yy) is used.
*DMY: The date format (dd/mm/yy) is used.
*YMD: The date format (yy/mm/dd) is used.
*JUL: The Julian date format (yy/ddd) is used.
DATSEP
Specifies the separator used when accessing date result columns.
Note: This parameter applies only when *JOB, *MDY, *DMY, *YMD, or *JUL is
specified on the DATFMT parameter.
*JOB: The date separator specified for the job at precompile time is used. Use
the Display Job (DSPJOB) command to determine the current value for the job.
498
CRTSQLCBL
/: A slash (/) is used.
.: A period (.) is used.
,: A comma (,) is used.
-: A dash (-) is used.
: A blank ( ) is used.
*BLANK: A blank ( ) is used.
TIMFMT
Specifies the format used when accessing time result columns. For input time
strings, the specified value is used to determine whether the time is specified
in a valid format.
Note: An input date string that uses the format *USA, *ISO, *EUR, or *JIS is
always valid.
If a relational database is specified on the RDB parameter and the
database is on a system that is not another AS/400 system, the time
format must be *USA, *ISO, *EUR, *JIS, or *HMS with a time separator
of colon or period.
*HMS: The (hh:mm:ss) format is used.
*USA: The United States time format (hh:mm xx) is used, where xx is AM or
PM.
*ISO: The International Organization for Standardization (ISO) time format
(hh.mm.ss) is used.
*EUR: The European time format (hh.mm.ss) is used.
*JIS: The Japanese Industrial Standard time format (hh:mm:ss) is used.
TIMSEP
Specifies the separator used when accessing time result columns.
Note: This parameter applies only when *HMS is specified on the TIMFMT
parameter.
*JOB: The time separator specified for the job at precompile time is used. Use
the Display Job (DSPJOB) command to determine the current value for the job.
:: A colon (:) is used.
.: A period (.) is used.
,: A comma (,) is used.
: A blank ( ) is used.
*BLANK: A blank ( ) is used.
499
CRTSQLCBL
REPLACE
Specifies whether a new program or SQL package is created when a program
or SQL package of the same name exists in the same library. The value of this
parameter is passed to the CRTCBLPGM command. More information on this
parameter is in Appendix A, Expanded Parameter Descriptions in the CL
Reference (Abridged) book.
*YES: A new program or SQL package is created, and any existing program or
SQL package of the same name and type in the specified library is moved to
QRPLOBJ.
*NO: A new program or SQL package is not created if an object of the same
name and type already exists in the specified library.
RDB
Specifies the name of the relational database where the SQL package object is
created.
*LOCAL: The program is created as a distributed SQL program. The SQL
statements will access the local database. An SQL package object is not created
as part of the precompile process. The Create Structured Query Language
Package (CRTSQLPKG) command can be used.
relational-database-name: Specify the name of the relational database where the
new SQL package object is to be created. When the name of the local relational
database is specified, the program created is still a distributed SQL program.
The SQL statements will access the local database.
*NONE: An SQL package object is not created. The program object is not a
distributed program and the Create Structured Query Language Package
(CRTSQLPKG) command cannot be used.
USER
Specifies the user name sent to the remote system when starting the
conversation. This parameter is valid only when RDB is specified.
*CURRENT: The user profile under which the current job is running is used.
user-name: Specify the user name to be used for the application server job.
PASSWORD
Specifies the password to be used on the remote system. This parameter is
valid only if RDB is specified.
*NONE: No password is sent. If this value is specified, USER(*CURRENT)
must also be specified.
password: Specify the password of the user name specified on the USER
parameter.
RDBCNNMTH
Specifies the semantics used for CONNECT statements. Refer to the SQL
Reference book for more information.
*DUW: CONNECT (Type 2) semantics are used to support distributed unit of
work. Consecutive CONNECT statements to additional relational databases do
not result in disconnection of previous connections.
500
CRTSQLCBL
*RUW: CONNECT (Type 1) semantics are used to support remote unit of
work. Consecutive CONNECT statements result in the previous connection
being disconnected before a new connection is established.
DFTRDBCOL
Specifies the collection name used for the unqualified names of tables, views,
indexes, and SQL packages. This parameter applies only to static SQL
statements.
*NONE: The naming convention defined on the OPTION parameter is used.
collection-name: Specify the name of the collection identifier. This value is used
instead of the naming convention specified on the OPTION parameter.
SQLPKG
Specifies the qualified name of the SQL package created on the relational
database specified on the RDB parameter of this command.
The library values are:
*PGMLIB: The package is created in the library with the same name as the
library containing the program.
library-name: Specify the name of the library where the package is created.
*PGM: The package name is the same as the program name.
package-name: Specify the name of the package created on the remote database
specified on the RDB parameter.
SAAFLAG
Specifies the IBM SQL flagging function. This parameter flags SQL statements
to verify whether they conform to IBM SQL syntax More information about
which IBM database products IBM SQL syntax is in the DRDA IBM SQL
Reference, SC26-3255-00.
*NOFLAG: The precompiler does not check to see whether SQL statements
conform to IBM SQL syntax.
*FLAG: The precompiler checks to see whether SQL statements conform to
IBM SQL syntax.
FLAGSTD
Specifies the American National Standards Institute (ANSI) flagging function.
This parameter flags SQL statements to verify whether they conform to the
following standards.
ANSI X3.135-1992 entry
ISO 9075-1992 entry
FIPS 127.2 entry
*NONE: The precompiler does not check to see whether SQL statements
conform to ANSI standards.
*ANS: The precompiler checks to see whether SQL statements conform to
ANSI standards.
PRTFILE
Specifies the qualified name of the printer device file to which the listing is
directed. The file must have a minimum record length of 132 bytes or
information is lost.
Appendix D. DB2 for AS/400 CL Command Descriptions
501
CRTSQLCBL
The name of the printer file can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
QSYSPRT: If a file name is not specified, the precompiler printout is directed
to the IBM-supplied printer file QSYSPRT.
printer-file-name: Specify the name of the printer device file to which the
precompiler printout is directed.
SRTSEQ
Specifies the sort sequence table to be used for string comparisons in SQL
statements.
Note: *HEX must be specified for this parameter on distributed applications
where the application server is not on an AS/400 system or the release
level is prior to V2R3M0.
*JOB: The SRTSEQ value for the job is retrieved during the precompile.
*JOBRUN: The SRTSEQ value for the job is retrieved when the program is
run. For distributed applications, SRTSEQ(*JOBRUN) is valid only when
LANGID(*JOBRUN) is also specified.
*LANGIDUNQ: The unique-weight sort table for the language specified on the
LANGID parameter is used.
*LANGIDSHR: The shared-weight sort table for the language specified on the
LANGID parameter is used.
*HEX: A sort sequence table is not used. The hexadecimal values of the
characters are used to determine the sort sequence.
The name of the sort sequence table can be qualified by one of the following
library values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
table-name: Specify the name of the sort sequence table to be used.
LANGID
Specifies the language identifier to be used when SRTSEQ(*LANGIDUNQ) or
SRTSEQ(*LANGIDSHR) is specified.
*JOB: The LANGID value for the job is retrieved during the precompile.
*JOBRUN: The LANGID value for the job is retrieved when the program is
run. For distributed applications, LANGID(*JOBRUN) is valid only when
SRTSEQ(*JOBRUN) is also specified.
502
CRTSQLCBL
language-id: Specify a language identifier to be used by the program.
USRPRF
Specifies the user profile that is used when the compiled program object is run,
including the authority that the program object has for each object in static
SQL statements. The profile of either the program owner or the program user
is used to control which objects can be used by the program object.
*NAMING: The user profile is determined by the naming convention. If the
naming convention is *SQL, USRPRF(*OWNER) is used. If the naming
convention is *SYS, USRPRF(*USER) is used.
*USER: The profile of the user running the program object is used.
*OWNER: The user profiles of both the program owner and the program user
are used when the program is run.
DYNUSRPRF
Specifies the user profile used for dynamic SQL statements.
*USER: Local dynamic SQL statements are run under the user profile of the
job. Distributed dynamic SQL statements are run under the user profile of the
application server job.
*OWNER: Local dynamic SQL statements are run under the user profile of the
programs owner. Distributed dynamic SQL statements are run under the user
profile of the SQL packages owner.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
TOSRCFILE
Specifies the qualified name of the source file that is to contain the output
source member that has been processed by the SQL precompiler. If the
specified source file is not found, it will be created. The output member will
have the same name as the name that is specified for the SRCMBR parameter.
The possible library values are:
QTEMP: The library QTEMP will be used.
*LIBL: The jobs library list is searched for the specified file. If the file is not
found in any library in the library list, the file will be created in the current
library.
*CURLIB: The current library for the job will be used. If no library is
specified as the current library for the job, the QGPL library will be used.
library-name: Specify the name of the library that is to contain the output
source file.
source-file-name: Specify the name of the source file to contain the output source
member.
TEXT
Specifies the text that briefly describes the program and its function. More
information on this parameter is in Appendix A, Expanded Parameter
Descriptions in the CL Reference (Abridged)book.
*SRCMBRTXT: The text is taken from the source file member being used to
create the COBOL program. Text for a database source member can be added
or changed by using the Start Source Entry Utility (STRSEU) command, or by
Appendix D. DB2 for AS/400 CL Command Descriptions
503
CRTSQLCBL
using either the Add Physical File Member (ADDPFM) or Change Physical File
Member (CHGPFM) command. If the source file is an inline file or a device
file, the text is blank.
*BLANK: Text is not specified.
description: Specify no more than 50 characters of text, enclosed in
apostrophes.
Example
CRTSQLCBL PGM(ACCTS/STATS) SRCFILE(ACCTS/ACTIVE)
TEXT('Statistical analysis program for
active accounts')
This command runs the SQL precompiler which precompiles the source and stores
the changed source in the member STATS in file QSQLTEMP in library QTEMP.
The COBOL compiler is called to create program STATS in library ACCTS using
the source member created by the SQL precompiler.
Pgm: B,I
REXX: B,I
Exec
*CURLIB/
CRTSQLCBLI
OBJ(
object-name )
library-name/
*LIBL/
QCBLLESRC
source-file-name
SRCFILE(
*CURLIB/
library-name/
(1)
SRCMBR(
*OBJ
source-file-member-name
OPTION(
OPTION Details
)
TGTRLS(
*CURRENT
*PRV
VxRxMx
OBJTYPE(
*PGM
*MODULE
*SRVPGM
*LIBL/
INCFILE(
*CURLIB/
library-name/
504
*SRCFILE
source-file-name
CRTSQLCBLI
*UR
*CHG
*ALL
*RS
*CS
*NONE
*NC
*RR
COMMIT(
*ENDACTGRP
*ENDMOD
CLOSQLCSR(
ALWCPYDTA(
*YES
*OPTIMIZE
*NO
*READ
*NONE
*ALLREAD
ALWBLK(
*NO
*YES
DLYPRP(
GENLVL(
10
severity-level
*JOB
*USA
*ISO
*EUR
*JIS
*MDY
*DMY
*YMD
*JUL
DATFMT(
DATSEP(
*JOB
'/'
'.'
','
'-'
' '
*BLANK
*HMS
*USA
*ISO
*EUR
*JIS
TIMFMT(
TIMSEP(
*JOB
':'
'.'
','
' '
*BLANK
REPLACE(
*YES
*NO
RDB(
*LOCAL
relational-database-name
*NONE
USER(
*CURRENT
user-name
PASSWORD(
*NONE
password
RDBCNNMTH(
*DUW
*RUW
DFTRDBCOL(
*NONE
collection-name
*OBJLIB/
SQLPKG(
*OBJ
package-name
library-name/
505
CRTSQLCBLI
SAAFLAG(
*NOFLAG
*FLAG
DBGVIEW(
*NONE
*SOURCE
FLAGSTD(
*NONE
*ANS
USRPRF(
*NAMING
*OWNER
*USER
*USER
*OWNER
DYNUSRPRF(
*JOB
*JOBRUN
*LANGIDUNQ
*LANGIDSHR
*HEX
*LIBL/
SRTSEQ(
table-name
*CURLIB/
library-name/
*JOB
*JOBRUN
language-identifier
LANGID(
OUTPUT(
*NONE
*PRINT
*LIBL/
QSYSPRT
printer-file-name
PRTFILE(
*CURLIB/
library-name/
QTEMP/
QSQLTEMP
source-file-name
TOSRCFILE(
*LIBL/
*CURLIB/
library-name/
TEXT(
*SRCMBRTXT
*BLANK
'description'
OPTION Details
*XREF
*GEN
*JOB
*SYS
*NOSECLVL
*NOXREF
*NOGEN
*SYSVAL
*PERIOD
*COMMA
*SQL
*SECLVL
506
CRTSQLCBLI
*QUOTESQL
*QUOTE
*NOEVENTF
*APOSTSQL
*APOST
*EVENTF
Notes:
1. All parameters preceding this point can be specified in positional form.
Purpose
The Create Structured Query Language ILE COBOL Object (CRTSQLCBLI)
command calls the Structured Query Language (SQL) precompiler which
precompiles COBOL source containing SQL statements, produces a temporary
source member, and then optionally calls the ILE COBOL compiler to create a
module, a program, or a service program.
Parameters
OBJ
Specifies the qualified name of the object being created.
*CURLIB: The new object is created in the current library for the job. If no
library is specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library where the object is created.
object-name: Specify the name of the object that is being created.
SRCFILE
Specifies the qualified name of the source file that contains the COBOL source
with SQL statements.
The name of the source file can be qualified by one of the following library
values:
*LIBL All libraries in the jobs library list are searched until the first match
is found.
*CURLIB The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
QCBLLESRC: If the source file name is not specified, the source file
QCBLLESRC contains the COBOL source.
source-file-name: Specify the name of the source file that contains the COBOL
source.
SRCMBR
Specifies the name of the source file member that contains the COBOL source.
This parameter is specified only if the source file name in the SRCFILE
parameter is a database file. If this parameter is not specified, the OBJ name
specified on the OBJ parameter is used.
*OBJ: Specifies that the COBOL source is in the member of the source file that
has the same name as that specified on the OBJ parameter.
507
CRTSQLCBLI
source-file-member-name: Specify the name of the member that contains the
COBOL source.
OPTION
Specifies whether one or more of the following options are used when the
COBOL source is precompiled. If an option is specified more than once, or if
two options conflict, the last option specified is used.
Element 1: Cross-Reference Options
*XREF: The precompiler cross-references items in the program to the statement
numbers in the program that refer to those items.
*NOXREF: The precompiler does not cross-reference names.
Element 2: Program Creation Options
*GEN: The precompiler creates the object that is specified by the OBJTYPE
parameter.
*NOGEN: The precompiler does not call the ILE COBOL compiler, and a
module, program, service program, or SQL package are not created.
Element 3: Decimal Point Options
*JOB: The value used as the decimal point for numeric constants in SQL is the
representation of decimal point specified for the job at precompile time.
*SYSVAL: The value used as the decimal point for numeric constants in SQL
statements is the QDECFMT system value.
*PERIOD: The value used as the decimal point for numeric constants in SQL
statements is a period (.).
Note: If QDECFMT specifies that the value used as the decimal point is a
comma (,), any numeric constants in lists (such as in the SELECT clause
or the VALUES clause) must be separated by a comma (,) followed by a
blank ( ). For example, VALUES(1,1, 2,23, 4,1) is equivalent to
VALUES(1.1,2.23,4.1) in which the decimal point is a period (.).
*COMMA: The value used as the decimal point for numeric constants in SQL
statements is a comma (,).
Note: Any numeric constants in lists (such as in the SELECT clause or the
VALUES clause) must be separated by a comma (,) followed by a blank(
). For example, VALUES(1,1, 2,23, 4,1) is equivalent to
VALUES(1.1,2.23,4.1) where the decimal point is a period(.).
Element 4: Naming Convention Options
*SYS: The system naming convention (library-name/file-name) is used.
*SQL: The SQL naming convention is used (collection-name.table-name).
When creating a program on a remote database other than an AS/400 system,
*SQL must be specified as the naming convention.
508
CRTSQLCBLI
Element 5: Second-Level Message Text Option
*NOSECLVL: Second-level text descriptions are not added to the listing.
*SECLVL: Second-level text with replacement data is added for all messages
on the listing.
Element 6: String Delimiter Options
*QUOTESQL: A double quote (") is the string delimiter in the SQL statements.
*APOSTSQL: An apostrophe (') is the string delimiter in the SQL statements.
Element 7: Literal Options
*QUOTE: A double quote (") is used for literals which are not numeric and
Boolean literals in the COBOL statements.
*APOST: An apostrophe (') is used for literals which are not numeric and
Boolean literals in the COBOL statements.
Element 8: Event File Creation
*NOEVENTF: The compiler will not produce an event file for use by
CoOperative Development Environment/400 (CODE/400).
*EVENTF: The compiler produces an event file for use by CoOperative
Development Environment/400 (CODE/400). The event file will be created as
a member in the file EVFEVENT in your source library. CODE/400 uses this
file to offer error feedback integrated with the CODE/400 editor. This option is
normally specified by CODE/400 on your behalf.
TGTRLS
Specifies the release of the operating system on which the user intends to use
the object being created.
In the examples given for the *CURRENT and *PRV values, and when
specifying the release-level value, the format VxRxMx is used to specify the
release, where Vx is the version, Rx is the release, and Mx is the modification
level. For example, V2R3M0 is version 2, release 3, modification level 0.
*CURRENT: The object is to be used on the release of the operating system
currently running on the users system. For example, if V2R3M5 is running on
the system, *CURRENT means the user intends to use the object on a system
with V2R3M5 installed. The user can also use the object on a system with any
subsequent release of the operating system installed.
Note: If V2R3M5 is running on the system, and the object is to be used on a
system with V2R3M0 installed, specify TGTRLS(V2R3M0) not
TGTRLS(*CURRENT).
*PRV: The object is to be used on the previous release with modification level 0
of the operating system. For example, if V2R3M5 is running on the users
system, *PRV means the user intends to use the object on a system with
V2R2M0 installed. The user can also use the object on a system with any
subsequent release of the operating system installed.
509
CRTSQLCBLI
release-level: Specify the release in the format VxRxMx. The object can be used
on a system with the specified release or with any subsequent release of the
operating system installed.
Valid values depend on the current version, release, and modification level,
and they change with each new release. If you specify a release-level which is
earlier than the earliest release level supported by this command, an error
message is sent indicating the earliest supported release.
OBJTYPE
Specifies the type of object being created.
*PGM: The SQL precompiler issues the CRTBNDCBL command to create the
bound program.
*MODULE: The SQL precompiler issues the CRTCBLMOD command to create
the module.
*SRVPGM: The SQL precompiler issues the CRTCBLMOD and CRTSRVPGM
commands to create the service program.
Notes:
1. When OBJTYPE(*PGM) or OBJTYPE(*SRVPGM) is specified and the RDB
parameter is also specified, the CRTSQLPKG command is issued by the
SQL precompiler after the program has been created. When
OBJTYPE(*MODULE) is specified, an SQL package is not created and you
must issue the CRTSQLPKG command after the CRTPGM or CRTSRVPGM
command has created the program.
2. If *NOGEN is specified, only the SQL temporary source member is
generated and a module, program, service program, or SQL package are
not created.
INCFILE
Specifies the qualified name of the source file that contains members included
in the program with any SQL INCLUDE statement.
The name of the source file can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
*SRCFILE: The qualified source file specified in the SRCFILE parameter
contains the source file members specified on any SQL INCLUDE statement.
source-file-name: Specify the name of the source file that contains the source file
members specified on any SQL INCLUDE statement. The record length of the
source file specified here must be no less than the record length of the source
file specified on the SRCFILE parameter.
COMMIT
Specifies whether SQL statements in the compiled unit are run under
commitment control. Files referred to in the host language source are not
affected by this option. Only SQL tables, SQL views, and SQL packages
referred to in SQL statements are affected.
510
CRTSQLCBLI
*CHG or *UR: Specifies the objects referred to in SQL ALTER, CALL,
COMMENT ON, CREATE, DROP, GRANT, LABEL ON, RENAME, and
REVOKE statements and the rows updated, deleted, and inserted are locked
until the end of the unit of work (transaction). Uncommitted changes in other
jobs can be seen.
*ALL or *RS: Specifies the objects referred to in SQL ALTER, CALL,
COMMENT ON, CREATE, DROP, GRANT, LABEL ON, RENAME, and
REVOKE statements and the rows selected, updated, deleted, and inserted are
locked until the end of the unit of work (transaction). Uncommitted changes in
other jobs cannot be seen.
*CS: Specifies the objects referred to in SQL ALTER, CALL, COMMENT ON,
CREATE, DROP, GRANT, LABEL ON, RENAME, and REVOKE statements and
the rows updated, deleted, and inserted are locked until the end of the unit of
work (transaction). A row that is selected, but not updated, is locked until the
next row is selected. Uncommitted changes in other jobs cannot be seen.
*NONE or *NC: Specifies that commitment control is not used. Uncommitted
changes in other jobs can be seen. If the SQL DROP COLLECTION statement
is included in the program, *NONE or *NC must be used. If a relational
database is specified on the RDB parameter and the relational database is on a
system that is not on an AS/400, *NONE or *NC cannot be specified.
*RR: Specifies the objects referred to in SQL ALTER, CALL, COMMENT ON,
CREATE, DROP, GRANT, LABEL ON, RENAME, and REVOKE statements and
the rows selected, updated, deleted, and inserted are locked until the end of
the unit of work (transaction). Uncommitted changes in other jobs cannot be
seen. All tables referred to in SELECT, UPDATE, DELETE, and INSERT
statements are locked exclusively until the end of the unit of work
(transaction).
CLOSQLCSR
Specifies when SQL cursors are implicitly closed, SQL prepared statements are
implicitly discarded, and LOCK TABLE locks are released. SQL cursors are
explicitly closed when you issue the CLOSE, COMMIT, or ROLLBACK
(without HOLD) SQL statements.
*ENDACTGRP: SQL cursors are closed, SQL prepared statements are
implicitly discarded, and LOCK TABLE locks are released when the activation
group ends.
*ENDMOD: SQL cursors are closed and SQL prepared statements are
implicitly discarded when the module is exited. LOCK TABLE locks are
released when the activation group ends.
ALWCPYDTA
Specifies whether a copy of the data can be used in a SELECT statement.
*YES: A copy of the data is used only when necessary.
*OPTIMIZE: The system determines whether to use the data retrieved directly
from the database or to use a copy of the data. The decision is based on which
method provides the best performance. If COMMIT is *CHG or *CS and
ALWBLK is not *ALLREAD, or if COMMIT is *ALL or *RR, then a copy of the
data is used only when it is necessary to run a query.
511
CRTSQLCBLI
*NO: A copy of the data is not used. If a temporary copy of the data is
required to perform the query, an error message is returned.
ALWBLK
Specifies whether the database manager can use record blocking, and the
extent to which blocking can be used for read-only cursors.
*READ: Records are blocked for read-only retrieval of data for cursors when:
v *NONE is specified on the COMMIT parameter, which indicates that
commitment control is not used.
v The cursor is declared with a FOR READ ONLY clause or there are no
dynamic statements that could run a positioned UPDATE or DELETE
statement for the cursor.
Specifying *READ can improve the overall performance of queries that meet
the above conditions and retrieve a large number of records.
*NONE: Rows are not blocked for retrieval of data for cursors.
Specifying *NONE:
v Guarantees that the data retrieved is current.
v May reduce the amount of time required to retrieve the first row of data for
a query.
v Stops the database manager from retrieving a block of data rows that is not
used by the program when only the first few rows of a query are retrieved
before the query is closed.
v Can degrade the overall performance of a query that retrieves a large
number of rows.
*ALLREAD: Rows are blocked for read-only cursors if *NONE or *CHG is
specified on the COMMIT parameter. All cursors in a program that are not
explicitly able to be updated are opened for read-only processing even though
EXECUTE or EXECUTE IMMEDIATE statements may be in the program.
Specifying *ALLREAD:
v Allows record blocking under commitment control level *CHG in addition to
the blocking allowed for *READ.
v Can improve the performance of almost all read-only cursors in programs,
but limits queries in the following ways:
The Rollback (ROLLBACK) command, a ROLLBACK statement in host
languages, or the ROLLBACK HOLD SQL statement does not reposition a
read-only cursor when *ALLREAD is specified.
Dynamic running of a positioned UPDATE or DELETE statement (for
example, using EXECUTE IMMEDIATE), cannot be used to update a row
in a cursor unless the DECLARE statement for the cursor includes the
FOR UPDATE clause.
DLYPRP
Specifies whether the dynamic statement validation for a PREPARE statement
is delayed until an OPEN, EXECUTE, or DESCRIBE statement is run. Delaying
validation improves performance by eliminating redundant validation.
*NO: Dynamic statement validation is not delayed. When the dynamic
statement is prepared, the access plan is validated. When the dynamic
512
CRTSQLCBLI
statement is used in an OPEN or EXECUTE statement, the access plan is
revalidated. Because the authority or the existence of objects referred to by the
dynamic statement may change, you must still check the SQLCODE or
SQLSTATE after issuing the OPEN or EXECUTE statement to ensure that the
dynamic statement is still valid.
*YES: Dynamic statement validation is delayed until the dynamic statement is
used in an OPEN, EXECUTE, or DESCRIBE SQL statement. When the dynamic
statement is used, the validation is completed and an access plan is built. If
you specify *YES on this parameter, you should check the SQLCODE and
SQLSTATE after running an OPEN, EXECUTE, or DESCRIBE statement to
ensure that the dynamic statement is valid.
Note: If you specify *YES, performance is not improved if the INTO clause is
used on the PREPARE statement or if a DESCRIBE statement uses the
dynamic statement before an OPEN is issued for the statement.
GENLVL
Specifies the severity level at which the create operation fails. If errors occur
that have a severity level greater than this value, the operation ends.
10: The default severity level is 10.
severity-level: Specify a value ranging from 0 through 40.
DATFMT
Specifies the format used when accessing date result columns. All output date
fields are returned in the specified format. For input date strings, the specified
value is used to determine whether the date is specified in a valid format.
Note: An input date string that uses the format *USA, *ISO, *EUR, or *JIS is
always valid.
If a relational database is specified on the RDB parameter and the
database is on a system that is not an AS/400 system, then *USA, *ISO,
*EUR, or *JIS must be specified.
*JOB: The format specified for the job is used. Use the Display Job (DSPJOB)
command to determine the current date format for the job.
*USA: The United States date format (mm/dd/yyyy) is used.
*ISO: The International Organization for Standardization (ISO) date format
(yyyy-mm-dd) is used.
*EUR: The European date format (dd.mm.yyyy) is used.
*JIS: The Japanese Industrial Standard date format (yyyy-mm-dd) is used.
*MDY: The date format (mm/dd/yy) is used.
*DMY: The date format (dd/mm/yy) is used.
*YMD: The date format (yy/mm/dd) is used.
*JUL: The Julian date format (yy/ddd) is used.
513
CRTSQLCBLI
DATSEP
Specifies the separator used when accessing date result columns.
Note: This parameter applies only when *JOB, *MDY, *DMY, *YMD, or *JUL is
specified on the DATFMT parameter.
*JOB: The date separator specified for the job at precompile time is used. Use
the Display Job (DSPJOB) command to determine the current value for the job.
/: A slash (/) is used.
.: A period (.) is used.
,: A comma (,) is used.
-: A dash (-) is used.
: A blank ( ) is used.
*BLANK: A blank ( ) is used.
TIMFMT
Specifies the format used when accessing time result columns. For input time
strings, the specified value is used to determine whether the time is specified
in a valid format.
Note: An input date string that uses the format *USA, *ISO, *EUR, or *JIS is
always valid.
If a relational database is specified on the RDB parameter and the
database is on a system that is not another AS/400 system, the time
format must be *USA, *ISO, *EUR, *JIS, or *HMS with a time separator
of a colon or period.
*HMS: The hh:mm:ss format is used.
*USA: The United States time format hh:mm xx is used, where xx is AM or
PM.
*ISO: The International Organization for Standardization (ISO) time format
hh.mm.ss is used.
*EUR: The European time format hh.mm.ss is used.
*JIS: The Japanese Industrial Standard time format hh:mm:ss is used.
TIMSEP
Specifies the separator used when accessing time result columns.
Note: This parameter applies only when *HMS is specified on the TIMFMT
parameter.
*JOB: The time separator specified for the job at precompile time is used. Use
the Display Job (DSPJOB) command to determine the current value for the job.
:: A colon (:) is used.
514
CRTSQLCBLI
.: A period (.) is used.
,: A comma (,) is used.
: A blank ( ) is used.
*BLANK: A blank ( ) is used.
REPLACE
Specifies if a SQL module, program, service program or package is created
when there is an existing SQL module, program, service program, or package
of the same name and type in the same library. The value of this parameter is
passed to the CRTCBLMOD, CRTBNDCBL, CRTSRVPGM, and CRTSQLPKG
commands.
*YES: A new SQL module, program, service program, or package is created,
any existing SQL object of the same name and type in the specified library is
moved to QRPLOBJ.
*NO: A new SQL module, program, service program, or package is not created
if an SQL object of the same name and type already exists in the specified
library.
RDB
Specifies the name of the relational database where the SQL package object is
created.
*LOCAL: The program is created as a distributed SQL program. The SQL
statements will access the local database. An SQL package object is not created
as part of the precompile process. The Create Structured Query Language
Package (CRTSQLPKG) command can be used.
relational-database-name: Specify the name of the relational database where the
new SQL package object is to be created. When the name of the local relational
database is specified, the program created is still a distributed SQL program.
The SQL statements will access the local database.
*NONE: An SQL package object is not created. The program object is not a
distributed program and the Create Structured Query Language Package
(CRTSQLPKG) command cannot be used.
USER
Specifies the user name sent to the remote system when starting the
conversation. This parameter is valid only when RDB is specified.
*CURRENT: The user profile under which the current job is running is used.
user-name: Specify the user name being used for the application server job.
PASSWORD
Specifies the password to be used on the remote system. This parameter is
valid only if RDB is specified.
*NONE: No password is sent. If this value is specified, USER(*CURRENT)
must also be specified.
password: Specify the password of the user name specified on the USER
parameter.
Appendix D. DB2 for AS/400 CL Command Descriptions
515
CRTSQLCBLI
RDBCNNMTH
Specifies the semantics used for CONNECT statements. Refer to the SQL
Reference book for more information.
*DUW: CONNECT (Type 2) semantics are used to support distributed unit of
work. Consecutive CONNECT statements to additional relational databases do
not result in disconnection of previous connections.
*RUW: CONNECT (Type 1) semantics are used to support remote unit of
work. Consecutive CONNECT statements result in the previous connection
being disconnected before a new connection is established.
DFTRDBCOL
Specifies the collection name used for the unqualified names of tables, views,
indexes, and SQL packages. This parameter applies only to static SQL
statements.
*NONE: The naming convention defined on the OPTION parameter is used.
collection-name: Specify the name of the collection identifier. This value is used
instead of the naming convention specified on the OPTION parameter.
SQLPKG
Specifies the qualified name of the SQL package created on the relational
database specified on the RDB parameter of this command.
The possible library values are:
*OBJLIB: The package is created in the library with the same name as the
library specified on the OBJ parameter.
library-name: Specify the name of the library where the package is created.
*OBJ: The name of the SQL package is the same as the object name specified
on the OBJ parameter.
package-name: Specify the name of the SQL package. If the remote system is not
an AS/400 system, no more than 8 characters can be specified.
SAAFLAG
Specifies the IBM SQL flagging function. This parameter flags SQL statements
to verify whether they conform to IBM SQL syntax More information about
which IBM database products IBM SQL syntax is in the DRDA IBM SQL
Reference, SC26-3255-00.
*NOFLAG: The precompiler does not check to see whether SQL statements
conform to IBM SQL syntax.
*FLAG: The precompiler checks to see whether SQL statements conform to
IBM SQL syntax.
FLAGSTD
Specifies the American National Standards Institute (ANSI) flagging function.
This parameter flags SQL statements to verify whether they conform to the
following standards.
ANSI X3.135-1992 entry
ISO 9075-1992 entry
FIPS 127.2 entry
516
CRTSQLCBLI
*NONE: The precompiler does not check to see whether SQL statements
conform to ANSI standards.
*ANS: The precompiler checks to see whether SQL statements conform to
ANSI standards.
DBGVIEW
Specifies the type of source debug information to be provided by the SQL
precompiler.
*NONE: The source view is not generated.
*SOURCE: The SQL precompiler provides the source views for the root and if
necessary, SQL INCLUDE statements. A view is provided which contains the
statements generated by the precompiler.
USRPRF
Specifies the user profile that is used when the compiled program object is run,
including the authority that the program object has for each object in static
SQL statements. The profile of either the program owner or the program user
is used to control which objects can be used by the program object.
*NAMING: The user profile is determined by the naming convention. If the
naming convention is *SQL, USRPRF(*OWNER) is used. If the naming
convention is *SYS, USRPRF(*USER) is used.
*USER: The profile of the user running the program object is used.
*OWNER: The user profiles of both the program owner and the program user
are used when the program is run.
DYNUSRPRF
Specifies the user profile to be used for dynamic SQL statements.
*USER: For local programs, dynamic SQL statements run under the profile of
the programs user. For distributed programs, dynamic SQL statements run
under the profile of the SQL packages user.
*OWNER: For local programs, dynamic SQL statements run under the profile
of the programs owner. For distributed programs, dynamic SQL statements
run under the profile of the SQL packages owner.
SRTSEQ
Specifies the sort sequence table to be used for string comparisons in SQL
statements.
Note: *HEX must be specified for this parameter on distributed applications
where the application server is not on an AS/400 system or the release level is
prior to V2R3M0.
*JOB: The SRTSEQ value for the job is retrieved during the precompile.
*JOBRUN: The SRTSEQ value for the job is retrieved when the program is
run. For distributed applications, SRTSEQ(*JOBRUN) is valid only when
LANGID(*JOBRUN) is also specified.
*LANGIDUNQ: The unique-weight sort table for the language specified on the
LANGID parameter is used.
Appendix D. DB2 for AS/400 CL Command Descriptions
517
CRTSQLCBLI
The name of the table name can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
*LANGIDSHR: The sort sequence table uses the same weight for multiple
characters, and is the shared-weight sort sequence table associated with the
language specified on the LANGID parameter.
*HEX: A sort sequence is not used. The hexadecimal values of the characters
are used to determine the sort sequence.
table-name: Specify the name of the sort sequence table to be used.
LANGID
Specifies the language identifier to be used when SRTSEQ(*LANGIDUNQ) or
SRTSEQ(*LANGIDSHR) is specified.
*JOB: The LANGID value for the job is retrieved during the precompile.
*JOBRUN: The LANGID value for the job is retrieved when the program is
run. For distributed applications, LANGID(*JOBRUN) is valid only when
SRTSEQ(*JOBRUN) is also specified.
language-identifier: Specify a language identifier.
OUTPUT
Specifies whether the precompiler listing is generated.
*NONE: The precompiler listing is not generated.
*PRINT: The precompiler listing is generated.
PRTFILE
Specifies the qualified name of the printer device file to which the precompiler
printout is directed. The file must have a minimum length of 132 bytes. If a file
with a record length of less than 132 bytes is specified, information is lost.
The name of the printer file can be qualified by one of the following library
values:
*LIBL All libraries in the jobs library list are searched until the first match
is found.
*CURLIB The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
QSYSPRT: If a file name is not specified, the precompiler printout is directed
to the IBM-supplied printer file QSYSPRT.
printer-file-name: Specify the name of the printer device file to which the
precompiler printout is directed.
518
CRTSQLCBLI
|
|
|
|
|
TOSRCFILE
Specifies the qualified name of the source file that is to contain the output
source member that has been processed by the SQL precompiler. If the
specified source file is not found, it will be created. The output member will
have the same name as the name that is specified for the SRCMBR parameter.
The possible library values are:
QTEMP: The library QTEMP will be used.
|
|
|
|
|
*LIBL: The jobs library list is searched for the specified file. If the file is not
found in any library in the library list, the file will be created in the current
library.
|
|
*CURLIB: The current library for the job will be used. If no library is
specified as the current library for the job, the QGPL library will be used.
library-name: Specify the name of the library that is to contain the output
source file.
|
|
|
source-file-name: Specify the name of the source file to contain the output source
member.
TEXT
Specifies the text that briefly describes the printer file. More information on
this parameter is in Appendix A, Expanded Parameter Descriptions in the CL
Reference (Abridged) book.
*SRCMBRTXT: The text is taken from the source file member being used to
create the COBOL program. Text can be added or changed for a database
source member by using the Start Source Entry Utility (STRSEU) command, or
by using either the Add Physical File Member (ADDPFM) or Change Physical
File Member (CHGPFM) command. If the source file is an inline file or a
device file, the text is blank.
*BLANK: Text is not specified.
description: Specify no more than 50 characters of text, enclosed in
apostrophes.
Example
CRTSQLCBLI
This command runs the SQL precompiler which precompiles the source and stores
the changed source in member PAYROLL in file QSQLTEMP in library QTEMP.
The ILE COBOL compiler is called to create module PAYROLL in the current
library by using the source member created by the SQL precompiler.
Pgm: B,I
REXX: B,I
Exec
*CURLIB/
CRTSQLCI
OBJ(
object-name )
library-name/
Appendix D. DB2 for AS/400 CL Command Descriptions
519
CRTSQLCI
*LIBL/
QCSRC
source-file-name
SRCFILE(
*CURLIB/
library-name/
(1)
SRCMBR(
*OBJ
source-file-member-name
OPTION(
OPTION Details
*CURRENT
*PRV
VxRxMx
TGTRLS(
OBJTYPE(
*MODULE
*PGM
*SRVPGM
*LIBL/
*SRCFILE
source-file-name
INCFILE(
*CURLIB/
library-name/
COMMIT(
*UR
*CHG
*ALL
*RS
*CS
*NONE
*NC
*RR
CLOSQLCSR(
*ENDACTGRP
*ENDMOD
*YES
*OPTIMIZE
*NO
ALWCPYDTA(
ALWBLK(
*READ
*NONE
*ALLREAD
DLYPRP(
*NO
*YES
GENLVL(
10
severity-level
MARGINS(
520
*SRCFILE
left-right
DATFMT(
*JOB
*USA
*ISO
*EUR
*JIS
*MDY
*DMY
*YMD
*JUL
CRTSQLCI
*JOB
'/'
'.'
','
'-'
' '
*BLANK
DATSEP(
TIMFMT(
*HMS
*USA
*ISO
*EUR
*JIS
TIMSEP(
*JOB
':'
'.'
','
' '
*BLANK
REPLACE(
*YES
*NO
RDB(
*LOCAL
relational-database-name
*NONE
USER(
*CURRENT
user-name
PASSWORD(
*NONE
password
*DUW
*RUW
RDBCNNMTH(
DFTRDBCOL(
*NONE
collection-name
*OBJLIB/
*OBJ
package-name
SQLPKG(
library-name/
SAAFLAG(
*NOFLAG
*FLAG
DBGVIEW(
*NONE
*SOURCE
FLAGSTD(
*NONE
*ANS
USRPRF(
*NAMING
*OWNER
*USER
DYNUSRPRF(
*USER
*OWNER
SRTSEQ(
*JOB
*JOBRUN
*LANGIDUNQ
*LANGIDSHR
*HEX
*LIBL/
table-name
*CURLIB/
library-name/
521
CRTSQLCI
*JOB
*JOBRUN
language-identifier
LANGID(
OUTPUT(
*NONE
*PRINT
*LIBL/
QSYSPRT
printer-file-name
PRTFILE(
*CURLIB/
library-name/
QTEMP/
QSQLTEMP
source-file-name
TOSRCFILE(
*LIBL/
*CURLIB/
library-name/
TEXT(
*SRCMBRTXT
*BLANK
'description'
OPTION Details
*XREF
*GEN
*PERIOD
*SYS
*NOSECLVL
*NOXREF
*NOGEN
*JOB
*SYSVAL
*COMMA
*SQL
*SECLVL
*NOCNULRQD
*NOEVENTF
*CNULRQD
*EVENTF
Notes:
1. All parameters preceding this point can be specified in positional form.
Purpose
The Create Structured Query Language ILE C Object (CRTSQLCI) command calls
the Structured Query Language (SQL) precompiler that precompiles C source
containing SQL statements, produces a temporary source member, and then
optionally calls the ILE C compiler to create a module, create a program, or create
a service program.
Parameters
OBJ
Specifies the qualified name of the object being created.
The name of the object can be qualified by one of the following library values:
*CURLIB: The object is created in the current library for the job. If no
library is specified as the current library for the job, the QGPL library is
used.
library-name: Specify the name of the library where the object is created.
522
CRTSQLCI
object-name: Specify the name of the object that is being created.
SRCFILE
Specifies the qualified name of the source file that contains the C source with
SQL statements.
The name of the source file can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
QCSRC: If the source file name is not specified, the IBM-supplied source file
QCSRC contains the C source.
source-file-name: Specify the name of the source file that contains the C source.
SRCMBR
Specifies the name of the source file member that contains the C source. This
parameter is only specified if the source file name in the SRCFILE parameter is
a database file. If this parameter is not specified, the OBJ name specified on the
OBJ parameter is used.
*OBJ: Specifies that the C source is in the member of the source file that has
the same name as that specified on the OBJ parameter.
source-file-member-name: Specify the name of the member that contains the C
source.
OPTION
Specifies whether one or more of the following options are used when the C
source is precompiled. If an option is specified more than once, or if two
options conflict, the last option specified is used.
Element 1: Cross-Reference Options
*XREF: The precompiler cross-references items in the program to the statement
numbers in the program that refer to those items.
*NOXREF: The precompiler does not cross-reference names.
Element 2: Program Creation Options
*GEN: The precompiler creates the object that is specified by the OBJTYPE
parameter.
*NOGEN: The precompiler does not call the C compiler, and a module,
program, service program, or SQL package is not created.
Element 3: Decimal Point Options
*PERIOD: The value used as the decimal point for numeric constants in SQL
statements is a period.
523
CRTSQLCI
*JOB: The value used as the decimal point for numeric constants in SQL is the
representation of decimal point specified for the job at precompile time.
*SYSVAL: The value used as the decimal point for numeric constants in SQL
statements is the QDECFMT system value.
Note: If QDECFMT specifies that the value used as the decimal point is a
comma, any numeric constants in lists (such as in the SELECT clause or
the VALUES clause) must be separated by a comma followed by a
blank. For example, VALUES(1,1, 2,23, 4,1) is equivalent to
VALUES(1.1,2.23,4.1) in which the decimal point is a period.
*COMMA: The value used as the decimal point for numeric constants in SQL
statements is a comma.
Note: Any numeric constants in lists (such as in the SELECT clause or the
VALUES clause) must be separated by a comma followed by a blank.
For example, VALUES(1,1, 2,23, 4,1) is equivalent to
VALUES(1.1,2.23,4.1) where the decimal point is a period.
Element 4: Naming Convention Options
*SYS: The system naming convention (library-name/file-name) is used.
*SQL: The SQL naming convention is used (collection-name.table-name). When
creating a package on a remote database other than an AS/400 system, *SQL
must be specified as the naming convention.
Element 5: Second-Level Message Text Option
*NOSECLVL: Second-level text descriptions are not added to the listing.
*SECLVL: Second-level text with replacement data is added for all messages
on the listing.
Element 6: NUL Required Options
*NOCNULRQD: For output character and graphic host variables, the
NUL-terminator is not returned when the host variable is exactly the same
length as the data. Input character and graphic host variables do not require a
NUL-terminator.
*CNULRQD: Output character and graphic host variables always contain the
NUL-terminator. If there is not enough space for the NUL-terminator, the data
is truncated and the NUL-terminator is added. Input character and graphic
host variables require a NUL-terminator.
Element 7: Event File Creation
*NOEVENTF: The compiler will not produce an event file for use by
CoOperative Development Environment/400 (CODE/400).
*EVENTF: The compiler produces an event file for use by CoOperative
Development Environment/400 (CODE/400). The event file will be created as
a member in the file EVFEVENT in your source library. CODE/400 uses this
524
CRTSQLCI
file to offer error feedback integrated with the CODE/400 editor. This option is
normally specified by CODE/400 on your behalf.
TGTRLS
Specifies the release of the operating system on which the user intends to use
the object being created.
In the examples given for the *CURRENT and *PRV values, and when
specifying the release-level value, the format VxRxMx is used to specify the
release, where Vx is the version, Rx is the release, and Mx is the modification
level. For example, V2R3M0 is version 2, release 3, modification level 0.
*CURRENT: The object is to be used on the release of the operating system
currently running on the users system. For example, if V2R3M5 is running on
the system, *CURRENT means the user intends to use the object on a system
with V2R3M5 installed. The user can also use the object on a system with any
subsequent release of the operating system installed.
Note: If V2R3M5 is running on the system, and the object is to be used on a
system with V2R3M0 installed, specify TGTRLS(V2R3M0) not
TGTRLS(*CURRENT).
*PRV: The object is to be used on the previous release with modification level 0
of the operating system. For example, if V2R3M5 is running on the users
system, *PRV means the user intends to use the object on a system with
V2R2M0 installed. The user can also use the object on a system with any
subsequent release of the operating system installed.
release-level: Specify the release in the format VxRxMx. The object can be used
on a system with the specified release or with any subsequent release of the
operating system installed.
Valid values depend on the current version, release, and modification level,
and they change with each new release. If you specify a release-level which is
earlier than the earliest release level supported by this command, an error
message is sent indicating the earliest supported release.
OBJTYPE
Specifies the type of object being created.
*MODULE: The SQL precompiler issues the CRTCMOD command to create
the module.
*PGM: The SQL precompiler issues the CRTBNDC command to create the
bound program.
*SRVPGM: The SQL precompiler issues the CRTCMOD and CRTSRVPGM
commands to create the service program.
The user must create a source member in QSRVSRC that has the same name as
the name specified on the OBJ parameter. The source member must contain the
export information for the module. More information on the export file is in
the Integrated Language Environment*C/400 Programmers Guide.
Notes:
1. When OBJTYPE(*PGM) or OBJTYPE(*SRVPGM) is specified and the RDB
parameter is also specified, the CRTSQLPKG command is issued by the
SQL precompiler after the program has been created. When
Appendix D. DB2 for AS/400 CL Command Descriptions
525
CRTSQLCI
OBJTYPE(*MODULE) is specified, an SQL package is not created and the
user must issue the CRTSQLPKG command after the CRTPGM or
CRTSRVPGM command has created the program.
2. If *NOGEN is specified, only the SQL temporary source member is
generated and a module, program, service program, or SQL package is not
created.
INCFILE
Specifies the qualified name of the source file that contains members included
in the program with any SQL INCLUDE statement.
The name of the source file can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
*SRCFILE: The qualified source file specified in the SRCFILE parameter
contains the source file members specified on any SQL INCLUDE statement.
source-file-name: Specify the name of the source file that contains the source file
members specified on any SQL INCLUDE statement. The record length of the
source file specified here must be no less than the record length of the source
file specified on the SRCFILE parameter.
COMMIT
Specifies whether SQL statements in the compiled unit are run under
commitment control. Files referred to in the host language source are not
affected by this option. Only SQL tables, SQL views, and SQL packages
referred to in SQL statements are affected.
*CHG or *UR: Specifies the objects referred to in SQL ALTER, CALL,
COMMENT ON, CREATE, DROP, GRANT, LABEL ON, RENAME, and
REVOKE statements and the rows updated, deleted, and inserted are locked
until the end of the unit of work (transaction). Uncommitted changes in other
jobs can be seen.
*ALL or *RS: Specifies the objects referred to in SQL ALTER, CALL,
COMMENT ON, CREATE, DROP, GRANT, LABEL ON, RENAME, and
REVOKE statements and the rows selected, updated, deleted, and inserted are
locked until the end of the unit of work (transaction). Uncommitted changes in
other jobs cannot be seen.
*CS: Specifies the objects referred to in SQL ALTER, CALL, COMMENT ON,
CREATE, DROP, GRANT, LABEL ON, RENAME, and REVOKE statements and
the rows updated, deleted, and inserted are locked until the end of the unit of
work (transaction). A row that is selected, but not updated, is locked until the
next row is selected. Uncommitted changes in other jobs cannot be seen.
*NONE or *NC: Specifies that commitment control is not used. Uncommitted
changes in other jobs can be seen. If the SQL DROP COLLECTION statement
is included in the program, *NONE or *NC must be used. If a relational
database is specified on the RDB parameter and the relational database is on a
system that is not on an AS/400, *NONE or *NC cannot be specified.
526
CRTSQLCI
*RR: Specifies the objects referred to in SQL ALTER, CALL, COMMENT ON,
CREATE, DROP, GRANT, LABEL ON, RENAME, and REVOKE statements and
the rows selected, updated, deleted, and inserted are locked until the end of
the unit of work (transaction). Uncommitted changes in other jobs cannot be
seen. All tables referred to in SELECT, UPDATE, DELETE, and INSERT
statements are locked exclusively until the end of the unit of work
(transaction).
CLOSQLCSR
Specifies when SQL cursors are implicitly closed, SQL prepared statements are
implicitly discarded, and LOCK TABLE locks are released. SQL cursors are
explicitly closed when you issue the CLOSE, COMMIT, or ROLLBACK
(without HOLD) SQL statements.
*ENDACTGRP: SQL cursors are closed, SQL prepared statements are
implicitly discarded, and LOCK TABLE locks are released when the activation
group ends.
*ENDMOD: SQL cursors are closed and SQL prepared statements are
implicitly discarded when the module is exited. LOCK TABLE locks are
released when the first SQL program on the call stack ends.
ALWCPYDTA
Specifies whether a copy of the data can be used in a SELECT statement.
*YES: A copy of the data is used only when necessary.
*OPTIMIZE: The system determines whether to use the data retrieved directly
from the database or to use a copy of the data. The decision is based on which
method provides the best performance. If COMMIT is *CHG or *CS and
ALWBLK is not *ALLREAD, or if COMMIT is *ALL or *RR, then a copy of the
data is used only when it is necessary to run a query.
*NO: A copy of the data is not allowed. If a temporary copy of the data is
required to perform the query, an error message is returned.
ALWBLK
Specifies whether the database manager can use record blocking, and the
extent to which blocking can be used for read-only cursors.
*READ: Records are blocked for read-only retrieval of data for cursors when:
v *NONE is specified on the COMMIT parameter, which indicates that
commitment control is not used.
v The cursor is declared with a FOR READ ONLY clause or there are no
dynamic statements that could run a positioned UPDATE or DELETE
statement for the cursor.
Specifying *READ can improve the overall performance of queries that meet
the above conditions and retrieve a large number of records.
*NONE: Rows are not blocked for retrieval of data for cursors.
Specifying *NONE:
v Guarantees that the data retrieved is current.
v May reduce the amount of time required to retrieve the first row of data for
a query.
Appendix D. DB2 for AS/400 CL Command Descriptions
527
CRTSQLCI
v Stops the database manager from retrieving a block of data rows that is not
used by the program when only the first few rows of a query are retrieved
before the query is closed.
v Can degrade the overall performance of a query that retrieves a large
number of rows.
*ALLREAD: Rows are blocked for read-only cursors if *NONE or *CHG is
specified on the COMMIT parameter. All cursors in a program that are not
explicitly able to be updated are opened for read-only processing even though
EXECUTE or EXECUTE IMMEDIATE statements may be in the program.
Specifying *ALLREAD:
v Allows record blocking under commitment control level *CHG in addition to
the blocking allowed for *READ.
v Can improve the performance of almost all read-only cursors in programs,
but limits queries in the following ways:
The Rollback (ROLLBACK) command, a ROLLBACK statement in host
languages, or the ROLLBACK HOLD SQL statement does not reposition a
read-only cursor when *ALLREAD is specified.
Dynamic running of a positioned UPDATE or DELETE statement (for
example, using EXECUTE IMMEDIATE), cannot be used to update a row
in a cursor unless the DECLARE statement for the cursor includes the
FOR UPDATE clause.
DLYPRP
Specifies whether the dynamic statement validation for a PREPARE statement
is delayed until an OPEN, EXECUTE, or DESCRIBE statement is run. Delaying
validation improves performance by eliminating redundant validation.
*NO: Dynamic statement validation is not delayed. When the dynamic
statement is prepared, the access plan is validated. When the dynamic
statement is used in an OPEN or EXECUTE statement, the access plan is
revalidated. Because the authority or the existence of objects referred to by the
dynamic statement may change, you must still check the SQLCODE or
SQLSTATE after issuing the OPEN or EXECUTE statement to ensure that the
dynamic statement is still valid.
*YES: Dynamic statement validation is delayed until the dynamic statement is
used in an OPEN, EXECUTE, or DESCRIBE SQL statement. When the dynamic
statement is used, the validation is completed and an access plan is built. If
you specify *YES on this parameter, you should check the SQLCODE and
SQLSTATE after running an OPEN, EXECUTE, or DESCRIBE statement to
ensure that the dynamic statement is valid.
Note: If you specify *YES, performance is not improved if the INTO clause is
used on the PREPARE statement or if a DESCRIBE statement uses the
dynamic statement before an OPEN is issued for the statement.
GENLVL
Specifies the severity level at which the create operation fails. If errors occur
that have a severity level greater than this value, the operation ends.
10: The default severity level is 10.
severity-level: Specify a value ranging from 0 through 40.
528
CRTSQLCI
MARGINS
Specifies the part of the precompiler input record that contains source text.
|
*SRCFILE: The precompiler uses file member margin values that are specified
by the user on the SRCMBR parameter. The margin values default to 1 and 80.
Element 1: Left Margin
left: Specify the beginning position for the statements. Valid values range from
1 through 80.
Element 2: Right Margin
right: Specify the ending position for the statements. Valid values range from 1
through 80.
DATFMT
Specifies the format used when accessing date result columns. All output date
fields are returned in the specified format. For input date strings, the specified
value is used to determine whether the date is specified in a valid format.
Note: An input date string that uses the format *USA, *ISO, *EUR, or *JIS is
always valid.
If a relational database is specified on the RDB parameter and the
database is on a system that is not an AS/400 system, then *USA, *ISO,
*EUR, or *JIS must be specified.
*JOB: The format specified for the job is used. Use the Display Job (DSPJOB)
command to determine the current date format for the job.
*USA: The United States date format (mm/dd/yyyy) is used.
*ISO: The International Organization for Standardization (ISO) date format
(yyyy-mm-dd) is used.
*EUR: The European date format (dd.mm.yyyy) is used.
*JIS: The Japanese Industrial Standard date format (yyyy-mm-dd) is used.
*MDY: The date format (mm/dd/yy) is used.
*DMY: The date format (dd/mm/yy) is used.
*YMD: The date format (yy/mm/dd) is used.
*JUL: The Julian date format (yy/ddd) is used.
DATSEP
Specifies the separator used when accessing date result columns.
Note: This parameter applies only when *JOB, *MDY, *DMY, *YMD, or *JUL is
specified on the DATFMT parameter.
*JOB:The date separator specified for the job at precompile time is used. Use
the Display Job (DSPJOB) command to determine the current value for the job.
529
CRTSQLCI
/: A slash (/) is used.
.: A period (.) is used.
,: A comma (,) is used.
-: A dash (-) is used.
: A blank ( ) is used.
*BLANK: A blank ( ) is used.
TIMFMT
Specifies the format used when accessing time result columns. For input time
strings, the specified value is used to determine whether the time is specified
in a valid format.
Note: An input time string that uses the format *USA, *ISO, *EUR, or *JIS is
always valid.
If a relational database is specified on the RDB parameter and the
database is on a system that is not another AS/400 system, the time
format must be *USA, *ISO, *EUR, *JIS, or *HMS with a time separator
of colon or period.
*HMS: The hh:mm:ss format is used.
*USA: The United States time format hh:mm xx is used, where xx is AM or
PM.
*ISO: The International Organization for Standardization (ISO) time format
hh.mm.ss is used.
*EUR: The European time format hh.mm.ss is used.
*JIS: The Japanese Industrial Standard time format hh:mm:ss is used.
TIMSEP
Specifies the separator used when accessing time result columns.
Note: This parameter applies only when *HMS is specified on the TIMFMT
parameter.
*JOB: The time separator specified for the job at precompile time is used. Use
the Display Job (DSPJOB) command to determine the current value for the job.
:: A colon (:) is used.
.: A period (.) is used.
,: A comma (,) is used.
: A blank ( ) is used.
*BLANK: A blank ( ) is used.
530
CRTSQLCI
REPLACE
Specifies if a SQL module, program, service program or package is created
when there is an existing SQL module, program, service program, or package
of the same name and type in the same library. The value of this parameter is
passed to the CRTCMOD, CRTBNDC, CRTSRVPGM, and CRTSQLPKG
commands.
*YES: A new SQL module, program, service program, or package is created,
and any existing object of the same name and type in the specified library is
moved to QRPLOBJ.
*NO: A new SQL module, program, service program, or package is not created
if an object of the same name and type already exists in the specified library.
RDB
Specifies the name of the relational database where the SQL package object is
created.
*LOCAL: The program is created as a distributed SQL program. The SQL
statements will access the local database. An SQL package object is not created
as part of the precompile process. The Create Structured Query Language
Package (CRTSQLPKG) command can be used.
relational-database-name: Specify the name of the relational database where the
new SQL package object is to be created. When the name of the local relational
database is specified, the program created is still a distributed SQL program.
The SQL statements will access the local database.
*NONE: An SQL package object is not created. The program object is not a
distributed program and the Create Structured Query Language Package
(CRTSQLPKG) command cannot be used.
USER
Specifies the user name sent to the remote system when starting the
conversation. This parameter is valid only when RDB is specified.
*CURRENT: The user profile under which the current job is running is used.
user-name: Specify the user name being used for the application server job.
PASSWORD
Specifies the password to be used on the remote system. This parameter is
valid only if RDB is specified.
*NONE: No password is sent. If this value is specified, USER(*CURRENT)
must also be specified.
password: Specify the password of the user name specified on the USER
parameter.
RDBCNNMTH
Specifies the semantics used for CONNECT statements. Refer to the SQL
Reference, SC41-3612 book for more information.
*DUW: CONNECT (Type 2) semantics are used to support distributed unit of
work. Consecutive CONNECT statements to additional relational databases do
not result in disconnection of previous connections.
531
CRTSQLCI
*RUW: CONNECT (Type 1) semantics are used to support remote unit of
work. Consecutive CONNECT statements result in the previous connection
being disconnected before a new connection is established.
DFTRDBCOL
Specifies the collection name used for the unqualified names of tables, views,
indexes, and SQL packages. This parameter applies only to static SQL
statements.
*NONE: The naming convention defined on the OPTION parameter is used.
collection-name: Specify the name of the collection identifier. This value is used
instead of the naming convention specified on the OPTION parameter.
SQLPKG
Specifies the qualified name of the SQL package created on the relational
database specified on the RDB parameter of this command.
The possible library values are:
*OBJLIB: The package is created in the library with the same name as the
library specified on the OBJ parameter.
library-name: Specify the name of the library where the package is created.
*OBJ: The name of the SQL package is the same as the object name specified
on the OBJ parameter.
package-name: Specify the name of the SQL package. If the remote system is not
an AS/400 system, no more than 8 characters can be specified.
SAAFLAG
Specifies the IBM SQL flagging function. This parameter flags SQL statements
to verify whether they conform to IBM SQL syntax More information about
which IBM database products IBM SQL syntax is in the DRDA IBM SQL
Reference, SC26-3255-00.
*NOFLAG: The precompiler does not check to see whether SQL statements
conform to IBM SQL syntax.
*FLAG: The precompiler checks to see whether SQL statements conform to
IBM SQL syntax
FLAGSTD
Specifies the American National Standards Institute (ANSI) flagging function.
This parameter flags SQL statements to verify whether they conform to the
following standards.
ANSI X3.135-1992 entry
ISO 9075-1992 entry
FIPS 127.2 entry
*NONE: The precompiler does not check to see whether SQL statements
conform to ANSI standards.
*ANS: The precompiler checks to see whether SQL statements conform to
ANSI standards.
DBGVIEW
This parameter specifies the type of source debug information to be provided
by the SQL precompiler.
532
CRTSQLCI
*NONE: The source view will not be generated.
*SOURCE: The SQL precompiler provides the source views for the root and if
necessary, SQL INCLUDE statements. A view is provided that contains the
statements generated by the precompiler.
USRPRF
Specifies the user profile that is used when the compiled program object is run,
including the authority that the program object has for each object in static
SQL statements. The profile of either the program owner or the program user
is used to control which objects can be used by the program object.
*NAMING: The user profile is determined by the naming convention. If the
naming convention is *SQL, USRPRF(*OWNER) is used. If the naming
convention is *SYS, USRPRF(*USER) is used.
*USER: The profile of the user running the program object is used.
*OWNER: The user profiles of both the program owner and the program user
are used when the program is run.
DYNUSRPRF
Specifies the user profile to be used for dynamic SQL statements.
*USER: Local dynamic SQL statements are run under the profile of the
programs user. Distributed dynamic SQL statements are run under the profile
of the SQL packages user.
*OWNER: Local dynamic SQL statements are run under the profile of the
programs owner. Distributed dynamic SQL statements are run under the
profile of the SQL packages owner.
SRTSEQ
Specifies the sort sequence table to be used for string comparisons in SQL
statements.
Note: *HEX must be specified for this parameter on distributed applications
where the application server is not on an AS/400 system or the release
level is prior to V2R3M0.
*JOB: The SRTSEQ value for the job is retrieved during the precompile.
*JOBRUN: The SRTSEQ value for the job is retrieved when the program is
run. For distributed applications, SRTSEQ(*JOBRUN) is valid only when
LANGID(*JOBRUN) is also specified.
*HEX: A sort sequence table is not used. The hexadecimal values of the
characters are used to determine the sort sequence.
*LANGIDSHR: The sort sequence table uses the same weight for multiple
characters, and is the shared-weight sort sequence table associated with the
language specified on the LANGID parameter.
*LANGIDUNQ: The unique-weight sort table for the language specified on the
LANGID parameter is used.
533
CRTSQLCI
The name of the table name can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of hte library to be searched.
table-name: Specify the name of the sort sequence table to be used.
LANGID
Specifies the language identifier to be used when SRTSEQ(*LANGIDUNQ) or
SRTSEQ(*LANGIDSHR) is specified.
*JOB: The LANGID value for the job is retrieved during the precompile.
*JOBRUN: The LANGID value for the job is retrieved when the program is
run. For distributed applications, LANGID(*JOBRUN) is valid only when
SRTSEQ(*JOBRUN) is also specified.
language-identifier: Specify a language identifier.
OUTPUT
Specifies whether the precompiler listing is generated.
*NONE: The precompiler listing is not generated.
*PRINT: The precompiler listing is generated.
PRTFILE
Specifies the qualified name of the printer device file to which the precompiler
printout is directed. The file must have a minimum length of 132 bytes. If a file
with a record length of less than 132 bytes is specified, information is lost.
The name of the printer file can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
QSYSPRT: If a file name is not specified, the precompiler printout is directed
to the IBM-supplied printer file QSYSPRT.
printer-file-name: Specify the name of the printer device file to which the
precompiler printout is directed.
TOSRCFILE
Specifies the qualified name of the source file that is to contain the output
source member that the SQL precompiler has processed. If the precompiler
cannot find the specified source file, it creates the file. The output member will
have the same name as the name that is specified for the SRCMBR parameter.
|
|
|
|
|
|
|
534
CRTSQLCI
|
|
|
*LIBL: The jobs library list is searched for the specified file. If the file is not
found in any library in the library list, the file will be created in the current
library.
|
|
*CURLIB: The current library for the job will be used. If no library is
specified as the current library for the job, the QGPL library will be used.
library-name: Specify the name of the library that is to contain the output
source file.
|
|
|
source-file-name: Specify the name of the source file to contain the output source
member.
TEXT
Specifies the text that briefly describes the program and the function. More
information on this parameter is in Appendix A, Expanded Parameter
Descriptions in the CL Reference book.
*SRCMBRTXT: The text is taken from the source file member being used to
create the C program. Text can be added or changed for a database source
member by using the Start Source Entry Utility (STRSEU) command, or by
using either the Add Physical File Member (ADDPFM) command or the
Change Physical File Member (CHGPFM) command. If the source file is an
inline file or a device file, the text is blank.
*BLANK: Text is not specified.
description: Specify no more than 50 characters of text, enclosed in
apostrophes.
Example
CRTSQLCI PAYROLL OBJTYPE(*MODULE)
TEXT('Payroll Program')
|
|
|
|
This command runs the SQL precompiler which precompiles the source and stores
the changed source in member PAYROLL in file QSQLTEMP in library QTEMP.
The ILE C for AS/400 compiler is called to create module PAYROLL in the current
library by using the source member created by the SQL precompiler.
Job: B,I
|
|
Pgm: B,I
REXX: B,I
Exec
*CURLIB/
CRTSQLCPPI
OBJ(
object-name )
library-name/
|
|
*LIBL/
SRCFILE(
QCSRC
source-file-name
*CURLIB/
library-name/
535
|
|
CRTSQLCPPI
(1)
|
|
SRCMBR(
*OBJ
source-file-member-name
OPTION(
OPTION Details
*CURRENT
VxRxMx
TGTRLS(
|
|
*LIBL/
*SRCFILE
source-file-name
INCFILE(
*CURLIB/
library-name/
|
|
COMMIT(
|
|
*UR
*CHG
*ALL
*RS
*CS
*NONE
*NC
*RR
CLOSQLCSR(
*YES
*OPTIMIZE
*NO
ALWCPYDTA(
|
|
ALWBLK(
*READ
*NONE
*ALLREAD
DLYPRP(
|
|
*NO
*YES
GENLVL(
10
severity-level
MARGINS(
|
|
*SRCFILE
left-right
DATFMT(
*JOB
*USA
*ISO
*EUR
*JIS
*MDY
*DMY
*YMD
*JUL
DATSEP(
*ENDACTGRP
*ENDMOD
536
*JOB
'/'
'.'
','
'-'
' '
*BLANK
TIMFMT(
*HMS
*USA
*ISO
*EUR
*JIS
|
|
CRTSQLCPPI
*JOB
':'
'.'
','
' '
*BLANK
TIMSEP(
|
|
REPLACE(
|
|
RDB(
*LOCAL
relational-database-name
*NONE
*CURRENT
user-name
PASSWORD(
*NONE
password
RDBCNNMTH(
|
|
*YES
*NO
USER(
|
|
*DUW
*RUW
DFTRDBCOL(
*NONE
collection-name
*OBJLIB/
*OBJ
package-name
SQLPKG(
library-name/
|
|
|
|
|
|
SAAFLAG(
*NOFLAG
*FLAG
DBGVIEW(
*NONE
*SOURCE
FLAGSTD(
USRPRF(
*NAMING
*OWNER
*USER
DYNUSRPRF(
|
|
*NONE
*ANS
*USER
*OWNER
SRTSEQ(
*JOB
*JOBRUN
*LANGIDUNQ
*LANGIDSHR
*HEX
*LIBL/
table-name
*CURLIB/
library-name/
|
|
LANGID(
|
|
*JOB
*JOBRUN
language-identifier
OUTPUT(
*NONE
*PRINT
*LIBL/
PRTFILE(
QSYSPRT
printer-file-name
*CURLIB/
library-name/
537
|
|
CRTSQLCPPI
QTEMP/
QSQLTEMP
source-file-name
TOSRCFILE(
*LIBL/
*CURLIB/
library-name/
|
|
TEXT(
*SRCMBRTXT
*BLANK
'description'
OPTION Details
|
|
|
*XREF
*GEN
*JOB
*SYS
*NOSECLVL
*NOXREF
*NOGEN
*PERIOD
*SYSVAL
*COMMA
*SQL
*SECLVL
|
|
*NOCNULRQD
*NOEVENTF
*CNULRQD
*EVENTF
Notes:
1. All parameters preceding this point can be specified in positional form.
|
|
Purpose
|
|
|
|
|
The Create Structured Query Language C++ Object (CRTSQLCPPI) command calls
the Structured Query Language (SQL) precompiler. The SQL precompiler
precompiles C++ source containing SQL statements, produces a temporary source
member, and then optionally calls the C++ compiler to create a module.
|
|
To precompile for the VisualAge C++ for AS/400 compiler, use the CVTSQLCPP
command.
Parameters
OBJ
Specifies the qualified name of the object that the precompiler creates.
|
|
One of the following library values can qualify the name of the object:
*CURLIB The object is created in the current library for the job. If you do
not specify a library as the current library for the job, the precompiler uses
QGPL library.
library-name: Specify the name of the library where the object is created.
object-name: Specify the name of the object that the precompiler creates.
|
|
|
SRCFILE
Specifies the qualified name of the source file that contains the C++ source
with SQL statements.
One of the following library values can qualify the name of the source file:
|
|
|
|
538
CRTSQLCPPI
|
|
|
|
|
|
*LIBL: The precompiler searches all libraries in the jobs library list until it
finds the first match.
*CURLIB: The precompiler searches the current library for the job. If you
do not specify a library as the current library for the job, it uses the QGPL
library.
library-name: Specify the name of the library that the precompiler searches.
|
|
QCSRC: If you do not specify the source file name, the IBM-supplied source
file QCSRC contains the C++ source.
|
|
source-file-name: Specify the name of the source file that contains the C++
source.
|
|
|
|
|
SRCMBR
Specifies the name of the source file member that contains the C++ source.
Specify this parameter only if the source file name in the SRCFILE parameter is
a database file. If you do not specify this parameter, the precompiler uses the
OBJ name that is specified on the OBJ parameter.
|
|
*OBJ: Specifies that the C++ source is in the member of the source file that has
the same name as the file specified on the OBJ parameter.
|
|
source-file-member-name: Specify the name of the member that contains the C++
source.
|
|
|
|
OPTION
Specifies whether one or more of the following options are used when the C++
source is precompiled. If an option is specified more than once, or if two
options conflict, the last option specified is used.
|
|
|
|
*NOGEN: The precompiler does not call the C++ compiler, and does not create
a module.
|
|
*JOB: The value used as the decimal point for numeric constants in SQL is the
representation of decimal point that is specified for the job at precompile time.
|
|
|
|
|
Note: If the job specifies that the value used as the decimal point is a comma,
any numeric constants in lists (such as in the SELECT clause or the
VALUES clause) must be separated by a comma followed by a blank.
For example, VALUES(1,1, 2,23, 4,1) is equivalent to
VALUES(1.1,2.23,4.1) in which the decimal point is a period.
539
CRTSQLCPPI
|
|
*PERIOD:The value used as the decimal point for numeric constants in SQL
statements is a period.
|
|
*COMMA: The value used as the decimal point for numeric constants in SQL
statements is a comma.
|
|
|
|
Note: Any numeric constants in lists (such as in the SELECT clause or the
VALUES clause) must be separated by a comma followed by a blank.
For example, VALUES(1,1, 2,23, 4,1) is equivalent to
VALUES(1.1,2.23,4.1) where the decimal point is a period.
|
|
|
|
|
*SECLVL: Second-level text with replacement data is added for all messages
on the listing.
|
|
|
|
|
|
|
|
*CNULRQD: Output character and graphic host variables always contain the
NUL-terminator. If there is not enough space for the NUL-terminator, the data
is truncated, and the NUL-terminator is added. Input character and graphic
host variables require a NUL-terminator.
|
|
*NOEVENTF: The compiler will not produce an event file for use by
CoOperative Development Environment/400 (CODE/400).
|
|
|
|
|
|
|
|
The examples given for the *CURRENT value, as well as the release-level value,
use the format VxRxMx to specify the release. In this format, Vx is the version,
|
|
540
CRTSQLCPPI
|
|
|
|
|
|
|
|
|
|
|
|
|
release-level: Specify the release in the format VxRxMx. The object can be used
on a system with the specified release or with any subsequent release of the
operating system installed.
|
|
|
|
Valid values depend on the current version, release, and modification level,
and they change with each new release. If you specify a release-level which is
earlier than the earliest release level that is supported by this command, an
error message is sent indicating the earliest supported release.
|
|
|
INCFILE
Specifies the qualified name of the source file that contains members that are
included in the program with any SQL INCLUDE statement.
One of the following library values can qualify the name of the source file:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
|
|
|
|
|
|
|
source-file-name: Specify the name of the source file that contains the source file
members that are specified on any SQL INCLUDE statement. The record length
of the source file that is specified here must be no less than the record length
of the source file specified on the SRCFILE parameter.
|
|
|
|
|
|
|
|
|
|
COMMIT
Specifies whether SQL statements in the compiled unit are run under
commitment control. Files referred to in the host language source are not
affected by this option. Only SQL tables, SQL views, and SQL packages
referred to in SQL statements are affected.
|
|
|
|
|
|
|
541
CRTSQLCPPI
|
|
|
REVOKE statements and the rows selected, updated, deleted, and inserted are
locked until the end of the unit of work (transaction). Uncommitted changes in
other jobs cannot be seen.
|
|
|
|
|
*CS: Specifies the objects referred to in SQL ALTER, CALL, COMMENT ON,
CREATE, DROP, GRANT, LABEL ON, RENAME, and REVOKE statements and
the rows updated, deleted, and inserted are locked until the end of the unit of
work (transaction). A row that is selected, but not updated, is locked until the
next row is selected. Uncommitted changes in other jobs cannot be seen.
|
|
|
|
|
|
|
|
|
|
|
|
*RR: Specifies the objects referred to in SQL ALTER, CALL, COMMENT ON,
CREATE, DROP, GRANT, LABEL ON, RENAME, and REVOKE statements and
the rows selected, updated, deleted, and inserted are locked until the end of
the unit of work (transaction). Uncommitted changes in other jobs cannot be
seen. All tables referred to in SELECT, UPDATE, DELETE, and INSERT
statements are locked exclusively until the end of the unit of work
(transaction).
|
|
|
|
|
CLOSQLCSR
Specifies when SQL cursors are implicitly closed, SQL prepared statements are
implicitly discarded, and LOCK TABLE locks are released. SQL cursors are
explicitly closed when you issue the CLOSE, COMMIT, or ROLLBACK
(without HOLD) SQL statements.
|
|
|
|
|
|
*ENDMOD: SQL cursors are closed, and SQL prepared statements are
implicitly discarded when the module is exited. LOCK TABLE locks are
released when the first SQL program on the call stack ends.
ALWCPYDTA
Specifies whether a copy of the data can be used in a SELECT statement.
|
|
|
|
|
|
|
|
*OPTIMIZE: The system determines whether to use the data retrieved directly
from the database or to use a copy of the data. The decision is based on which
method provides the best performance. If COMMIT is *CHG or *CS and
ALWBLK is not *ALLREAD, or if COMMIT is *ALL or *RR, then a copy of the
data is used only when it is necessary to run a query.
|
|
*NO: A copy of the data is not allowed. If a temporary copy of the data is
required to perform the query, an error message is returned.
ALWBLK
Specifies whether the database manager can use record blocking, and the
extent to which blocking can be used for read-only cursors.
|
|
|
542
CRTSQLCPPI
|
|
|
*READ: Records are blocked for read-only retrieval of data for cursors in the
following situations:
v *NONE is specified on the COMMIT parameter, which indicates that
commitment control is not used.
v The cursor is declared with a FOR READ ONLY clause or there are no
dynamic statements that could run a positioned UPDATE or DELETE
statement for the cursor.
|
|
Specifying *READ can improve the overall performance of queries that meet
the above conditions and retrieve a large number of records.
*NONE: Rows are not blocked for retrieval of data for cursors.
Specifying *NONE:
|
|
|
|
|
|
Specifying *ALLREAD:
v Allows record-blocking under commitment control level *CHG in addition to
the blocking allowed for *READ.
v Can improve the performance of almost all read-only cursors in programs,
but limits queries in the following ways:
The Rollback (ROLLBACK) command, a ROLLBACK statement in host
languages, or the ROLLBACK HOLD SQL statement does not reposition a
read-only cursor when *ALLREAD is specified.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
DLYPRP
Specifies whether the dynamic statement validation for a PREPARE statement
is delayed until an OPEN, EXECUTE, or DESCRIBE statement is run. Delaying
validation improves performance by eliminating redundant validation.
|
|
|
|
|
|
|
543
CRTSQLCPPI
|
|
|
|
|
|
|
|
|
Note: If you specify *YES, performance is not improved if the INTO clause is
used on the PREPARE statement or if a DESCRIBE statement uses the
dynamic statement before an OPEN is issued for the statement.
GENLVL
Specifies the severity level at which the create operation fails. If errors occur
that have a severity level greater than this value, the operation ends.
|
|
|
|
|
|
|
|
|
|
|
*SRCFILE: The file member margin values specified by the user on the
SRCMBR parameter are used. If the member is of SQLCLE, SQLC, C, or CLE
source type, the margin values are the values that are specified on the SEU
services display. If the member is a different source type, the margin values are
the default values of 1 and 80.
|
|
left: Specify the beginning position for the statements. Valid values range from
1 through 80.
|
|
right: Specify the ending position for the statements. Valid values range from 1
through 80.
|
|
|
|
DATFMT
Specifies the format used when accessing date result columns. All output date
fields are returned in the specified format. For input date strings, the specified
value is used to determine whether the date is specified in a valid format.
Note: An input date string that uses the format *USA, *ISO, *EUR, or *JIS is
always valid.
|
|
|
|
|
|
|
*JOB: The format specified for the job is used. Use the Display Job (DSPJOB)
command to determine the current date format for the job.
|
|
544
CRTSQLCPPI
|
|
|
DATSEP
Specifies the separator used when accessing date result columns.
|
|
Note: This parameter applies only when *JOB, *MDY, *DMY, *YMD, or *JUL is
specified on the DATFMT parameter.
|
|
*JOB:The date separator specified for the job at precompile time is used. Use
the Display Job (DSPJOB) command to determine the current value for the job.
: A blank ( ) is used.
|
|
|
|
|
|
|
|
|
|
TIMFMT
Specifies the format used when accessing time result columns. For input time
strings, the specified value is used to determine whether the time is specified
in a valid format.
Note: An input time string that uses the format *USA, *ISO, *EUR, or *JIS is
always valid.
If a relational database is specified on the RDB parameter and the
database is on a system that is not another AS/400 system, the time
format must be *USA, *ISO, *EUR, *JIS, or *HMS with a time separator
of colon or period.
|
|
|
|
545
CRTSQLCPPI
TIMSEP
Specifies the separator used when accessing time result columns.
|
|
|
|
Note: This parameter applies only when *HMS is specified on the TIMFMT
parameter.
|
|
*JOB: The time separator specified for the job at precompile time is used. Use
the Display Job (DSPJOB) command to determine the current value for the job.
: A blank ( ) is used.
|
|
|
|
REPLACE
Specifies if an SQL module is created when there is an existing SQL module of
the same name in the same library. The value of this parameter is passed to the
CRTCPPMOD command.
|
|
*YES: A new SQL module is created, and any existing object of the same name
in the specified library is moved to QRPLOBJ.
|
|
*NO: A new SQL module is not created if an object of the same name already
exists in the specified library.
RDB
Specifies the name of the relational database where the SQL package object is
created.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
*NONE: An SQL package object is not created. The program object is not a
distributed program and the Create Structured Query Language Package
(CRTSQLPKG) command cannot be used.
USER
Specifies the user name sent to the remote system when starting the
conversation. This parameter is valid only when RDB is specified.
|
|
|
|
*CURRENT: The user profile under which the current job is running is used.
user-name: Specify the user name being used for the application server job.
546
CRTSQLCPPI
|
|
|
PASSWORD
Specifies the password to be used on the remote system. This parameter is
valid only if RDB is specified.
|
|
|
|
password: Specify the password of the user name that is specified on the USER
parameter.
|
|
|
RDBCNNMTH
Specifies the semantics used for CONNECT statements. Refer to the SQL
Reference, SC41-3612 book for more information.
|
|
|
|
|
|
|
|
|
|
DFTRDBCOL
Specifies the collection name used for the unqualified names of tables, views,
indexes, and SQL packages. This parameter applies only to static SQL
statements.
|
|
collection-name: Specify the name of the collection identifier. This value is used
instead of the naming convention that is specified on the OPTION parameter.
|
|
|
|
SQLPKG
Specifies the qualified name of the SQL package created on the relational
database specified on the RDB parameter of this command.
The possible library values are:
*OBJLIB: The package is created in the library with the same name as the
library specified on the OBJ parameter.
library-name: Specify the name of the library where the package is created.
|
|
*OBJ: The name of the SQL package is the same as the object name specified
on the OBJ parameter.
|
|
package-name: Specify the name of the SQL package. If the remote system is not
an AS/400 system, no more than 8 characters can be specified.
|
|
|
|
|
|
|
|
|
SAAFLAG
Specifies the IBM SQL flagging function. This parameter flags SQL statements
to verify whether they conform to IBM SQL syntax More information about
which IBM database products IBM SQL syntax is in the DRDA IBM SQL
Reference, SC26-3255-00.
*NOFLAG: The precompiler does not check to see whether SQL statements
conform to IBM SQL syntax.
547
CRTSQLCPPI
*FLAG: The precompiler checks to see whether SQL statements conform to
IBM SQL syntax.
|
|
FLAGSTD
Specifies the American National Standards Institute (ANSI) flagging function.
This parameter flags SQL statements to verify whether they conform to the
following standards.
|
|
|
|
|
|
|
|
|
*NONE: The precompiler does not check to see whether SQL statements
conform to ANSI standards.
|
|
|
|
|
DBGVIEW
This parameter specifies the type of source debug information to be provided
by the SQL precompiler.
|
|
|
*SOURCE: The SQL precompiler provides the source views for the root and if
necessary, SQL INCLUDE statements. A view is provided that contains the
statements generated by the precompiler.
|
|
|
|
|
USRPRF
Specifies the user profile that is used when the compiled program object is run,
including the authority that the program object has for each object in static
SQL statements. The profile of either the program owner or the program user
is used to control which objects can be used by the program object.
|
|
|
*USER: The profile of the user running the program object is used.
|
|
*OWNER: The user profiles of both the program owner and the program user
are used when the program is run.
DYNUSRPRF
Specifies the user profile to be used for dynamic SQL statements.
|
|
|
|
|
*USER: Local dynamic SQL statements are run under the profile of the
programs user. Distributed dynamic SQL statements are run under the profile
of the SQL packages user.
|
|
|
*OWNER: Local dynamic SQL statements are run under the profile of the
programs owner. Distributed dynamic SQL statements are run under the
profile of the SQL packages owner.
|
|
|
SRTSEQ
Specifies the sort sequence table to be used for string comparisons in SQL
statements.
548
CRTSQLCPPI
|
|
|
*JOB: The SRTSEQ value for the job is retrieved during the precompile.
|
|
|
*JOBRUN: The SRTSEQ value for the job is retrieved when the program is
run. For distributed applications, SRTSEQ(*JOBRUN) is valid only when
LANGID(*JOBRUN) is also specified.
|
|
*HEX: A sort sequence table is not used. The hexadecimal values of the
characters are used to determine the sort sequence.
|
|
|
*LANGIDSHR: The sort sequence table uses the same weight for multiple
characters, and is the shared-weight sort sequence table associated with the
language specified on the LANGID parameter.
|
|
*LANGIDUNQ: The unique-weight sort table for the language that is specified
on the LANGID parameter is used.
|
|
The name of the table name can be qualified by one of the following library
values:
|
|
|
|
|
|
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of hte library to be searched.
table-name: Specify the name of the sort sequence table to be used.
|
|
|
LANGID
Specifies the language identifier to be used when SRTSEQ(*LANGIDUNQ) or
SRTSEQ(*LANGIDSHR) is specified.
*JOB: The LANGID value for the job is retrieved during the precompile.
|
|
|
*JOBRUN: The LANGID value for the job is retrieved when the program is
run. For distributed applications, LANGID(*JOBRUN) is valid only when
SRTSEQ(*JOBRUN) is also specified.
|
|
OUTPUT
Specifies whether the precompiler listing is generated.
|
|
|
|
PRTFILE
Specifies the qualified name of the printer device file to which the precompiler
printout is directed. The file must have a minimum length of 132 bytes. If a file
with a record length of less than 132 bytes is specified, information is lost.
|
|
The name of the printer file can be qualified by one of the following library
values:
549
CRTSQLCPPI
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
|
|
|
|
|
|
|
|
|
printer-file-name: Specify the name of the printer device file to which the
precompiler printout is directed.
TOSRCFILE
Specifies the qualified name of the source file that is to contain the output
source member that has been processed by the SQL precompiler. If the
specified source file is not found, it will be created. The output member will
have the same name as the name that is specified for the SRCMBR parameter.
|
|
|
|
|
|
|
|
|
source-file-name: Specify the name of the source file to contain the output source
member.
|
|
|
|
|
|
|
TEXT
Specifies the text that briefly describes the program and the function. More
information on this parameter is in Appendix A, Expanded Parameter
Descriptions in the CL Reference book.
|
|
|
|
|
|
|
|
|
|
*SRCMBRTXT: The text is taken from the source file member being used to
create the C++ program. You can add or change text for a database source
member by using the Start Source Entry Utility (STRSEU) command. You can
also use either the Add Physical File Member (ADDPFM) command or the
Change Physical File Member (CHGPFM) command. If the source file is an
inline file or a device file, the text is blank.
|
|
Example
|
|
550
CRTSQLCPPI
|
|
|
This command runs the SQL precompiler which precompiles the source and stores
the changed source in member PAYROLL in file QSQLTEMP in library QTEMP.
The command calls the ILE C++ compiler to create module PAYROLL in the
current library by using the source member that is created by the SQL precompiler.
Pgm: B,I
REXX: B,I
Exec
*CURLIB/
CRTSQLPLI
PGM(
program-name )
library-name/
*LIBL/
QPLISRC
source-file-name
SRCFILE(
*CURLIB/
library-name/
(1)
SRCMBR(
*PGM
source-file-member-name
OPTION(
Option Details
*CURRENT
*PRV
VxRxMx
TGTRLS(
*LIBL/
*SRCFILE
source-file-name
INCFILE(
*CURLIB/
library-name/
COMMIT(
*UR
*CHG
*ALL
*RS
*CS
*NONE
*NC
*RR
CLOSQLCSR(
)
*ENDPGM
*ENDSQL
*ENDJOB
ALWCPYDTA(
*YES
*OPTIMIZE
*NO
ALWBLK(
*READ
*NONE
*ALLREAD
551
CRTSQLPLI
*NO
*YES
DLYPRP(
GENLVL(
10
severity-level
*SRCFILE
left-right
MARGINS(
*JOB
*USA
*ISO
*EUR
*JIS
*MDY
*DMY
*YMD
*JUL
DATFMT(
*JOB
'/'
'.'
','
'-'
' '
*BLANK
DATSEP(
*HMS
*USA
*ISO
*EUR
*JIS
TIMFMT(
*JOB
':'
'.'
','
' '
*BLANK
TIMSEP(
*YES
*NO
REPLACE(
RDB(
*LOCAL
relational-database-name
*NONE
USER(
*CURRENT
user-name
PASSWORD(
*NONE
password
*DUW
*RUW
RDBCNNMTH(
DFTRDBCOL(
*NONE
collection-name
*PGMLIB/
*PGM
package-name
SQLPKG(
library-name/
SAAFLAG(
552
*NOFLAG
*FLAG
FLAGSTD(
*NONE
*ANS
CRTSQLPLI
*LIBL/
QSYSPRT
printer-file-name
PRTFILE(
*CURLIB/
library-name/
*JOB
*JOBRUN
*LANGIDUNQ
*LANGIDSHR
*HEX
*LIBL/
SRTSEQ(
table-name
*CURLIB/
library-name/
*JOB
*JOBRUN
language-ID
LANGID(
USRPRF(
*NAMING
*OWNER
*USER
DYNUSRPRF(
*USER
*OWNER
QTEMP/
QSQLTEMP
source-file-name
TOSRCFILE(
*LIBL/
*CURLIB/
library-name/
TEXT(
*SCRMBRTXT
*BLANK
'description'
Option Details
*NOSRC
*NOSOURCE
*NOXREF
*GEN
*JOB
*SYS
*XREF
*NOGEN
*PERIOD
*SYSVAL
*COMMA
*SQL
*SRC
*SOURCE
*NOSECLVL
)
*SECLVL
Notes:
1. All parameters preceding this point can be specified in positional form.
553
CRTSQLPLI
Purpose
The Create Structured Query Language PL/I (CRTSQLPLI) command calls a
Structured Query Language (SQL) precompiler, which precompiles PL/I source
containing SQL statements, produces a temporary source member, and optionally
calls the PL/I compiler to compile the program.
Parameters
PGM
Specifies the qualified name of the compiled program.
The name of the compiled PL/I program can be qualified by one of the
following library values:
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library where the compiled PL/I
program is created.
program-name: Specify the name of the compiled program.
SRCFILE
Specifies the qualified name of the source file that contains the PL/I source
with SQL statements.
The name of the source file can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
QPLISRC: If the source file name is not specified, the IBM-supplied source file
QPLISRC contains the PL/I source.
source-file-name: Specify the name of the source file that contains the PL/I
source.
SRCMBR
Specifies the name of the source file member that contains the PL/I source.
This parameter is specified only if the source file name in the SRCFILE
parameter is a database file. If this parameter is not specified, the PGM name
specified on the PGM parameter is used.
*PGM: Specifies that the PL/I source is in the member of the source file that
has the same name as that specified on the PGM parameter.
source-file-member-name: Specify the name of the member that contains the PL/I
source.
OPTION
Specifies whether one or more of the following options are used when the
PL/I source is precompiled. If an option is specified more than once, or if two
options conflict, the last option specified is used.
554
CRTSQLPLI
Element 1: Source Listing Options
*NOSOURCE: or *NOSRC: A source printout is not produced by the
precompiler unless errors are detected during precompile or create package.
*SOURCE or *SRC: The precompiler produces a source printout consisting of
PL/I source input.
Element 2: Cross-Reference Options
*NOXREF: The precompiler does not cross-reference names.
*XREF: The precompiler cross-references items in the program to the statement
numbers in the program that refer to those items.
Element 3: Program Creation Options
*GEN: The compiler creates a program that can run after the program is
compiled. An SQL package object is created if a relational database name is
specified on the RDB parameter.
*NOGEN: The precompiler does not call the C compiler, and a program and
SQL package are not created.
Element 4: Decimal Point Options
*JOB: The value used as the decimal point for numeric constants in SQL is the
representation of decimal point specified for the job at precompile time.
*PERIOD: The value used as the decimal point for numeric constants used in
SQL statements is a period.
*SYSVAL: The value used as the decimal point for numeric constants in SQL
statements is the QDECFMT system value.
Note: If QDECFMT specifies that the value used as the decimal point is a
comma, any numeric constants in lists (such as in the SELECT clause or
the VALUES clause) must be separated by a comma followed by a
blank. For example, VALUES(1,1, 2,23, 4,1) is equivalent to
VALUES(1.1,2.23,4.1) in which the decimal point is a period.
*COMMA: The value used as the decimal point for numeric constants in SQL
statements is a comma.
Note: Any numeric constants in lists (such as in the SELECT clause or the
VALUES clause) must be separated by a comma followed by a blank.
For example, VALUES(1,1, 2,23, 4,1) is equivalent to
VALUES(1.1,2.23,4.1) where the decimal point is a period.
Element 5: Naming Convention Options
*SYS: The system naming convention (library-name/file-name) is used.
*SQL: The SQL naming convention is used (collection-name.table-name). When
creating a program on a remote database other than an AS/400 system, *SQL
must be specified as the naming convention.
Appendix D. DB2 for AS/400 CL Command Descriptions
555
CRTSQLPLI
Element 6: Second-Level Message Text Option
*NOSECLVL: Second-level text descriptions are not added to the listing.
*SECLVL: Second-level text with replacement data is added to the printout for
all messages on the listing.
TGTRLS
Specifies the release of the operating system on which the user intends to use
the object being created.
In the examples given for the *CURRENT and *PRV values, and when
specifying the release-level value, the format VxRxMx is used to specify the
release, where Vx is the version, Rx is the release, and Mx is the modification
level. For example, V2R3M0 is version 2, release 3, modification level 0.
*CURRENT: The object is to be used on the release of the operating system
currently running on the users system. For example, if V2R3M5 is running on
the system, *CURRENT means the user intends to use the object on a system
with V2R3M5 installed. The user can also use the object on a system with any
subsequent release of the operating system installed.
Note: If V2R3M5 is running on the system, and the object is to be used on a
system with V2R3M0 installed, specify TGTRLS(V2R3M0) not
TGTRLS(*CURRENT).
*PRV: The object is to be used on the previous release with modification level 0
of the operating system. For example, if V2R3M5 is running on the users
system, *PRV means the user intends to use the object on a system with
V2R2M0 installed. The user can also use the object on a system with any
subsequent release of the operating system installed.
release-level: Specify the release in the format VxRxMx. The object can be used
on a system with the specified release or with any subsequent release of the
operating system installed.
Valid values depend on the current version, release, and modification level,
and they change with each new release. If you specify a release-level which is
earlier than the earliest release level supported by this command, an error
message is sent indicating the earliest supported release.
INCFILE
Specifies the qualified name of the source file that contains members included
in the program with any SQL INCLUDE statement.
The name of the source file can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
*SRCFILE: The qualified source file specified in the SRCFILE parameter
contains the source file members specified on any SQL INCLUDE statement.
556
CRTSQLPLI
source-file-name: Specify the name of the source file that contains the source file
members specified on any SQL INCLUDE statement. The record length of the
source file specified must be no less than the record length of the source file
specified for the SRCFILE parameter.
COMMIT
Specifies whether SQL statements in the compiled program are run under
commitment control. Files referred to in the host language source are not
affected by this option. Only SQL tables, SQL views, and SQL packages
referred to in SQL statements are affected.
*CHG or *UR: Specifies the objects referred to in SQL ALTER, CALL,
COMMENT ON, CREATE, DROP, GRANT, LABEL ON, RENAME, and
REVOKE statements and the rows updated, deleted, and inserted are locked
until the end of the unit of work (transaction). Uncommitted changes in other
jobs can be seen.
*ALL or *RS: Specifies the objects referred to in SQL ALTER, CALL,
COMMENT ON, CREATE, DROP, GRANT, LABEL ON, RENAME, and
REVOKE statements and the rows selected, updated, deleted, and inserted are
locked until the end of the unit of work (transaction). Uncommitted changes in
other jobs cannot be seen.
*CS: Specifies the objects referred to in SQL ALTER, CALL, COMMENT ON,
CREATE, DROP, GRANT, LABEL ON, RENAME, and REVOKE statements and
the rows updated, deleted, and inserted are locked until the end of the unit of
work (transaction). A row that is selected, but not updated, is locked until the
next row is selected. Uncommitted changes in other jobs cannot be seen.
*NONE or *NC: Specifies that commitment control is not used. Uncommitted
changes in other jobs can be seen. If the SQL DROP COLLECTION statement
is included in the program, *NONE or *NC must be used. If a relational
database is specified on the RDB parameter and the relational database is on a
system that is not on an AS/400, *NONE or *NC cannot be specified.
*RR: Specifies the objects referred to in SQL ALTER, CALL, COMMENT ON,
CREATE, DROP, GRANT, LABEL ON, RENAME, and REVOKE statements and
the rows selected, updated, deleted, and inserted are locked until the end of
the unit of work (transaction). Uncommitted changes in other jobs cannot be
seen. All tables referred to in SELECT, UPDATE, DELETE, and INSERT
statements are locked exclusively until the end of the unit of work
(transaction).
CLOSQLCSR
Specifies when SQL cursors are implicitly closed, SQL prepared statements are
implicitly discarded, and LOCK TABLE locks are released. SQL cursors are
explicitly closed when you issue the CLOSE, COMMIT, or ROLLBACK
(without HOLD) SQL statements.
*ENDPGM: SQL cursors are closed and SQL prepared statements are
discarded when the program ends. LOCK TABLE locks are released when the
first SQL program on the call stack ends.
*ENDSQL: SQL cursors remain open between calls and can be fetched without
running another SQL OPEN. One of the programs higher on the call stack
must have run at least one SQL statement. SQL cursors are closed, SQL
prepared statements are discarded, and LOCK TABLE locks are released when
Appendix D. DB2 for AS/400 CL Command Descriptions
557
CRTSQLPLI
the first SQL program on the call stack ends. If *ENDSQL is specified for a
program that is the first SQL program called (the first SQL program on the call
stack), the program is treated as if *ENDPGM was specified.
*ENDJOB: SQL cursors remain open between calls and can be fetched without
running another SQL OPEN. The programs higher on the call stack do not
need to have run SQL statements. SQL cursors are left open, SQL prepared
statements are preserved, and LOCK TABLE locks are held when the first SQL
program on the call stack ends. SQL cursors are closed, SQL prepared
statements are discarded, and LOCK TABLE locks are released when the job
ends.
ALWCPYDTA
Specifies whether a copy of the data can be used in a SELECT statement.
*YES: A copy of the data is used only when necessary.
*OPTIMIZE: The system determines whether to use the data retrieved directly
from the database or to use a copy of the data. The decision is based on which
method provides the best performance. If COMMIT is *CHG or *CS and
ALWBLK is not *ALLREAD, or if COMMIT is *ALL or *RR, then a copy of the
data is used only when it is necessary to run a query.
*NO: A copy of the data is not allowed. If a temporary copy of the data is
required to perform the query, an error message is returned.
ALWBLK
Specifies whether the database manager can use record blocking, and the
extent to which blocking can be used for read-only cursors.
*READ: Records are blocked for read-only retrieval of data for cursors when:
v *NONE is specified on the COMMIT parameter, which indicates that
commitment control is not used.
v The cursor is declared with a FOR READ ONLY clause or there are no
dynamic statements that could run a positioned UPDATE or DELETE
statement for the cursor.
Specifying *READ can improve the overall performance of queries that meet
the above conditions and retrieve a large number of records.
*NONE: Rows are not blocked for retrieval of data for cursors.
Specifying *NONE:
v Guarantees that the data retrieved is current.
v May reduce the amount of time required to retrieve the first row of data for
a query.
v Stops the database manager from retrieving a block of data rows that is not
used by the program when only the first few rows of a query are retrieved
before the query is closed.
v Can degrade the overall performance of a query that retrieves a large
number of rows.
*ALLREAD: Rows are blocked for read-only cursors if *NONE or *CHG is
specified on the COMMIT parameter. All cursors in a program that are not
558
CRTSQLPLI
explicitly able to be updated are opened for read-only processing even though
EXECUTE or EXECUTE IMMEDIATE statements may be in the program.
Specifying *ALLREAD:
v Allows record blocking under commitment control level *CHG in addition to
the blocking allowed for *READ.
v Can improve the performance of almost all read-only cursors in programs,
but limits queries in the following ways:
The Rollback (ROLLBACK) command, a ROLLBACK statement in host
languages, or the ROLLBACK HOLD SQL statement does not reposition a
read-only cursor when *ALLREAD is specified.
Dynamic running of a positioned UPDATE or DELETE statement (for
example, using EXECUTE IMMEDIATE), cannot be used to update a row
in a cursor unless the DECLARE statement for the cursor includes the
FOR UPDATE clause.
DLYPRP
Specifies whether the dynamic statement validation for a PREPARE statement
is delayed until an OPEN, EXECUTE, or DESCRIBE statement is run. Delaying
validation improves performance by eliminating redundant validation.
*NO: Dynamic statement validation is not delayed. When the dynamic
statement is prepared, the access plan is validated. When the dynamic
statement is used in an OPEN or EXECUTE statement, the access plan is
revalidated. Because the authority or the existence of objects referred to by the
dynamic statement may change, you must still check the SQLCODE or
SQLSTATE after issuing the OPEN or EXECUTE statement to ensure that the
dynamic statement is still valid.
*YES: Dynamic statement validation is delayed until the dynamic statement is
used in an OPEN, EXECUTE, or DESCRIBE SQL statement. When the dynamic
statement is used, the validation is completed and an access plan is built. If
you specify *YES on this parameter, you should check the SQLCODE and
SQLSTATE after running an OPEN, EXECUTE, or DESCRIBE statement to
ensure that the dynamic statement is valid.
Note: If you specify *YES, performance is not improved if the INTO clause is
used on the PREPARE statement or if a DESCRIBE statement uses the
dynamic statement before an OPEN is issued for the statement.
GENLVL
Specifies the severity level at which the create operation fails. If errors occur
that have a severity level greater than or equal to this value, the operation
ends.
10: The default severity level is 10.
severity-level: Specify a value ranging from 0 through 40.
MARGINS
Specifies the part of the precompiler input record that contains source text.
*SRCFILE: The file member margin values specified by the user on the
SRCMBR parameter are used. If the member is a SQLPLI source type, the
559
CRTSQLPLI
margin values are the values specified on the SEU services display. If the
member is a different source type, the margin values are the default values of 2
and 72.
Element 1: Left Margin
left: Specify the beginning position for the statements. Valid values range from
1 through 80.
Element 2: Right Margin
right: Specify the ending position for the statements. Valid values range from 1
through 80.
DATFMT
Specifies the format used when accessing date result columns. All output date
fields are returned in the specified format. For input date strings, the specified
value is used to determine whether the date is specified in a valid format.
Note: An input date string that uses the format *USA, *ISO, *EUR, or *JIS is
always valid.
If a relational database is specified on the RDB parameter and the
database is on a system that is not an AS/400 system, then *USA, *ISO,
*EUR, or *JIS must be specified.
*JOB: The format specified for the job is used. Use the Display Job (DSPJOB)
command to determine the current date format for the job.
*USA: The United States date format (mm/dd/yyyy) is used.
*ISO: The International Organization for Standardization (ISO) date format
(yyyy-mm-dd) is used.
*EUR: The European date format (dd.mm.yyyy) is used.
*JIS: The Japanese Industrial Standard date format (yyyy-mm-dd) is used.
*MDY: The date format (mm/dd/yy) is used.
*DMY: The date format (dd/mm/yy) is used.
*YMD: The date format (yy/mm/dd) is used.
*JUL: The Julian date format (yy/ddd) is used.
DATSEP
Specifies the separator used when accessing date result columns.
Note: This parameter applies only when *JOB, *MDY, *DMY, *YMD, or *JUL is
specified on the DATFMT parameter.
*JOB: The date separator specified for the job at precompile time is used. Use
the Display Job (DSPJOB) command to determine the current value for the job.
/: A slash (/) is used.
560
CRTSQLPLI
.: A period (.) is used.
,: A comma (,) is used.
-: A dash (-) is used.
: A blank ( ) is used.
*BLANK: A blank ( ) is used.
TIMFMT
Specifies the format used when accessing time result columns. For input time
strings, the specified value is used to determine whether the time is specified
in a valid format.
Note: An input date string that uses the format *USA, *ISO, *EUR, or *JIS is
always valid.
If a relational database is specified on the RDB parameter and the
database is on a system that is not another AS/400 system, the time
format must be *USA, *ISO, *EUR, *JIS, or *HMS with a time separator
of colon or period.
*HMS: The (hh:mm:ss) format is used.
*USA: The United States time format (hh:mm xx) is used, where xx is AM or
PM.
*ISO: The International Organization for Standardization (ISO) time format
(hh.mm.ss) is used.
*EUR: The European time format (hh.mm.ss) is used.
*JIS: The Japanese Industrial Standard time format (hh:mm:ss) is used.
TIMSEP
Specifies the separator used when accessing time result columns.
Note: This parameter applies only when *HMS is specified on the TIMFMT
parameter.
*JOB: The time separator specified for the job at precompile time is used. Use
the Display Job (DSPJOB) command to determine the current value for the job.
:: A colon (:) is used.
.: A period (.) is used.
,: A comma (,) is used.
: A blank ( ) is used.
*BLANK: A blank ( ) is used.
REPLACE
Specifies whether a new program or SQL package is created when a program
or SQL package of the same name exists in the same library. The value of this
Appendix D. DB2 for AS/400 CL Command Descriptions
561
CRTSQLPLI
parameter is passed to the CRTPLIPGM command. More information on this
parameter is in Appendix A, Expanded Parameter Descriptions in the CL
Reference (Abridged) book.
*YES: A new program or SQL package is created, and any existing program or
SQL package of the same name and type in the specified library is moved to
QRPLOBJ.
*NO: A new program or SQL package is not created if an object of the same
name and type already exists in the specified library.
RDB
Specifies the name of the relational database where the SQL package object is
created.
*LOCAL: The program is created as a distributed SQL program. The SQL
statements will access the local database. An SQL package object is not created
as part of the precompile process. The Create Structured Query Language
Package (CRTSQLPKG) command can be used.
relational-database-name: Specify the name of the relational database where the
new SQL package object is to be created. When the name of the local relational
database is specified, the program created is still a distributed SQL program.
The SQL statements will access the local database.
*NONE: An SQL package object is not created. The program object is not a
distributed program and the Create Structured Query Language Package
(CRTSQLPKG) command cannot be used.
USER
Specifies the user name sent to the remote system when starting the
conversation. This parameter is valid only when RDB is specified.
*CURRENT: The user profile under which the current job is running is used.
user-name: Specify the user name being used for the application server job.
PASSWORD
Specifies the password to be used on the remote system. This parameter is
valid only if RDB is specified.
*NONE: No password is sent. If this value is specified, USER(*CURRENT)
must also be specified.
password: Specify the password of the user name specified on the USER
parameter.
RDBCNNMTH
Specifies the semantics used for CONNECT statements. Refer to the SQL
Reference book for more information.
*DUW: CONNECT (Type 2) semantics are used to support distributed unit of
work. Consecutive CONNECT statements to additional relational databases do
not result in disconnection of previous connections.
*RUW: CONNECT (Type 1) semantics are used to support remote unit of
work. Consecutive CONNECT statements result in the previous connection
being disconnected before a new connection is established.
562
CRTSQLPLI
DFTRDBCOL
Specifies the collection name used for the unqualified names of tables, views,
indexes, and SQL packages. This parameter applies only to static SQL
statements.
*NONE: The naming convention defined on the OPTION parameter is used.
collection-name: Specify the name of the collection identifier. This value is used
instead of the naming convention specified on the OPTION parameter.
SQLPKG
Specifies the qualified name of the SQL package created on the relational
database specified on the RDB parameter of this command.
The possible library values are:
*PGMLIB: The package is created in the library with the same name as the
library containing the program.
library-name: Specify the name of the library where the package is created.
*PGM: The package name is the same as the program name.
package-name: Specify the name of the package created on the remote database
specified on the RDBNAME parameter.
SAAFLAG
Specifies the IBM SQL flagging function. This parameter flags SQL statements
to verify whether they conform to IBM SQL syntax More information about
which IBM database products IBM SQL syntax is in the DRDA IBM SQL
Reference, SC26-3255-00.
*NOFLAG: The precompiler does not check to see whether SQL statements
conform to IBM SQL syntax.
*FLAG: The precompiler checks to see whether SQL statements conform to
IBM SQL syntax.
FLAGSTD
Specifies the American National Standards Institute (ANSI) flagging function.
This parameter flags SQL statements to verify whether they conform to the
following standards.
ANSI X3.135-1992 entry
ISO 9075-1992 entry
FIPS 127.2 entry
*NONE: The precompiler does not check to see whether SQL statements
conform to ANSI standards.
*ANS: The precompiler checks to see whether SQL statements conform to
ANSI standards.
563
CRTSQLPLI
PRTFILE
Specifies the qualified name of the printer device file to which the listing is
directed. The file must have a minimum record length of 132 bytes or
information is lost.
The name of the printer file can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
QSYSPRT: If a file name is not specified, the precompiler printout is directed
to the IBM-supplied printer file QSYSPRT.
printer-file-name: Specify the name of the printer device file to which the
precompiler printout is directed.
SRTSEQ
Specifies the sort sequence table to be used for string comparisons in SQL
statements.
Note: *HEX must be specified for this parameter on distributed applications
where the application server is not on an AS/400 system or the release
level is prior to V2R3M0.
*JOB: The SRTSEQ value for the job is retrieved during the precompile.
*JOBRUN: The SRTSEQ value for the job is retrieved when the program is
run. For distributed applications, SRTSEQ(*JOBRUN) is valid only when
LANGID(*JOBRUN) is also specified.
*LANGIDUNQ: The unique-weight sort table for the language specified on the
LANGID parameter is used.
*LANGIDSHR: The shared-weight sort table for the language specified on the
LANGID parameter is used.
*HEX: A sort sequence table is not used. The hexadecimal values of the
characters are used to determine the sort sequence.
The name of the sort sequence table can be qualified by one of hte following
library values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
table-name: Specify the name of the sort sequence table to be used.
LANGID
Specifies the language identifier to be used when SRTSEQ(*LANGIDUNQ) or
SRTSEQ(*LANGIDSHR) is specified.
564
CRTSQLPLI
*JOB: The LANGID value for the job is retrieved during the precompile.
*JOBRUN: The LANGID value for the job is retrieved when the program is
run. For distributed applications, LANGID(*JOBRUN) is valid only when
SRTSEQ(*JOBRUN) is also specified.
language-id: Specify a language identifier to be used by the program.
USRPRF
Specifies the user profile that is used when the compiled program object is run,
including the authority that the program object has for each object in static
SQL statements. The profile of either the program owner or the program user
is used to control which objects can be used by the program object.
*NAMING: The user profile is determined by the naming convention. If the
naming convention is *SQL, USRPRF(*OWNER) is used. If the naming
convention is *SYS, USRPRF(*USER) is used.
*USER: The profile of the user running the program object is used.
*OWNER: The user profiles of both the program owner and the program user
are used when the program is run.
DYNUSRPRF
Specifies the user profile used for dynamic SQL statements.
*USER: Local dynamic SQL statements are run under the user profile of the
job. Distributed dynamic SQL statements are run under the user profile of the
application server job.
*OWNER: Local dynamic SQL statements are run under the user profile of the
programs owner. Distributed dynamic SQL statements are run under the user
profile of the SQL packages owner.
|
|
|
|
|
|
TOSRCFILE
Specifies the qualified name of the source file that is to contain the output
source member that has been processed by the SQL precompiler. If the
specified source file is not found, it will be created. The output member will
have the same name as the name that is specified for the SRCMBR parameter.
The possible library values are:
|
|
|
|
library-name: Specify the name of the library that is to contain the output
source file.
|
|
|
|
source-file-name: Specify the name of the source file to contain the output source
member.
TEXT
Specifies the text that briefly describes the program and its function. More
Appendix D. DB2 for AS/400 CL Command Descriptions
565
CRTSQLPLI
information on this parameter is in Appendix A, Expanded Parameter
Descriptions in the CL Reference (Abridged)book.
*SCRMBRTXT: The text is taken from the source file member being used to
create the PL/I program. The user can add or change text for a database
source member by using the Start Source Entry Utility (STRSEU) command, or
by using either the Add Physical File Member (ADDPFM) or Change Physical
File Member (CHGPFM) command. If the source file is an inline file or a
device file, the text is blank.
*BLANK: Text is not specified.
description: Specify no more than 50 characters of text, enclosed in
apostrophes.
Example
CRTSQLPLI
PAYROLL
TEXT('Payroll Program')
This command runs the SQL precompiler, which precompiles the source and stores
the changed source in member PAYROLL in file QSQLTEMP in library QTEMP.
The PL/I compiler is called to create program PAYROLL in the current library
using the source member created by the SQL precompiler.
Pgm: B,I
REXX: B,I
Exec
*CURLIB/
CRTSQLRPG
PGM(
program-name )
library-name/
*LIBL/
QRPGSRC
source-file-name
SRCFILE(
*CURLIB/
library-name/
(1)
SRCMBR(
*PGM
source-file-member-name
OPTION(
OPTION DETAILS
)
TGTRLS(
*CURRENT
*PRV
VxRxMx
*LIBL/
INCFILE(
*CURLIB/
library-name/
566
*SRCFILE
source-file-name
CRTSQLRPG
*UR
*CHG
*ALL
*RS
*CS
*NONE
*NC
*RR
COMMIT(
CLOSQLCSR(
)
*ENDPGM
*ENDSQL
*ENDJOB
ALWCPYDTA(
*YES
*OPTIMIZE
*NO
ALWBLK(
*READ
*NONE
*ALLREAD
*NO
*YES
DLYPRP(
10
severity-level
GENLVL(
*JOB
*USA
*ISO
*EUR
*JIS
*MDY
*DMY
*YMD
*JUL
DATFMT(
*JOB
'/'
'.'
','
'-'
' '
*BLANK
DATSEP(
*HMS
*USA
*ISO
*EUR
*JIS
TIMFMT(
*JOB
':'
'.'
','
' '
*BLANK
TIMSEP(
*YES
*NO
REPLACE(
RDB(
*LOCAL
relational-database-name
*NONE
USER(
*CURRENT
user-name
PASSWORD(
*NONE
password
RDBCNNMTH(
*DUW
*RUW
567
CRTSQLRPG
*NONE
collection-name
DFTRDBCOL(
*PGMLIB/
*PGM
package-name
SQLPKG(
library-name/
*NOFLAG
*FLAG
SAAFLAG(
FLAGSTD(
*NONE
*ANS
*LIBL/
QSYSPRT
printer-file-name
PRTFILE(
*CURLIB/
library-name/
*JOB
*JOBRUN
*LANGIDUNQ
*LANGIDSHR
*HEX
*LIBL/
SRTSEQ(
table-name
*CURLIB/
library-name/
*JOB
*JOBRUN
language-ID
LANGID(
USRPRF(
*NAMING
*OWNER
*USER
DYNUSRPRF(
*USER
*OWNER
QTEMP/
QSQLTEMP
source-file-name
TOSRCFILE(
*LIBL/
*CURLIB/
library-name/
TEXT(
*SRCMBRTXT
*BLANK
'description'
OPTION Details
*NOSRC
*NOSOURCE
*NOXREF
*GEN
*JOB
*SYS
*XREF
*NOGEN
*SYSVAL
*PERIOD
*COMMA
*SQL
*SOURCE
*SRC
568
CRTSQLRPG
*NOSECLVL
*NOSEQSRC
*NOLSTDBG
*SECLVL
*SEQSRC
*LSTDBG
Notes:
1. All parameters preceding this point can be specified in positional form.
Purpose
The Create Structured Query Language RPG (CRTSQLRPG) command calls the
Structured Query Language (SQL) precompiler which precompiles the RPG source
containing the SQL statements, produces a temporary source member, and then
optionally calls the RPG compiler to compile the program.
Parameters
PGM
Specifies the qualified name of the compiled program.
The name of the compiled RPG can be qualified by one of the following library
values:
*CURLIB: The compiled RPG program is created in the current library for
the job. If no library is specified as the current library for the job, the QGPL
library is used.
library-name: Specify the name of hte library where the compiled RPG
program is created.
program-name: Specify the name of the compiled program.
SRCFILE
Specifies the qualified name of the source file that contains the RPG source
with SQL statements.
The name of the source file can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
QRPGSRC: If the source file name is not specified, the IBM-supplied source
file QRPGSRC contains the RPG source.
source-file-name: Specify the name of the source file that contains the RPG
source.
SRCMBR
Specifies the name of hte source file member that contains the RPG source.
This parameter is specified only if the source file name in the SRCFILE
parameter is a database file. If this parameter is not specified, the PGM name
specified on the PGM parameter is used.
*PGM: Specifies that the RPG source is in the member of the source file that
has the same name as that specified on the PGM parameter.
Appendix D. DB2 for AS/400 CL Command Descriptions
569
CRTSQLRPG
source-file-member-name: Specify the name of the member that contains the RPG
source.
OPTION
Specifies whether one or more of the following options are used when the RPG
source is precompiled. If an option is specified more than once, or if two
options conflict, the last option specified is used.
Element 1: Source Listing Options
*NOSOURCE or *NOSRC: A source printout is not produced by the
precompiler unless errors are detected during precompile or create package.
*SOURCE or *SRC: The precompiler produces a source printout, consisting of
RPG source input.
Element 2: Cross-Reference Options
*NOXREF: The precompiler does not cross-reference names.
*XREF: The precompiler cross-references items in the program to the statement
numbers in the program that refer to those items.
Element 3: Program Creation Options
*GEN: The compiler creates a program that can run after the program is
compiled. An SQL package object is created if a relational database name is
specified on the RDB parameter.
*NOGEN: The precompiler does not call the RPG compiler, and a program
and SQL package are not created.
Element 4: Decimal Point Options
*JOB: The value used as the decimal point for numeric constants in SQL is the
representation of decimal point specified for the job at precompile time.
*SYSVAL: The value used as the decimal point for numeric constants in SQL
statements is the QDECFMT system value.
Note: If QDECFMT specifies that the value used as the decimal point is a
comma, any numeric constants in lists (such as in the SELECT clause,
VALUES clause, and so on.) must be separated by a comma followed by
a blank. For example, VALUES(1,1, 2,23, 4,1) is equivalent to
VALUES(1.1,2.23,4.1) where the decimal point is a period.
*PERIOD: The value used as the decimal point for numeric constants used in
SQL statements is a period.
*COMMA: The value used as the decimal point for numeric constants in SQL
statements is a comma.
Note: Any numeric constants in lists (such as in the SELECT clause, VALUES
clause, and so on.) must be separated by a comma followed by a blank.
For example, VALUES(1,1, 2,23, 4,1) is equivalent to
VALUES(1.1,2.23,4.1) where the decimal point is a period.
570
CRTSQLRPG
Element 5: Naming Convention Options
*SYS: The system naming convention (library-name/file-name) is used.
*SQL: The SQL naming convention is used (collection-name.table-name). When
creating a program on a remote database other than an AS/400 system, *SQL
must be specified as the naming convention.
Element 6: Second-Level Message Text Option
*NOSECLVL: Second-level text descriptions are not added to the listing.
*SECLVL: Second-level text with replacement data is added for all messages
on the listing.
Element 7: Source Sequence Number Option
*NOSEQSRC: Source sequence numbers from the input source files are used
when creating the new source member in QSQLTEMP.
*SEQSRC: Source records written to the new source member in QSQLTEMP
are numbered starting at 000001.
Element 8: Debug Listing View Option
*NOLSTDBG: Error and debug information is not generated.
*LSTDBG: The SQL precompiler generates a listing view and error and debug
information required for this view. You can use *LSTDBG only if you are using
the CODE/400 product to compile your program.
TGTRLS
Specifies the release of the operating system on which the user intends to use
the object being created.
In the examples given for the *CURRENT and *PRV values, and when
specifying the release-level value, the format VxRxMx is used to specify the
release, where Vx is the version, Rx is the release, and Mx is the modification
level. For example, V2R3M0 is version 2, release 3, modification level 0.
*CURRENT: The object is to be used on the release of the operating system
currently running on the users system. For example, if V2R3M5 is running on
the system, *CURRENT means the user intends to use the object on a system
with V2R3M5 installed. The user can also use the object on a system with any
subsequent release of the operating system installed.
Note: If V2R3M5 is running on the system, and the object is to be used on a
system with V2R3M0 installed, specify TGTRLS(V2R3M0) not
TGTRLS(*CURRENT).
*PRV: The object is to be used on the previous release with modification level 0
of the operating system. For example, if V2R3M5 is running on the users
system, *PRV means the user intends to use the object on a system with
V2R2M0 installed. The user can also use the object on a system with any
subsequent release of the operating system installed.
571
CRTSQLRPG
release-level: Specify the release in the format VxRxMx. The object can be used
on a system with the specified release or with any subsequent release of the
operating system installed.
Valid values depend on the current version, release, and modification level,
and they change with each new release. If you specify a release-level which is
earlier than the earliest release level supported by this command, an error
message is sent indicating the earliest supported release.
INCFILE
Specifies the qualified name of the source file that contains members included
in the program with any SQL INCLUDE statement.
The name of the source file can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
*SRCFILE: The qualified source file specified in the SRCFILE parameter
contains the source file members specified on any SQL INCLUDE statement.
source-file-name: Specify the name of the source file that contains the source file
members specified on any SQL INCLUDE statement. The record length of the
source file specified here must be no less than the record length of the source
file specified for the SRCFILE parameter.
COMMIT
Specifies whether SQL statements in the compiled program are run under
commitment control. Files referred to in the host language source are not
affected by this option. Only SQL tables, SQL views, and SQL packages
referred to in SQL statements are affected.
Note: Files referenced in the RPG source are not affected by this option.
*CHG or *UR: Specifies the objects referred to in SQL ALTER, CALL,
COMMENT ON, CREATE, DROP, GRANT, LABEL ON, RENAME, and
REVOKE statements and the rows updated, deleted, and inserted are locked
until the end of the unit of work (transaction). Uncommitted changes in other
jobs can be seen.
*ALL or *RS: Specifies the objects referred to in SQL ALTER, CALL,
COMMENT ON, CREATE, DROP, GRANT, LABEL ON, RENAME, and
REVOKE statements and the rows selected, updated, deleted, and inserted are
locked until the end of the unit of work (transaction). Uncommitted changes in
other jobs cannot be seen.
*CS: Specifies the objects referred to in SQL ALTER, CALL, COMMENT ON,
CREATE, DROP, GRANT, LABEL ON, RENAME, and REVOKE statements and
the rows updated, deleted, and inserted are locked until the end of the unit of
work (transaction). A row that is selected, but not updated, is locked until the
next row is selected. Uncommitted changes in other jobs cannot be seen.
572
CRTSQLRPG
*NONE or *NC: Specifies that commitment control is not used. Uncommitted
changes in other jobs can be seen. If the SQL DROP COLLECTION statement
is included in the program, *NONE or *NC must be used. If a relational
database is specified on the RDB parameter and the relational database is on a
system that is not on an AS/400, *NONE or *NC cannot be specified.
*RR: Specifies the objects referred to in SQL ALTER, CALL, COMMENT ON,
CREATE, DROP, GRANT, LABEL ON, RENAME, and REVOKE statements and
the rows selected, updated, deleted, and inserted are locked until the end of
the unit of work (transaction). Uncommitted changes in other jobs cannot be
seen. All tables referred to in SELECT, UPDATE, DELETE, and INSERT
statements are locked exclusively until the end of the unit of work
(transaction).
CLOSQLCSR
Specifies when SQL cursors are implicitly closed, SQL prepared statements are
implicitly discarded, and LOCK TABLE locks are released. SQL cursors are
explicitly closed when you issue the CLOSE, COMMIT, or ROLLBACK
(without HOLD) SQL statements.
*ENDPGM: SQL cursors are closed and SQL prepared statements are
discarded when the program ends. LOCK TABLE locks are released when the
first SQL program on the call stack ends.
*ENDSQL: SQL cursors remain open between calls and can be fetched without
running another SQL OPEN. One of the programs higher on the call stack
must have run at least one SQL statement. SQL cursors are closed, SQL
prepared statements are discarded, and LOCK TABLE locks are released when
the first SQL program on the call stack ends. If *ENDSQL is specified for a
program that is the first SQL program called (the first SQL program on the call
stack), the program is treated as if *ENDPGM was specified.
*ENDJOB: SQL cursors remain open between calls and can be fetched without
running another SQL OPEN. The programs higher on the call stack do not
need to have run SQL statements. SQL cursors are left open, SQL prepared
statements are preserved, and LOCK TABLE locks are held when the first SQL
program on the call stack ends. SQL cursors are closed, SQL prepared
statements are discarded, and LOCK TABLE locks are released when the job
ends.
ALWCPYDTA
Specifies whether a copy of the data can be used in a SELECT statement.
*YES: A copy of the data is used only when necessary.
*OPTIMIZE: The system determines whether to use the data retrieved directly
from the database or to use a copy of the data. The decision is based on which
method provides the best performance. If COMMIT is *CHG or *CS and
ALWBLK is not *ALLREAD, or if COMMIT is *ALL or *RR, then a copy of the
data is used only when it is necessary to run a query.
*NO: A copy of the data is not allowed. If a temporary copy of the data is
required to perform the query, an error message is returned.
ALWBLK
Specifies whether the database manager can use record blocking, and the
extent to which blocking can be used for read-only cursors.
Appendix D. DB2 for AS/400 CL Command Descriptions
573
CRTSQLRPG
*READ: Records are blocked for read-only retrieval of data for cursors when:
v *NONE is specified on the COMMIT parameter, which indicates that
commitment control is not used.
v The cursor is declared with a FOR READ ONLY clause or there are no
dynamic statements that could run a positioned UPDATE or DELETE
statement for the cursor.
Specifying *READ can improve the overall performance of queries that meet
the above conditions and retrieve a large number of records.
*NONE: Rows are not blocked for retrieval of data for cursors.
Specifying *NONE:
v Guarantees that the data retrieved is current.
v May reduce the amount of time required to retrieve the first row of data for
a query.
v Stops the database manager from retrieving a block of data rows that is not
used by the program when only the first few rows of a query are retrieved
before the query is closed.
v Can degrade the overall performance of a query that retrieves a large
number of rows.
*ALLREAD: Rows are blocked for read-only cursors if *NONE or *CHG is
specified on the COMMIT parameter. All cursors in a program that are not
explicitly able to be updated are opened for read-only processing even though
EXECUTE or EXECUTE IMMEDIATE statements may be in the program.
Specifying *ALLREAD:
v Allows record blocking under commitment control level *CHG in addition to
the blocking allowed for *READ.
v Can improve the performance of almost all read-only cursors in programs,
but limits queries in the following ways:
The Rollback (ROLLBACK) command, a ROLLBACK statement in host
languages, or the ROLLBACK HOLD SQL statement does not reposition a
read-only cursor when *ALLREAD is specified.
Dynamic running of a positioned UPDATE or DELETE statement (for
example, using EXECUTE IMMEDIATE), cannot be used to update a row
in a cursor unless the DECLARE statement for the cursor includes the
FOR UPDATE clause.
DLYPRP
Specifies whether the dynamic statement validation for a PREPARE statement
is delayed until an OPEN, EXECUTE, or DESCRIBE statement is run. Delaying
validation improves performance by eliminating redundant validation.
*NO: Dynamic statement validation is not delayed. When the dynamic
statement is prepared, the access plan is validated. When the dynamic
statement is used in an OPEN or EXECUTE statement, the access plan is
revalidated. Because the authority or the existence of objects referred to by the
dynamic statement may change, you must still check the SQLCODE or
SQLSTATE after issuing the OPEN or EXECUTE statement to ensure that the
dynamic statement is still valid.
574
CRTSQLRPG
*YES: Dynamic statement validation is delayed until the dynamic statement is
used in an OPEN, EXECUTE, or DESCRIBE SQL statement. When the dynamic
statement is used, the validation is completed and an access plan is built. If
you specify *YES on this parameter, you should check the SQLCODE and
SQLSTATE after running an OPEN, EXECUTE, or DESCRIBE statement to
ensure that the dynamic statement is valid.
Note: If you specify *YES, performance is not improved if the INTO clause is
used on the PREPARE statement or if a DESCRIBE statement uses the
dynamic statement before an OPEN is issued for the statement.
GENLVL
Specifies the severity level at which the create operation fails. If errors occur
that have a severity level greater than or equal to this value, the operation
ends.
10: The default severity level is 10.
severity-level: Specify a value ranging from 0 through 40.
DATFMT
Specifies the format used when accessing date result columns. All output date
fields are returned in the specified format. For input date strings, the specified
value is used to determine whether the date is specified in a valid format.
Note: An input date string that uses the format *USA, *ISO, *EUR, or *JIS is
always valid.
If a relational database is specified on the RDB parameter and the
database is on a system that is not an AS/400 system, then *USA, *ISO,
*EUR, or *JIS must be specified.
*JOB: The format specified for the job is used. Use the Display Job (DSPJOB)
command to determine the current date format for the job.
*USA: The United States date format (mm/dd/yyyy) is used.
*ISO: The International Organization for Standardization (ISO) date format
(yyyy-mm-dd) is used.
*EUR: The European date format (dd.mm.yyyy) is used.
*JIS: The Japanese Industrial Standard date format (yyyy-mm-dd) is used.
*MDY: The date format (mm/dd/yy) is used.
*DMY: The date format (dd/mm/yy) is used.
*YMD: The date format (yy/mm/dd) is used.
*JUL: The Julian date format (yy/ddd) is used.
DATSEP
Specifies the separator used when accessing date result columns.
Note: This parameter applies only when *JOB, *MDY, *DMY, *YMD, or *JUL is
specified on the DATFMT parameter.
Appendix D. DB2 for AS/400 CL Command Descriptions
575
CRTSQLRPG
*JOB: The date separator specified for the job at precompile time is used. Use
the Display Job (DSPJOB) command to determine the current value for the job.
/: A slash (/) is used.
.: A period (.) is used.
,: A comma (,) is used.
-: A dash (-) is used.
: A blank ( ) is used.
*BLANK: A blank ( ) is used.
TIMFMT
Specifies the format used when accessing time result columns. For input time
strings, the specified value is used to determine whether the time is specified
in a valid format.
Note: An input date string that uses the format *USA, *ISO, *EUR, or *JIS is
always valid.
If a relational database is specified on the RDB parameter and the
database is on a system that is not another AS/400 system, the time
format must be *USA, *ISO, *EUR, *JIS, or *HMS with a time separator
of colon or period.
*HMS: The (hh:mm:ss) format is used.
*USA: The United States time format (hh:mm xx) is used, where xx is AM or
PM.
*ISO: The International Organization for Standardization (ISO) time format
(hh.mm.ss) is used.
*EUR: The European time format (hh.mm.ss) is used.
*JIS: The Japanese Industrial Standard time format (hh:mm:ss) is used.
TIMSEP
Specifies the separator used when accessing time result columns.
Note: This parameter applies only when *HMS is specified on the TIMFMT
parameter.
*JOB: The time separator specified for the job at precompile time is used. Use
the Display Job (DSPJOB) command to determine the current value for the job.
:: A colon (:) is used.
.: A period (.) is used.
,: A comma (,) is used.
: A blank ( ) is used.
576
CRTSQLRPG
*BLANK: A blank ( ) is used.
REPLACE
Specifies whether a new program or SQL package is created when a program
or SQL package of the same name exists in the same library. The value of this
parameter is passed to the C command.More information on this parameter is
in Appendix A, Expanded Parameter Descriptions in the CL Reference
(Abridged) book.
*YES: A new program or SQL package is created, and any existing program or
SQL package of the same name and type in the specified library is moved to
QRPLOBJ.
*NO: A new program or SQL package is not created if an object of the same
name and type already exists in the specified library.
RDB
Specifies the name of the relational database where the SQL package object is
created.
*LOCAL: The program is created as a distributed SQL program. The SQL
statements will access the local database. An SQL package object is not created
as part of the precompile process. The Create Structured Query Language
Package (CRTSQLPKG) command can be used.
relational-database-name: Specify the name of the relational database where the
new SQL package object is to be created. When the name of the local relational
database is specified, the program created is still a distributed SQL program.
The SQL statements will access the local database.
*NONE: An SQL package object is not created. The program object is not a
distributed program and the Create Structured Query Language Package
(CRTSQLPKG) command cannot be used.
USER
Specifies the user name sent to the remote system when starting the
conversation. This parameter is valid only when RDB is specified.
*CURRENT: The user profile under which the current job is running is used.
user-name: Specify the user name being used for the application requester job.
PASSWORD
Specifies the password to be used on the remote system. This parameter is
valid only if RDB is specified.
*NONE: No password is sent. If this value is specified, USER(*CURRENT)
must also be specified.
password: Specify the password of the user name specified on the USER
parameter.
RDBCNNMTH
Specifies the semantics used for CONNECT statements. Refer to the SQL
Reference, SC41-3612 book for more information.
577
CRTSQLRPG
*DUW: CONNECT (Type 2) semantics are used to support distributed unit of
work. Consecutive CONNECT statements to additional relational databases do
not result in disconnection of previous connections.
*RUW: CONNECT (Type 1) semantics are used to support remote unit of
work. Consecutive CONNECT statements result in the previous connection
being disconnected before a new connection is established.
DFTRDBCOL
Specifies the collection name used for the unqualified names of tables, views,
indexes, and SQL packages. This parameter applies only to static SQL
statements.
*NONE: The naming convention defined on the OPTION parameter is used.
collection-name: Specify the name of the collection identifier. This value is used
instead of the naming convention specified on the OPTION parameter.
SQLPKG
Specifies the qualified name of the SQL package created on the relational
database specified on the RDB parameter of this command.
The possible library values are:
*PGMLIB: The package is created in the library with the same name as the
library containing the program.
library-name: Specify the name of the library where the package is created.
*PGM: The package name is the same as the program name.
package-name: Specify the name of the package created on the remote database
specified on the RDBNAME parameter.
SAAFLAG
Specifies the IBM SQL flagging function. This parameter flags SQL statements
to verify whether they conform to IBM SQL syntax More information about
which IBM database products IBM SQL syntax is in the DRDA IBM SQL
Reference, SC26-3255-00.
*NOFLAG: The precompiler does not check to see whether SQL statements
conform to IBM SQL syntax.
*FLAG: The precompiler checks to see whether SQL statements conform to
IBM SQL syntax.
FLAGSTD
Specifies the American National Standards Institute (ANSI) flagging function.
This parameter flags SQL statements to verify whether they conform to the
following standards.
ANSI X3.135-1992 entry
ISO 9075-1992 entry
FIPS 127.2 entry
*NONE: The precompiler does not check to see whether SQL statements
conform to ANSI standards.
*ANS: The precompiler checks to see whether SQL statements conform to
ANSI standards.
578
CRTSQLRPG
PRTFILE
Specifies the qualified name of the printer device file to which the listing is
directed. The file must have a minimum record length of 132 bytes or
information is lost.
The name of the printer file can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the printer device file to which the
compiler printout is directed.
QSYSPRT: If a file name is not specified, the precompiler printout is directed
to the IBM-supplied printer file QSYSPRT.
printer-file-name: Specify the name of the printer device file to which the
compiler printout is directed.
SRTSEQ
Specifies the sort sequence table to be used for string comparisons in SQL
statements.
Note: *HEX must be specified for this parameter on distributed applications
where the application server is not on an AS/400 system or the release
level is prior to V2R3M0.
*JOB: The SRTSEQ value for the job is retrieved during the precompile.
*JOBRUN: The SRTSEQ value for the job is retrieved when the program is
run. For distributed applications, SRTSEQ(*JOBRUN) is valid only when
LANGID(*JOBRUN) is also specified.
*LANGIDUNQ: The unique-weight sort table for the language specified on the
LANGID parameter is used.
*LANGIDSHR: The shared-weight sort table for the language specified on the
LANGID parameter is used.
*HEX: A sort sequence table is not used. The hexadecimal values of the
characters are used to determine the sort sequence.
The name of the sort sequence table can be qualified by one of the following
library values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
table-name: Specify the name of the sort sequence table to be used.
579
CRTSQLRPG
LANGID
Specifies the language identifier to be used when SRTSEQ(*LANGIDUNQ) or
SRTSEQ(*LANGIDSHR) is specified.
*JOB: The LANGID value for hte job is retrieved during the precompile.
*JOBRUN: The LANGID value for the job is retrieved when the program is
run. For distributed applications, LANGID(*JOBRUN) is valid only when
SRTSEQ(*JOBRUN) is also specified.
language-id: Specify a language identifier to be used by the program.
USRPRF
Specifies the user profile that is used when the compiled program object is run,
including the authority that the program object has for each object in static
SQL statements. The profile of either the program owner or the program user
is used to control which objects can be used by the program object.
*NAMING: The user profile is determined by the naming convention. If the
naming convention is *SQL, USRPRF(*OWNER) is used. If the naming
convention is *SYS, USRPRF(*USER) is used.
*USER: The profile of the user running the program object is used.
*OWNER: The user profiles of both the program owner and the program user
are used when the program is run.
DYNUSRPRF
Specifies the user profile used for dynamic SQL statements.
*USER: Local dynamic SQL statements are run under the user profile of the
job. Distributed dynamic SQL statements are run under the user profile of the
application server job.
*OWNER: Local dynamic SQL statements are run under the user profile of the
programs owner. Distributed dynamic SQL statements are run under the user
profile of the SQL packages owner.
TOSRCFILE
Specifies the qualified name of the source file that is to contain the output
source member that has been processed by the SQL precompiler. If the
specified source file is not found, it will be created. The output member will
have the same name as the name that is specified for the SRCMBR parameter.
|
|
|
|
|
|
|
|
|
|
|
|
|
580
CRTSQLRPG
source-file-name: Specify the name of the source file to contain the output source
member.
TEXT
Specifies text that briefly describes the program and its function. More
information on this parameter is in Appendix A, Expanded Parameter
Descriptions in the CL Reference book.
*SRCMBRTXT: The text is taken from the source file member being used to
create the RPG program. Text for a database source member can be added or
changed by using the Start Source Entry Utility (STRSEU) command, or by
using either the Add Physical File Member (ADDPFM) command or the
Change Physical File Member (CHGPFM) command. If the source file is an
inline file or a device file, the text is blank.
*BLANK: Text is not specified.
description: Specify no more than 50 characters of text, enclosed in
apostrophes.
Example
CRTSQLRPG PGM(JONES/ARBR5)
TEXT('Accounts Receivable Branch 5')
This command runs the SQL precompiler which precompiles the source and stores
the changed source in member ARBR5 in file QSQLTEMP in library QTEMP. The
RPG compiler is called to create program ARBR5 in library JONES by using the
source member created by the SQL precompiler.
Pgm: B,I
REXX: B,I
Exec
*CURLIB/
CRTSQLRPGI
OBJ(
object-name )
library-name/
*LIBL/
QRPGLESRC
source-file-name
SRCFILE(
*CURLIB/
library-name/
(1)
SRCMBR(
*OBJ
source-file-member-name
OPTION(
OPTION Details
)
TGTRLS(
*CURRENT
*PRV
VxRxMx
581
CRTSQLRPGI
OBJTYPE(
*PGM
*MODULE
*SRVPGM
*LIBL/
*SRCFILE
source-file-name
INCFILE(
*CURLIB/
library-name/
COMMIT(
*UR
*CHG
*ALL
*RS
*CS
*NONE
*NC
*RR
CLOSQLCSR(
*ENDACTGRP
*ENDMOD
*YES
*OPTIMIZE
*NO
ALWCPYDTA(
ALWBLK(
*READ
*NONE
*ALLREAD
DLYPRP(
*NO
*YES
GENLVL(
10
severity-level
DATFMT(
*JOB
*USA
*ISO
*EUR
*JIS
*MDY
*DMY
*YMD
*JUL
DATSEP(
*JOB
'/'
'.'
','
'-'
' '
*BLANK
TIMFMT(
*HMS
*USA
*ISO
*EUR
*JIS
TIMSEP(
*JOB
':'
'.'
','
' '
*BLANK
REPLACE(
582
*YES
*NO
RDB(
*LOCAL
relational-database-name
*NONE
CRTSQLRPGI
USER(
*CURRENT
user-name
PASSWORD(
*NONE
password
RDBCNNMTH(
*DUW
*RUW
DFTRDBCOL(
*NONE
collection-name
*OBJLIB/
*OBJ
package-name
SQLPKG(
library-name/
SAAFLAG(
*NOFLAG
*FLAG
DBGVIEW(
*NONE
*SOURCE
FLAGSTD(
*NONE
*ANS
USRPRF(
*NAMING
*OWNER
*USER
DYNUSRPRF(
*USER
*OWNER
*JOB
*JOBRUN
*LANGIDUNQ
*LANGIDSHR
*HEX
*LIBL/
SRTSEQ(
table-name
*CURLIB/
library-name/
*JOB
*JOBRUN
language-identifier
LANGID(
OUTPUT(
*NONE
*PRINT
*LIBL/
QSYSPRT
printer-file-name
PRTFILE(
*CURLIB/
library-name/
QTEMP/
QSQLTEMP1
source-file-name
TOSRCFILE(
*LIBL/
*CURLIB/
library-name/
TEXT(
*SRCMBRTXT
*BLANK
'description'
583
CRTSQLRPGI
OPTION Details
*XREF
*GEN
*JOB
*SYS
*NOSECLVL
*NOXREF
*NOGEN
*SYSVAL
*PERIOD
*COMMA
*SQL
*SECLVL
*NOSEQSRC
*NOEVENTF
*SEQSRC
*EVENTF
Notes:
1. All parameters preceding this point can be specified in positional form.
Purpose
The Create Structured Query Language ILE RPG Object (CRTSQLRPGI) command
calls the Structured Query Language (SQL) precompiler which precompiles RPG
source containing SQL statements, produces a temporary source member, and then
optionally calls the ILE RPG compiler to create a module, create a program, or
create a service program.
Parameters
OBJ
Specifies the qualified name of the object being created.
*CURLIB: The new object is created in the current library for the job. If no
library is specified as the current library for the job, the QGPL library is
used.
library-name: Specify the name of the library where the object is created.
object-name: Specify the name of the object being created.
SRCFILE
Specifies the qualified name of the source file that contains the RPG source
with SQL statements.
The name of the source file can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
QRPGLESRC: If the source file name is not specified, the IBM-supplied source
file QRPGLESRC contains the RPG source.
source-file-name: Specify the name of the source file that contains the RPG
source.
SRCMBR
Specifies the name of the source file member that contains the RPG source.
584
CRTSQLRPGI
This parameter is specified only if the source file name in the SRCFILE
parameter is a database file. If this parameter is not specified, the PGM name
specified on the OBJ parameter is used.
*OBJ: Specifies that the RPG source is in the member of the source file that has
the same name as that specified on the OBJ parameter.
source-file-member-name: Specify the name of the member that contains the RPG
source.
OPTION
Specifies whether one or more of the following options are used when the RPG
source is precompiled. If an option is specified more than once, or if two
options conflict, the last option specified is used.
Element 1: Cross-Reference Options
*XREF: The precompiler cross-references items in the program to the statement
numbers in the program that refer to those items.
*NOXREF: The precompiler does not cross-reference names.
Element 2: Program Creation Options
*GEN: The precompiler creates the object that is specified by the OBJTYPE
parameter.
*NOGEN: The precompiler does not call the RPG compiler, and a module,
program, service program, or SQL package is not created.
Element 3: Decimal Point Options
*JOB: The value used as the decimal point for numeric constants in SQL is the
representation of decimal point specified for the job at precompile time.
*SYSVAL: The value used as the decimal point for numeric constants in SQL
statements is the QDECFMT system value.
Note: If QDECFMT specifies that the value used as the decimal point is a
comma(,), any numeric constants in lists (such as in the SELECT clause
or the VALUES clause) must be separated by a comma (,) followed by a
blank ( ). For example, VALUES(1,1, 2,23, 4,1) is equivalent to
VALUES(1.1,2.23,4.1) in which the decimal point is a period (.).
*PERIOD: The value used as the decimal point for numeric constants in SQL
statements is a period (.).
*COMMA: The value used as the decimal point for numeric constants in SQL
statements is a comma (,).
Note: Any numeric constants in lists (such as in the SELECT clause or the
VALUES clause) must be separated by a comma (,) followed by a blank(
). For example, VALUES(1,1, 2,23, 4,1) is equivalent to
VALUES(1.1,2.23,4.1) where the decimal point is a period (.).
Element 4: Naming Convention Options
Appendix D. DB2 for AS/400 CL Command Descriptions
585
CRTSQLRPGI
*SYS: The system naming convention (library-name/file-name) is used.
*SQL: The SQL naming convention is used (collection-name.table-name). When
creating a program on a remote database other than an AS/400 system, *SQL
must be specified as the naming convention.
Element 5: Second-Level Message Text Option
*NOSECLVL: Second-level text descriptions are not added to the listing.
*SECLVL: Second-level text with replacement data is added for all messages
on the listing.
Element 6: Sequence source
*NOSEQSRC: The source file member created into QSQLTEMP1 has the same
sequence numbers as the original source read by the precompiler.
*SEQSRC: The source file member created into QSQLTEMP1 contains
sequence numbers starting at 000001 and incremented by 000001.
Element 7: Event File Creation
*NOEVENTF: The compiler will not produce an Event File for use by
CoOperative Development Environment/400 (CODE/400).
*EVENTF: The compiler produces an event file for use by CoOperative
Development Environment/400 (CODE/400). The event file will be created as
a member in the file EVFEVENT in your source library. CODE/400 uses this
file to offer error feedback integrated with the CODE/400 editor. This option is
normally specified by CODE/400 on your behalf.
Element 8: Date Conversion
*NOCVTDT: Date, time and timestamp data types which are retrieved from
externally-described files are to be processed using the native RPG language.
*CVTDT: Date, time and timestamp data types which are retrieved from
externally-described files are to be processed as fixed-length character.
TGTRLS
Specifies the release of the operating system on which the user intends to use
the object being created.
In the examples given for the *CURRENT and *PRV values, and when
specifying the release-level value, the format VxRxMx is used to specify the
release, where Vx is the version, Rx is the release, and Mx is the modification
level. For example, V2R3M0 is version 2, release 3, modification level 0.
*CURRENT: The object is to be used on the release of the operating system
currently running on the users system. For example, if V2R3M5 is running on
the system, *CURRENT means the user intends to use the object on a system
with V2R3M5 installed. The user can also use the object on a system with any
subsequent release of the operating system installed.
586
CRTSQLRPGI
Note: If V2R3M5 is running on the system, and the object is to be used on a
system with V2R3M0 installed, specify TGTRLS(V2R3M0) not
TGTRLS(*CURRENT).
*PRV: The object is to be used on the previous release with modification level 0
of the operating system. For example, if V2R3M5 is running on the users
system, *PRV means the user intends to use the object on a system with
V2R2M0 installed. The user can also use the object on a system with any
subsequent release of the operating system installed.
release-level: Specify the release in the format VxRxMx. The object can be used
on a system with the specified release or with any subsequent release of the
operating system installed.
Valid values depend on the current version, release, and modification level,
and they change with each new release. If you specify a release-level which is
earlier than the earliest release level supported by this command, an error
message is sent indicating the earliest supported release.
OBJTYPE
Specifies the type of object being created.
*PGM: The SQL precompiler issues the CRTBNDRPG command to create the
bound program.
*MODULE: The SQL precompiler issues the CRTRPGMOD command to create
the module.
*SRVPGM: The SQL precompiler issues the CRTRPGMOD and CRTSRVPGM
commands to create the service program.
Notes:
1. When OBJTYPE(*PGM) or OBJTYPE(*SRVPGM) is specified and the RDB
parameter is also specified, the CRTSQLPKG command is issued by the
SQL precompiler after the program has been created. When
OBJTYPE(*MODULE) is specified, an SQL package is not created and you
must issue the CRTSQLPKG command after the CRTPGM or CRTSRVPGM
command has created the program.
2. If *NOGEN is specified, only the SQL temporary source member is
generated and a module, program, service program, and SQL package are
not created.
INCFILE
Specifies the qualified name of the source file that contains members included
in the program with any SQL INCLUDE statement.
The name of the source file can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
*SRCFILE: The qualified source file specified in the SRCFILE parameter
contains the source file members specified on any SQL INCLUDE statement.
587
CRTSQLRPGI
source-file-name: Specify the name of the source file that contains the source file
members specified on any SQL INCLUDE statement. The record length of the
source file specified here must be no less than the record length of the source
file specified on the SRCFILE parameter.
COMMIT
Specifies whether SQL statements in the compiled unit are run under
commitment control. Files referred to in the host language source are not
affected by this option. Only SQL tables, SQL views, and SQL packages
referred to in SQL statements are affected.
*CHG or *UR: Specifies the objects referred to in SQL ALTER, CALL,
COMMENT ON, CREATE, DROP, GRANT, LABEL ON, RENAME, and
REVOKE statements and the rows updated, deleted, and inserted are locked
until the end of the unit of work (transaction). Uncommitted changes in other
jobs can be seen.
*ALL or *RS: Specifies the objects referred to in SQL ALTER, CALL,
COMMENT ON, CREATE, DROP, GRANT, LABEL ON, RENAME, and
REVOKE statements and the rows selected, updated, deleted, and inserted are
locked until the end of the unit of work (transaction). Uncommitted changes in
other jobs cannot be seen.
*CS: Specifies the objects referred to in SQL ALTER, CALL, COMMENT ON,
CREATE, DROP, GRANT, LABEL ON, RENAME, and REVOKE statements and
the rows updated, deleted, and inserted are locked until the end of the unit of
work (transaction). A row that is selected, but not updated, is locked until the
next row is selected. Uncommitted changes in other jobs cannot be seen.
*NONE or *NC: Specifies that commitment control is not used. Uncommitted
changes in other jobs can be seen. If the SQL DROP COLLECTION statement
is included in the program, *NONE or *NC must be used. If a relational
database is specified on the RDB parameter and the relational database is on a
system that is not on an AS/400, *NONE or *NC cannot be specified.
*RR: Specifies the objects referred to in SQL ALTER, CALL, COMMENT ON,
CREATE, DROP, GRANT, LABEL ON, RENAME, and REVOKE statements and
the rows selected, updated, deleted, and inserted are locked until the end of
the unit of work (transaction). Uncommitted changes in other jobs cannot be
seen. All tables referred to in SELECT, UPDATE, DELETE, and INSERT
statements are locked exclusively until the end of the unit of work
(transaction).
CLOSQLCSR
Specifies when SQL cursors are implicitly closed, SQL prepared statements are
implicitly discarded, and LOCK TABLE locks are released. SQL cursors are
explicitly closed when you issue the CLOSE, COMMIT, or ROLLBACK
(without HOLD) SQL statements.
*ENDACTGRP: SQL cursors are closed, SQL prepared statements are
implicitly discarded, and LOCK TABLE locks are released when the activation
group ends.
*ENDMOD: SQL cursors are closed and SQL prepared statements are
implicitly discarded when the module is exited. LOCK TABLE locks are
released when the first SQL program on the call stack ends.
588
CRTSQLRPGI
ALWCPYDTA
Specifies whether a copy of the data can be used in a SELECT statement.
*YES: A copy of the data is used only when necessary.
*OPTIMIZE: The system determines whether to use the data retrieved directly
from the database or to use a copy of the data. The decision is based on which
method provides the best performance. If COMMIT is *CHG or *CS and
ALWBLK is not *ALLREAD, or if COMMIT is *ALL or *RR, then a copy of the
data is used only when it is necessary to run a query.
*NO: A copy of the data is not used. If temporary copy of the data is required
to perform the query, an error message is returned.
ALWBLK
Specifies whether the database manager can use record blocking, and the
extent to which blocking can be used for read-only cursors.
*READ: Records are blocked for read-only retrieval of data for cursors when:
v *NONE is specified on the COMMIT parameter, which indicates that
commitment control is not used.
v The cursor is declared with a FOR READ ONLY clause or there are no
dynamic statements that could run a positioned UPDATE or DELETE
statement for the cursor.
Specifying *READ can improve the overall performance of queries that meet
the above conditions and retrieve a large number of records.
*NONE: Rows are not blocked for retrieval of data for cursors.
Specifying *NONE:
v Guarantees that the data retrieved is current.
v May reduce the amount of time required to retrieve the first row of data for
a query.
v Stops the database manager from retrieving a block of data rows that is not
used by the program when only the first few rows of a query are retrieved
before the query is closed.
v Can degrade the overall performance of a query that retrieves a large
number of rows.
*ALLREAD: Rows are blocked for read-only cursors if *NONE or *CHG is
specified on the COMMIT parameter. All cursors in a program that are not
explicitly able to be updated are opened for read-only processing even though
EXECUTE or EXECUTE IMMEDIATE statements may be in the program.
Specifying *ALLREAD:
v Allows record blocking under commitment control level *CHG in addition to
the blocking allowed for *READ.
v Can improve the performance of almost all read-only cursors in programs,
but limits queries in the following ways:
The Rollback (ROLLBACK) command, a ROLLBACK statement in host
languages, or the ROLLBACK HOLD SQL statement does not reposition a
read-only cursor when *ALLREAD is specified.
589
CRTSQLRPGI
Dynamic running of a positioned UPDATE or DELETE statement (for
example, using EXECUTE IMMEDIATE), cannot be used to update a row
in a cursor unless the DECLARE statement for the cursor includes the
FOR UPDATE clause.
DLYPRP
Specifies whether the dynamic statement validation for a PREPARE statement
is delayed until an OPEN, EXECUTE, or DESCRIBE statement is run. Delaying
validation improves performance by eliminating redundant validation.
*NO: Dynamic statement validation is not delayed. When the dynamic
statement is prepared, the access plan is validated. When the dynamic
statement is used in an OPEN or EXECUTE statement, the access plan is
revalidated. Because the authority or the existence of objects referred to by the
dynamic statement may change, you must still check the SQLCODE or
SQLSTATE after issuing the OPEN or EXECUTE statement to ensure that the
dynamic statement is still valid.
*YES: Dynamic statement validation is delayed until the dynamic statement is
used in an OPEN, EXECUTE, or DESCRIBE SQL statement. When the dynamic
statement is used, the validation is completed and an access plan is built. If
you specify *YES on this parameter, you should check the SQLCODE and
SQLSTATE after running an OPEN, EXECUTE, or DESCRIBE statement to
ensure that the dynamic statement is valid.
Note: If you specify *YES, performance is not improved if the INTO clause is
used on the PREPARE statement or if a DESCRIBE statement uses the
dynamic statement before an OPEN is issued for the statement.
GENLVL
Specifies the severity level at which the create operation fails. If errors occur
that have a severity level greater than this value, the operation ends.
10: The default severity level is 10.
severity-level: Specify a value ranging from 0 through 40.
DATFMT
Specifies the format used when accessing date result columns. All output date
fields are returned in the specified format. For input date strings, the specified
value is used to determine whether the date is specified in a valid format.
Note: An input date string that uses the format *USA, *ISO, *EUR, or *JIS is
always valid.
If a relational database is specified on the RDB parameter and the
database is on a system that is not an AS/400 system, then *USA, *ISO,
*EUR, or *JIS must be specified.
*JOB: The format specified for the job is used. Use the Display Job (DSPJOB)
command to determine the current date format for the job.
*USA: The United States date format (mm/dd/yyyy) is used.
*ISO: The International Organization for Standardization (ISO) date format
(yyyy-mm-dd) is used.
590
CRTSQLRPGI
*EUR: The European date format (dd.mm.yyyy) is used.
*JIS: The Japanese Industrial Standard date format (yyyy-mm-dd) is used.
*MDY: The date format (mm/dd/yy) is used.
*DMY: The date format (dd/mm/yy) is used.
*YMD: The date format (yy/mm/dd) is used.
*JUL: The Julian date format (yy/ddd) is used.
DATSEP
Specifies the separator used when accessing date result columns.
Note: This parameter applies only when *JOB, *MDY, *DMY, *YMD, or *JUL is
specified on the DATFMT parameter.
*JOB: The date separator specified for the job at precompile time is used. Use
the Display Job (DSPJOB) command to determine the current value for the job.
/: A slash (/) is used.
.: A period (.) is used.
,: A comma (,) is used.
-: A dash (-) is used.
: A blank ( ) is used.
*BLANK: A blank ( ) is used.
TIMFMT
Specifies the format used when accessing time result columns. For input time
strings, the specified value is used to determine whether the time is specified
in a valid format.
Note: An input time string that uses the format *USA, *ISO, *EUR, or *JIS is
always valid.
If a relational database is specified on the RDB parameter and the
database is on a system that is not another AS/400 system, the time
format must be *USA, *ISO, *EUR, *JIS, or *HMS with a time separator
of a colon or period.
*HMS: The hh:mm:ss format is used.
*USA: The United States time format hh:mm xx is used, where xx is AM or
PM.
*ISO: The International Organization for Standardization (ISO) time format
hh.mm.ss is used.
*EUR: The European time format hh.mm.ss is used.
*JIS: The Japanese Industrial Standard time format hh:mm:ss is used.
Appendix D. DB2 for AS/400 CL Command Descriptions
591
CRTSQLRPGI
TIMSEP
Specifies the separator used when accessing time result columns.
Note: This parameter applies only when *HMS is specified on the TIMFMT
parameter.
*JOB: The time separator specified for the job at precompile time is used. Use
the Display Job (DSPJOB) command to determine the current value for the job.
:: A colon (:) is used.
.: A period (.) is used.
,: A comma (,) is used.
: A blank ( ) is used.
*BLANK: A blank ( ) is used.
REPLACE
Specifies if a SQL module, program, service program or package is created
when there is an existing SQL module, program, service program, or package
of the same name and type in the same library. The value of this parameter is
passed to the CRTRPGMOD, CRTBNDRPG, CRTSRVPGM, and CRTSQLPKG
commands.
*YES: A new SQL module, program, service program, or package is created,
any existing SQL object of the same name and type in the specified library is
moved to QRPLOBJ.
*NO: A new SQL module, program, service program, or package is not created
if an SQL object of the same name and type already exists in the specified
library.
RDB
Specifies the name of the relational database where the SQL package object is
created.
*LOCAL: The program is created as a distributed SQL program. The SQL
statements will access the local database. An SQL package object is not created
as part of the precompile process. The Create Structured Query Language
Package (CRTSQLPKG) command can be used.
relational-database-name: Specify the name of the relational database where the
new SQL package object is to be created. When the name of the local relational
database is specified, the program created is still a distributed SQL program.
The SQL statements will access the local database.
*NONE: An SQL package object is not created. The program object is not a
distributed program and the Create Structured Query Language Package
(CRTSQLPKG) command cannot be used.
USER
Specifies the user name sent to the remote system when starting the
conversation. This parameter is valid only when RDB is specified.
*CURRENT: The user profile under which the current job is running is used.
592
CRTSQLRPGI
user-name: Specify the user name being used for the application server job.
PASSWORD
Specifies the password to be used on the remote system. This parameter is
valid only if RDB is specified.
*NONE: No password is sent. If this value is specified, USER(*CURRENT)
must also be specified.
password: Specify the password of the user name specified on the USER
parameter.
RDBCNNMTH
Specifies the semantics used for CONNECT statements. Refer to the SQL
Reference, SC41-3612 book for more information.
*DUW: CONNECT (Type 2) semantics are used to support distributed unit of
work. Consecutive CONNECT statements to additional relational databases do
not result in disconnection of previous connections.
*RUW: CONNECT (Type 1) semantics are used to support remote unit of
work. Consecutive CONNECT statements result in the previous connection
being disconnected before a new connection is established.
DFTRDBCOL
Specifies the collection name used for the unqualified names of tables, views,
indexes, and SQL packages. This parameter applies only to static SQL
statements.
*NONE: The naming convention defined on the OPTION parameter is used.
collection-name: Specify the name of the collection identifier. This value is used
instead of the naming convention specified on the OPTION parameter.
SQLPKG
Specifies the qualified name of the SQL package created on the relational
database specified on the RDB parameter of this command.
The possible library values are:
*OBJLIB: The package is created in the library with the same name as the
library specified on the OBJ parameter.
library-name: Specify the name of the library where the package is created.
*OBJ: The name of the SQL package is the same as the object name specified
on the OBJ parameter.
package-name: Specify the name of the SQL package. If the remote system is not
an AS/400 system, no more than 8 characters can be specified.
SAAFLAG
Specifies the IBM SQL flagging function. This parameter flags SQL statements
to verify whether they conform to IBM SQL syntax. More information about
IBM SQL syntax found in IBM database products can be found in the DRDA
IBM SQL Reference, SC26325500.
*NOFLAG: The precompiler does not check to see whether SQL statements
conform to IBM SQL syntax.
593
CRTSQLRPGI
*FLAG: The precompiler checks to see whether SQL statements conform to
IBM SQL syntax.
FLAGSTD
Specifies the American National Standards Institute (ANSI) flagging function.
This parameter flags SQL statements to verify whether they conform to the
following standards.
ANSI X3.135-1992 entry
ISO 9075-1992 entry
FIPS 127.2 entry
*NONE: The precompiler does not check to see whether SQL statements
conform to ANSI standards.
*ANS: The precompiler checks to see whether SQL statements conform to
ANSI standards.
DBGVIEW
Specifies the type of source debug information to be provided by the SQL
precompiler.
*NONE: The source view will not be generated.
*SOURCE: The SQL precompiler will provide the source views for the root
and if necessary, SQL INCLUDE statements. A view will be provided which
contains the statements generated by the precompiler.
USRPRF
Specifies the user profile that is used when the compiled program object is run,
including the authority that the program object has for each object in static
SQL statements. The profile of either the program owner or the program user
is used to control which objects can be used by the program object.
*NAMING: The user profile is determined by the naming convention. If the
naming convention is *SQL, USRPRF(*OWNER) is used. If the naming
convention is *SYS, USRPRF(*USER) is used.
*USER: The profile of the user running the program object is used.
*OWNER: The user profiles of both the program owner and the program user
are used when the program is run.
DYNUSRPRF
Specifies the user profile to be used for dynamic SQL statements.
*USER: For local, dynamic SQL statements run under the user of the
programs user. For distributed, dynamic SQL statements run under the profile
of the SQL packages user.
*OWNER: For local, dynamic SQL statements run under the profile of the
programs owner. For distributed, dynamic SQL statements run under the
profile of the SQL packages owner.
SRTSEQ
Specifies the sort sequence table to be used for string comparisons in SQL
statements.
594
CRTSQLRPGI
Note: *HEX must be specified for this parameter on distributed applications
where the application server is not on an AS/400 system or the release
level is prior to V2R3M0.
*JOB: The SRTSEQ value for the job is retrieved during the precompile.
*JOBRUN: The SRTSEQ value for the job is retrieved when the program is
run. For distributed applications, SRTSEQ(*JOBRUN) is valid only when
LANGID(*JOBRUN) is also specified.
*LANGIDUNQ: The unique-weight sort table for the language specified on the
LANGID parameter is used.
*LANGIDSHR: The sort sequence table uses the same weight for multiple
characters, and is the shared-weight sort sequence table associated with the
language specified on the LANGID parameter.
*HEX: A sort sequence table is not used. The hexadecimal values of the
characters are used to determine the sort sequence.
The name of the sort sequence table can be qualified by one of the following
library values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
table-name: Specify the name of the sort sequence table to be used.
LANGID
Specifies the language identifier to be used when SRTSEQ(*LANGIDUNQ) or
SRTSEQ(*LANGIDSHR) is specified.
*JOB: The LANGID value for the job is retrieved during the precompile.
*JOBRUN: The LANGID value for the job is retrieved when the program is
run. For distributed applications, LANGID(*JOBRUN) is valid only when
SRTSEQ(*JOBRUN) is also specified.
language-identifier: Specify a language identifier.
OUTPUT
Specifies whether the precompiler listing is generated.
*NONE: The precompiler listing is not generated.
*PRINT: The precompiler listing is generated.
PRTFILE
Specifies the qualified name of the printer device file to which the precompiler
printout is directed. The file must have a minimum length of 132 bytes. If a file
with a record length of less than 132 bytes is specified, information is lost.
The name of the printer file can be qualified by one of the following library
values:
595
CRTSQLRPGI
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
QSYSPRT: If a file name is not specified, the precompiler printout is directed
to the IBM-supplied printer file QSYSPRT.
printer-file-name: Specify the name of the printer device file to which the
precompiler printout is directed.
TOSRCFILE
Specifies the qualified name of the source file that is to contain the output
source member that has been processed by the SQL precompiler. If the
specified source file is not found, it will be created. The output member will
have the same name as the name that is specified for the SRCMBR parameter.
|
|
|
|
|
|
|
source-file-name: Specify the name of the source file to contain the output source
member.
|
|
|
|
|
|
|
TEXT
Specifies the text that briefly describes the function. More information on this
parameter is located in Appendix A, Expanded Parameter Descriptions in the
CL Reference book.
*SRCMBRTXT: The text is taken from the source file member being used to
create the RPG program. Text can be added or changed for a database source
member by using the Start Source Entry Utility (STRSEU) command, or by
using either the Add Physical File Member (ADDPFM) or Change Physical File
Member (CHGPFM) command. If the source file is an inline file or a device
file, the text is blank.
*BLANK: Text is not specified.
description: Specify no more than 50 characters of text, enclosed in
apostrophes.
Example
CRTSQLRPGI
This command runs the SQL precompiler which precompiles the source and stores
the changed source in member PAYROLL in file QSQLTEMP1 in library QTEMP.
596
CRTSQLRPGI
The ILE RPG compiler is called to create program PAYROLL in the current library
by using the source member created by the SQL precompiler.
Pgm: B,I
REXX: B,I
Exec
*LIBL/
PGM(
CRTSQLPKG
program-name )
*CURLIB/
library-name/
(1)
RDB(
*PGM
relational-database-name
USER(
*CURRENT
user-name
PASSWORD(
*NONE
password
10
severity-level
GENLVL(
REPLACE(
*YES
*NO
DFTRDBCOL(
*PGM
*NONE
collection-name
*LIBL/
QSYSPRT
printer-file-name
PRTFILE(
*CURLIB/
library-name/
OBJTYPE(
*PGM
*SRVPGM
*ALL
MODULE(
module-name
(2)
)
TEXT(
*PGMTXT
*BLANK
'description'
597
CRTSQLPKG
Notes:
1. All parameters preceding this point can be specified in positional form.
2. A maximum of 256 modules may be specified.
Purpose
The Create Structured Query Language Package (CRTSQLPKG) command is used
to create (or re-create) an SQL package on a relational database from an existing
distributed SQL program. A distributed SQL program is a program created by
specifying the RDB parameter on a CRTSQLxxx (where xxx = C, CI, CBL, CBLI,
FTN, PLI, or RPG or RPGI) command.
Parameters
PGM
Specifies the qualified name of the program for which the SQL package is
being created. The program must be a distributed SQL program.
The name of the program can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
program-name: Specify the name of the program for which the package is being
created.
RDB
Specifies the name of the relational database where the SQL package is being
created.
*PGM: The relational database name specified for the SQL program is used.
The relational database name is specified on the RDB parameter of the
distributed SQL program.
relational-database-name: Specify the name of the relational database where the
SQL package is to be created. Use the Work with Relational Database Directory
Entry (WRKRDBDIRE) command to show the relational database names that
are valid on this parameter.
USER
Specifies the user name sent to the remote system when starting the
conversation.
*CURRENT: The user name associated with the current job is used.
user-name: Specify the user name being used for the application server job.
PASSWORD
Specifies the password to be used on the remote system.
*NONE: No password is sent. If this value is specified, USER(*CURRENT)
must also be specified.
598
CRTSQLPKG
password: Specify the password of the user name specified on the USER
parameter.
GENLVL
Specifies the maximum severity level allowed for errors detected during SQL
package creation. If errors occur at a level that exceeds the specified level, the
SQL package is not created.
10: The default severity-level is 10.
severity-level: Specify the maximum severity level. Valid values range from 0
through 40.
REPLACE
Specifies whether an existing package is being replaced with the new package.
More information on this parameter is in Appendix A, Expanded Parameter
Descriptions in the CL Reference book.
*YES: An existing SQL package of the same name is replaced by the new SQL
package.
*NO: An existing SQL package of the same name is not replaced; a new SQL
package is not created if the package already exists in the specified library.
DFTRDBCOL
Specifies the collection name to be used for unqualified names of tables, views,
indexes, and SQL packages. This parameter applies only to static SQL
statements in the package.
*PGM: The collection name specified for the SQL program is used. The default
relational database collection name is specified on the DFTRDBCOL parameter
of the distributed SQL program.
*NONE: Unqualified names for tables, views, indexes, and SQL packages use
the search conventions specified on the OPTION parameter of the CRTSQLxxx
command used to create the program.
collection-name: Specify the collection name that is used for unqualified tables,
views, indexes, and SQL packages.
PRTFILE
Specifies the qualified name of the printer device file to which the create SQL
package error listing is directed. If no errors are detected during the creation of
the SQL package, no listing is produced.
The name of the printer file can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
QSYSPRT: If a file name is not specified, the create SQL package error listing
is directed to the IBM-supplied printer file QSYSPRT.
599
CRTSQLPKG
printer-file-name: Specify the name of the printer device file to which the create
SQL package error listing is directed.
OBJTYPE
Specifies the type of program for which an SQL package is created.
*PGM: Create an SQL package from the program specified on the PGM
parameter.
*SRVPGM: Create an SQL package from the service program specified on the
PGM parameter.
MODULE
Specifies a list of modules in a bound program.
*ALL: An SQL package is created for each module in the program. An error
message is sent if none of the modules in the program contain SQL statements
or none of the modules is a distributed module.
Note: CRTSQLPKG can process programs that do not contain more than 1024
modules.
module-name: Specify the names of up to 256 modules in the program for which
an SQL package is to be created. If more than 256 modules exist that need to
have an SQL package created, multiple CRTSQLPKG commands must be used.
Duplicate module names in the same program are allowed. This command
looks at each module in the program and if *ALL or the module name is
specified on the MODULE parameter, processing continues to determine
whether an SQL package should be created. If the module is created using SQL
and the RDB parameter is specified on the precompile command, an SQL
package is created for the module. The SQL package is associated with the
module of the bound program.
TEXT
Specifies text that briefly describes the SQL package and its function.
*PGMTXT: The text from the program for which the SQL package is being
created is used.
*BLANK: No text is specified.
description: Specify a maximum of 50 characters of text, enclosed in
apostrophes.
Example
CRTSQLPKG PAYROLL RDB(SYSTEMA)
TEXT('Payroll Program')
This command creates an SQL package from the distributed SQL program
PAYROLL on relational database SYSTEMA.
600
CVTSQLCPP
|
|
|
Job: B,I
|
|
Pgm: B,I
REXX: B,I
Exec
*LIBL/
SRCFILE(
CVTSQLCPP
source-file-name
*CURLIB/
library-name/
|
|
SRCMBR(
|
|
*OBJ
source-file-member-name
(1)
)
*LIBL/
QSQLTEMP
source-file-name
TOSRCFILE(
*CURLIB/
library-name/
|
|
OPTION(
OPTION Details
*CURRENT
VxRxMx
TGTRLS(
|
|
*LIBL/
*SRCFILE
source-file-name
INCFILE(
*CURLIB/
library-name/
|
|
COMMIT(
|
|
CLOSQLCSR(
*ENDACTGRP
*ENDMOD
ALWCPYDTA(
|
|
*UR
*CHG
*ALL
*RS
*CS
*NONE
*NC
*RR
*YES
*OPTIMIZE
*NO
ALWBLK(
*READ
*NONE
*ALLREAD
DLYPRP(
*NO
*YES
GENLVL(
10
severity-level
601
CVTSQLCPP
|
|
*SRCFILE
left-right
MARGINS(
|
|
*JOB
*USA
*ISO
*EUR
*JIS
*MDY
*DMY
*YMD
*JUL
DATFMT(
*JOB
'/'
'.'
','
'-'
' '
*BLANK
DATSEP(
|
|
*HMS
*USA
*ISO
*EUR
*JIS
TIMFMT(
*JOB
':'
'.'
','
' '
*BLANK
TIMSEP(
|
|
RDB(
*LOCAL
relational-database-name
*NONE
USER(
*CURRENT
user-name
|
|
*NONE
password
PASSWORD(
RDBCNNMTH(
*DUW
*RUW
|
|
*NONE
collection-name
DFTRDBCOL(
|
|
*OBJLIB/
*OBJ
package-name
SQLPKG(
library-name/
|
|
SAAFLAG(
*NOFLAG
*FLAG
DBGVIEW(
*NONE
*SOURCE
FLAGSTD(
*NONE
*ANS
|
|
602
USRPRF(
*NAMING
*OWNER
*USER
CVTSQLCPP
|
|
*USER
*OWNER
DYNUSRPRF(
|
|
SRTSEQ(
*JOB
*JOBRUN
*LANGIDUNQ
*LANGIDSHR
*HEX
*LIBL/
table-name
*CURLIB/
library-name/
|
|
LANGID(
|
|
*JOB
*JOBRUN
language-identifier
OUTPUT(
*NONE
*PRINT
*LIBL/
QSYSPRT
printer-file-name
PRTFILE(
*CURLIB/
library-name/
|
|
TEXT(
*SRCMBRTXT
*BLANK
'description'
|
|
OPTION Details
|
|
|
|
*XREF
*JOB
*SYS
*NOSECLVL
*NOCNULRQD
*NOXREF
*SYSVAL
*PERIOD
*COMMA
*SQL
*SECLVL
*CNULRQD
*NOEVENTF
*EVENTF
|
|
Notes:
|
|
|
|
|
|
Purpose
The Convert Structured Query Language C++ Source (CVTSQLCPP) command
calls the Structured Query Language (SQL) precompiler. The precompiler
precompiles C++ source that contains SQL statements, and produces a temporary
source member. This source member can then be provided as input to the
VisualAge C++ for AS/400 compiler.
603
CVTSQLCPP
Parameters
SRCFILE
Specifies the qualified name of the source file that contains the C++ source
with SQL statements.
|
|
|
One of the following library values can qualify the name of the source file:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
|
|
source-file-name: Specify the name of the source file that contains the C++
source with SQL statements.
|
|
|
|
|
|
|
SRCMBR
Specifies the name of the source file member that contains the C++ source.
|
|
|
|
|
TOSRCFILE
Specifies the qualified name of the source file that is to contain the output C++
source member that has been processed by the SQL C++ precompiler. If the
specified source file is not found, it will be created. The output member will
have the same name as the name specified for the SRCMBR parameter.
|
|
The name of the source file can be qualified by one of the following library
values:
|
|
|
*LIBL: The jobs library list is searched for the specified file. If the file is not
found in any library in the library list, the file will be created in the current
library.
|
|
*CURLIB: The current library for the job will be used. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library that is to contain the output
source file.
|
|
OPTION
Specifies whether one or more of the following options are used when the C++
source is precompiled. If an option is specified more than once, or if two
options conflict, the last option specified is used.
|
|
|
|
|
|
|
|
|
*JOB: The value used as the decimal point for numeric constants in SQL is the
representation of decimal point specified for the job at precompile time.
|
|
|
Note: If the job decimal point value specifies that the value used as the
decimal point is a comma, any numeric constants in lists (such as in the
SELECT clause or the VALUES clause) must be separated by a comma
604
CVTSQLCPP
|
|
|
|
*PERIOD:The value used as the decimal point for numeric constants in SQL
statements is a period.
|
|
*COMMA: The value used as the decimal point for numeric constants in SQL
statements is a comma.
|
|
|
|
Note: Any numeric constants in lists (such as in the SELECT clause or the
VALUES clause) must be separated by a comma followed by a blank.
For example, VALUES(1,1, 2,23, 4,1) is equivalent to
VALUES(1.1,2.23,4.1) where the decimal point is a period.
|
|
|
|
|
*SECLVL: Second-level text with replacement data is added for all messages
on the listing.
|
|
|
|
|
|
|
|
*CNULRQD: Output character and graphic host variables always contain the
NUL-terminator. If there is not enough space for the NUL-terminator, the data
is truncated and the NUL-terminator is added. Input character and graphic
host variables require a NUL-terminator.
|
|
*NOEVENTF: The compiler will not produce an event file for use by
CoOperative Development Environment/400 (CODE/400).
|
|
|
|
|
|
|
|
TGTRLS
Specifies the release of the operating system on which the user intends to use
the object being created.
605
CVTSQLCPP
|
|
|
|
In the examples given for the *CURRENT and *PRV values, and when
specifying the release-level value, the format VxRxMx is used to specify the
release, where Vx is the version, Rx is the release, and Mx is the modification
level. For example, V2R3M0 is version 2, release 3, modification level 0.
|
|
|
|
|
|
|
|
|
|
|
release-level: Specify the release in the format VxRxMx. The object can be used
on a system with the specified release or with any subsequent release of the
operating system installed.
|
|
|
|
Valid values depend on the current version, release, and modification level,
and they change with each new release. If you specify a release-level which is
earlier than the earliest release level supported by this command, an error
message is sent indicating the earliest supported release.
|
|
|
INCFILE
Specifies the qualified name of the source file that contains members included
in the program with any SQL INCLUDE statement.
The name of the source file can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
|
|
|
|
|
|
source-file-name: Specify the name of the source file that contains the source file
members specified on any SQL INCLUDE statement. The record length of the
source file specified here must be no less than the record length of the source
file specified on the SRCFILE parameter.
|
|
|
|
|
|
COMMIT
Specifies whether SQL statements in the compiled unit are run under
commitment control. Files referred to in the host language source are not
affected by this option. Only SQL tables, SQL views, and SQL packages
referred to in SQL statements are affected.
|
|
|
|
|
|
|
|
|
|
606
CVTSQLCPP
|
|
|
|
|
|
|
|
|
|
*CS: Specifies the objects referred to in SQL ALTER, CALL, COMMENT ON,
CREATE, DROP, GRANT, LABEL ON, RENAME, and REVOKE statements and
the rows updated, deleted, and inserted are locked until the end of the unit of
work (transaction). A row that is selected, but not updated, is locked until the
next row is selected. Uncommitted changes in other jobs cannot be seen.
|
|
|
|
|
|
|
|
|
|
|
|
*RR: Specifies the objects referred to in SQL ALTER, CALL, COMMENT ON,
CREATE, DROP, GRANT, LABEL ON, RENAME, and REVOKE statements and
the rows selected, updated, deleted, and inserted are locked until the end of
the unit of work (transaction). Uncommitted changes in other jobs cannot be
seen. All tables referred to in SELECT, UPDATE, DELETE, and INSERT
statements are locked exclusively until the end of the unit of work
(transaction).
|
|
|
|
|
CLOSQLCSR
Specifies when SQL cursors are implicitly closed, SQL prepared statements are
implicitly discarded, and LOCK TABLE locks are released. SQL cursors are
explicitly closed when you issue the CLOSE, COMMIT, or ROLLBACK
(without HOLD) SQL statements.
|
|
|
|
|
|
*ENDMOD: SQL cursors are closed and SQL prepared statements are
implicitly discarded when the module is exited. LOCK TABLE locks are
released when the first SQL program on the call stack ends.
|
|
ALWCPYDTA
Specifies whether a copy of the data can be used in a SELECT statement.
|
|
|
|
|
*OPTIMIZE: The system determines whether to use the data retrieved directly
from the database or to use a copy of the data. The decision is based on which
method provides the best performance. If COMMIT is *CHG or *CS and
ALWBLK is not *ALLREAD, or if COMMIT is *ALL or *RR, then a copy of the
data is used only when it is necessary to run a query.
|
|
*NO: A copy of the data is not allowed. If a temporary copy of the data is
required to perform the query, an error message is returned.
|
|
|
ALWBLK
Specifies whether the database manager can use record blocking, and the
extent to which blocking can be used for read-only cursors.
Appendix D. DB2 for AS/400 CL Command Descriptions
607
CVTSQLCPP
|
*READ: Records are blocked for read-only retrieval of data for cursors when:
|
|
|
|
|
|
|
Specifying *READ can improve the overall performance of queries that meet
the above conditions and retrieve a large number of records.
*NONE: Rows are not blocked for retrieval of data for cursors.
|
|
|
Specifying *NONE:
v Guarantees that the data retrieved is current.
v May reduce the amount of time required to retrieve the first row of data for
a query.
v Stops the database manager from retrieving a block of data rows that is not
used by the program when only the first few rows of a query are retrieved
before the query is closed.
|
|
|
|
|
|
Specifying *ALLREAD:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
DLYPRP
Specifies whether the dynamic statement validation for a PREPARE statement
is delayed until an OPEN, EXECUTE, or DESCRIBE statement is run. Delaying
validation improves performance by eliminating redundant validation.
|
|
|
|
|
|
|
608
CVTSQLCPP
|
|
|
|
|
|
|
|
|
Note: If you specify *YES, performance is not improved if the INTO clause is
used on the PREPARE statement or if a DESCRIBE statement uses the
dynamic statement before an OPEN is issued for the statement.
|
|
|
GENLVL
Specifies the severity level at which the create operation fails. If errors occur
that have a severity level greater than this value, the operation ends.
|
|
MARGINS
Specifies the part of the precompiler input record that contains source text.
|
|
*SRCFILE: The file member margin values specified by the user on the
SRCMBR parameter are used. The margin default values are 1 and 80.
|
|
left: Specify the beginning position for the statements. Valid values range from
1 through 80.
|
|
right: Specify the ending position for the statements. Valid values range from 1
through 80.
|
|
|
|
DATFMT
Specifies the format used when accessing date result columns. All output date
fields are returned in the specified format. For input date strings, the specified
value is used to determine whether the date is specified in a valid format.
|
|
|
|
|
Note: An input date string that uses the format *USA, *ISO, *EUR, or *JIS is
always valid.
If a relational database is specified on the RDB parameter and the
database is on a system that is not an AS/400 system, then *USA, *ISO,
*EUR, or *JIS must be specified.
|
|
*JOB: The format specified for the job is used. Use the Display Job (DSPJOB)
command to determine the current date format for the job.
|
|
609
CVTSQLCPP
|
|
|
|
|
Note: This parameter applies only when *JOB, *MDY, *DMY, *YMD, or *JUL is
specified on the DATFMT parameter.
|
|
*JOB:The date separator specified for the job at precompile time is used. Use
the Display Job (DSPJOB) command to determine the current value for the job.
: A blank ( ) is used.
|
|
|
|
Note: An input time string that uses the format *USA, *ISO, *EUR, or *JIS is
always valid.
|
|
|
|
|
|
|
|
|
|
|
610
CVTSQLCPP
|
|
TIMSEP
Specifies the separator used when accessing time result columns.
|
|
Note: This parameter applies only when *HMS is specified on the TIMFMT
parameter.
|
|
*JOB: The time separator specified for the job at precompile time is used. Use
the Display Job (DSPJOB) command to determine the current value for the job.
: A blank ( ) is used.
|
|
|
RDB
Specifies the name of the relational database where the SQL package object is
created.
|
|
|
|
|
|
|
|
|
|
|
*NONE: An SQL package object is not created. The program object is not a
distributed program and the Create Structured Query Language Package
(CRTSQLPKG) command cannot be used.
|
|
|
USER
Specifies the user name sent to the remote system when starting the
conversation. This parameter is valid only when RDB is specified.
*CURRENT: The user profile under which the current job is running is used.
user-name: Specify the user name being used for the application server job.
|
|
|
PASSWORD
Specifies the password to be used on the remote system. This parameter is
valid only if RDB is specified.
|
|
|
|
password: Specify the password of the user name specified on the USER
parameter.
|
|
|
RDBCNNMTH
Specifies the semantics used for CONNECT statements. Refer to the SQL
Reference, SC41-3612 book for more information.
Appendix D. DB2 for AS/400 CL Command Descriptions
611
CVTSQLCPP
|
|
|
|
|
|
|
|
|
|
|
|
|
collection-name: Specify the name of the collection identifier. This value is used
instead of the naming convention specified on the OPTION parameter.
SQLPKG
Specifies the qualified name of the SQL package created on the relational
database specified on the RDB parameter of this command.
|
|
|
|
|
*OBJ: The name of the SQL package is the same as the object name specified
on the OBJ parameter.
|
|
package-name: Specify the name of the SQL package. If the remote system is not
an AS/400 system, no more than 8 characters can be specified.
|
|
|
SAAFLAG
Specifies the IBM SQL flagging function. This parameter flags SQL statements
to verify whether they conform to IBM SQL syntax More information about
which IBM database products IBM SQL syntax is in the DRDA IBM SQL
Reference, SC26-3255-00.
|
|
|
|
|
|
|
*NOFLAG: The precompiler does not check to see whether SQL statements
conform to IBM SQL syntax.
|
|
|
|
|
|
|
|
|
|
|
*NONE: The precompiler does not check to see whether SQL statements
conform to ANSI standards.
|
|
612
CVTSQLCPP
|
|
|
DBGVIEW
This parameter specifies the type of source debug information to be provided
by the SQL precompiler.
|
|
|
*SOURCE: The SQL precompiler provides the source views for the root and if
necessary, SQL INCLUDE statements. A view is provided that contains the
statements generated by the precompiler.
|
|
|
|
|
USRPRF
Specifies the user profile that is used when the compiled program object is run,
including the authority that the program object has for each object in static
SQL statements. The profile of either the program owner or the program user
is used to control which objects can be used by the program object.
|
|
|
*USER: The profile of the user running the program object is used.
|
|
*OWNER: The user profiles of both the program owner and the program user
are used when the program is run.
|
|
DYNUSRPRF
Specifies the user profile to be used for dynamic SQL statements.
|
|
|
*USER: Local dynamic SQL statements are run under the profile of the
programs user. Distributed dynamic SQL statements are run under the profile
of the SQL packages user.
|
|
|
*OWNER: Local dynamic SQL statements are run under the profile of the
programs owner. Distributed dynamic SQL statements are run under the
profile of the SQL packages owner.
|
|
|
SRTSEQ
Specifies the sort sequence table to be used for string comparisons in SQL
statements.
|
|
|
*JOB: The SRTSEQ value for the job is retrieved during the precompile.
|
|
|
*JOBRUN: The SRTSEQ value for the job is retrieved when the program is
run. For distributed applications, SRTSEQ(*JOBRUN) is valid only when
LANGID(*JOBRUN) is also specified.
|
|
*HEX: A sort sequence table is not used. The hexadecimal values of the
characters are used to determine the sort sequence.
|
|
|
*LANGIDSHR: The sort sequence table uses the same weight for multiple
characters, and is the shared-weight sort sequence table associated with the
language specified on the LANGID parameter.
613
CVTSQLCPP
|
|
*LANGIDUNQ: The unique-weight sort table for the language specified on the
LANGID parameter is used.
|
|
The name of the table name can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of hte library to be searched.
|
|
|
|
|
|
|
LANGID
Specifies the language identifier to be used when SRTSEQ(*LANGIDUNQ) or
SRTSEQ(*LANGIDSHR) is specified.
*JOB: The LANGID value for the job is retrieved during the precompile.
|
|
|
*JOBRUN: The LANGID value for the job is retrieved when the program is
run. For distributed applications, LANGID(*JOBRUN) is valid only when
SRTSEQ(*JOBRUN) is also specified.
|
|
OUTPUT
Specifies whether the precompiler listing is generated.
|
|
|
|
The name of the printer file can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
|
|
|
|
|
|
|
|
|
|
|
printer-file-name: Specify the name of the printer device file to which the
precompiler printout is directed.
|
|
|
|
TEXT
Specifies the text that briefly describes the program and the function. More
information on this parameter is in Appendix A, Expanded Parameter
Descriptions in the CL Reference book.
614
CVTSQLCPP
|
|
|
|
|
|
*SRCMBRTXT: The text is taken from the source file member being used as
the text for the output source member. Text can be added or changed for a
database source member by using the Start Source Entry Utility (STRSEU)
command, or by using either the Add Physical File Member (ADDPFM)
command or the Change Physical File Member (CHGPFM) command. If the
source file is an inline file or a device file, the text is blank.
|
|
Example
|
|
|
|
This command runs the SQL precompiler which precompiles the source and stores
the changed source in member PAYROLL in file MYSRCFILE in library MYLIB. No
module or program object is created.
Pgm: B,I
REXX: B,I
Exec
DLTSQLPKG
*LIBL/
SQLPKG(
*CURLIB/
*USRLIBL/
*ALL/
*ALLUSR/
library-name/
(1)
SQL-package-name
generic*-SQL-package name
Notes:
1. All parameters preceding this point can be specified in positional form.
Purpose
The Delete Structured Query Language Package (DLTSQLPKG) command is used
to delete one or more SQL packages.
DLTSQLPKG is a local command and must be used on the AS/400 system where
the SQL package being deleted is located.
To delete an SQL package on a remote system that is also an AS/400 system, use
the Submit Remote Command (SBMRMTCMD) command to run the DLTSQLPKG
command on the remote system.
The user can do the following to delete an SQL package from a remote system that
is not an AS/400 system:
v Use interactive SQL to run the CONNECT and DROP PACKAGE operations.
v Sign on the remote system and use a command local to that system.
Appendix D. DB2 for AS/400 CL Command Descriptions
615
DLTSQLPKG
v Create and run an SQL program that contains a DROP PACKAGE SQL
statement.
Parameters
SQLPKG
Specifies the qualified name of the SQL package being deleted. A specific or
generic SQL package name can be specified.
The name of the SQL Package can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match is
found.
*CURLIB: The current library for the job is searched. If no library is specified
as the current library for the job, the QGPL library is used.
*USRLIBL: Only the libraries in the user portion of the jobs library list are
searched.
*ALL: All libraries in the system, including QSYS, are searched.
*ALLUSR: All user libraries are searched. All libraries with names that do not
begin with the letter Q are searched except for the following:
#CGULIB
#COBLIB
#DFULIB
#DSULIB
#RPGLIB
#SDALIB
#SEULIB
Although the following Qxxx libraries are provided by IBM, they typically
contain user data that changes frequently. Therefore, these libraries are
considered user libraries and are also searched:
QDSNX
QGPL
QGPL38
QPFRDATA
QRCL
QS36F
QUSER38
QUSRADSM
QUSRBRM
QUSRIJS
QUSRINFSKR
QUSRRDARS
QUSRSYS
QUSRVxRxMx
Example
DLTSQLPKG
SQLPKG(JONES)
616
PRTSQLINF
Pgm: B,I
REXX: B,I
Exec
*LIBL/
PRTSQLINF
OBJ(
object-name )
*CURLIB/
library-name/
(1)
OBJTYPE(
*PGM
*SQLPKG
*SRVPGM
Notes:
1. All parameters preceding this point can be specified in positional form.
Purpose
The Print Structured Query Language Information (PRTSQLINF) command prints
information about the embedded SQL statements in a program, SQL package, or
service program. The information includes the SQL statements, the access plans
used during the running of the statement, and a list of the command parameters
used to precompile the source member for the object.
Parameters
OBJ
Specifies the name of the program or SQL package for which you want SQL
information printed.
The name of the object can be qualified by one of the following library values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the program or SQL package for which
you want information printed.
object-name: Specify the name of the program or SQL package for which you
want information printed.
OBJTYPE
Specifies the type of object.
*PGM: The object is a program.
*SQLPKG: The object is an SQL package.
*SRVPGM: The object is a service program.
617
PRTSQLINF
Example
Example 1:
PRTSQLINF
PAYROLL
This command will print information about the SQL statements contained in
program PAYROLL.
Pgm: B,I
REXX: B,I
Exec
*LIBL/
RUNSQLSTM
SRCFILE (
source-file-name
*CURLIB/
library-name/
(1)
SRCMBR ( source-file-member-name
*UR
*CHG
*ALL
*RS
*CS
*NONE
*NC
*RR
COMMIT (
NAMING (
*SYS
*SQL
PROCESS(
*RUN
*SYN
*YES
*OPTIMIZE
*NO
ALWCPYDTA (
ALWBLK (
*READ
*NONE
*ALLREAD
ERRLVL (
10
severity-level
DATFMT (
*JOB
*USA
*ISO
*EUR
*JIS
*MDY
*DMY
*YMD
*JUL
DATSEP (
618
*JOB
'/'
'.'
','
'-'
' '
*BLANK
TIMFMT (
*HMS
*USA
*ISO
*EUR
*JIS
RUNSQLSTM
TIMSEP (
*JOB
':'
'.'
','
' '
*BLANK
)
DECMPT (
*SYSVAL
*JOB
*PERIOD
*COMMA
SRTSEQ (
*JOB
*LANGIDUNQ
*LANGIDSHR
*HEX
*LIBL/
table-name
*CURLIB/
library-name/
LANGID (
*JOB
language-identifier
DFTRDBCOL (
*NONE
collection-name
*NONE
*ANS
FLAGSTD (
SAAFLAG (
*NOFLAG
*FLAG
*LIBL/
QSYSPRT
printer-file-name
PRTFILE (
*CURLIB/
library-name/
SQL-procedure-parameters
TGTRLS (
*CURRENT
VxRxMx
*ENDACTGRP
*ENDMOD
CLOSQLCSR (
OUTPUT (
*NONE
*PRINT
DBGVIEW (
*NONE
*STMT
*LIST
USRPRF (
*NAMING
*OWNER
*USER
DYNUSRPRF (
*USER
*OWNER
619
RUNSQLSTM
DLYPRP (
*NO
*YES
Notes:
1. All parameters preceding this point can be specified in positional form.
Purpose
The Run Structured Query Language Statement (RUNSQLSTM) command
processes a source file of SQL statements.
Parameters
SRCFILE
Specifies the qualified name of the source file that contains the SQL statements
to be run.
The name of the source file can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
source-file-name: Specify the name of the source file that contains the SQL
statements to be run. The source file can be a database file or an inline data
file.
SRCMBR
Specifies the name of the source file member that contains the SQL statements
to be run.
COMMIT
Specifies whether SQL statements in the source file are run under commitment
control.
*CHG or *UR: Specifies the objects referred to in SQL ALTER, CALL,
COMMENT ON, CREATE, DROP, GRANT, LABEL ON, RENAME, and
REVOKE statements and the rows updated, deleted, and inserted are locked
until the end of the unit of work (transaction). Uncommitted changes in other
jobs can be seen.
*ALL or *RS: Specifies the objects referred to in SQL ALTER, CALL,
COMMENT ON, CREATE, DROP, GRANT, LABEL ON, RENAME, and
REVOKE statements and the rows selected, updated, deleted, and inserted are
locked until the end of the unit of work (transaction). Uncommitted changes in
other jobs cannot be seen.
*CS: Specifies the objects referred to in SQL ALTER, CALL, COMMENT ON,
CREATE, DROP, GRANT, LABEL ON, RENAME, and REVOKE statements and
the rows updated, deleted, and inserted are locked until the end of the unit of
work (transaction). A row that is selected, but not updated, is locked until the
next row is selected. Uncommitted changes in other jobs cannot be seen.
620
RUNSQLSTM
*NONE or *NC: Specifies that commitment control is not used. Uncommitted
changes in other jobs can be seen. If the SQL DROP COLLECTION statement
is included in the program, *NONE or *NC must be used. If a relational
database is specified on the RDB parameter and the relational database is on a
system that is not on an AS/400, *NONE or *NC cannot be specified.
*RR: Specifies the objects referred to in SQL ALTER, CALL, COMMENT ON,
CREATE, DROP, GRANT, LABEL ON, RENAME, and REVOKE statements and
the rows selected, updated, deleted, and inserted are locked until the end of
the unit of work (transaction). Uncommitted changes in other jobs cannot be
seen. All tables referred to in SELECT, UPDATE, DELETE, and INSERT
statements are locked exclusively until the end of the unit of work
(transaction).
NAMING
Specifies the naming convention used for naming objects in SQL statements.
*SYS: The system naming convention (library-name/file-name) is used.
*SQL: The SQL naming convention (collection-name.table-name) is used.
PROCESS
Specifies whether SQL statements in the source file member are executed or
syntax-checked only.
*RUN: Statement are syntax-checked and run.
*SYN: Statements are syntax-checked only.
ALWCPYDTA
Specifies whether a copy of the data can be used in a SELECT statement.
*YES: A copy of the data is used only when necessary.
*OPTIMIZE: The system determines whether to use the data retrieved directly
from the database or to use a copy of the data. The decision is based on which
method provides the best performance. If COMMIT is *CHG or *CS and
ALWBLK is not *ALLREAD, or if COMMIT is *ALL or *RR, then a copy of the
data is used only when it is necessary to run a query.
*NO: A copy of the data is not used. If temporary copy of the data is required
to perform the query, an error message is returned.
ALWBLK
Specifies whether the database manager can use record blocking, and the
extent to which blocking can be used for read-only cursors.
*READ: Records are blocked for read-only retrieval of data for cursors when:
v *NONE is specified on the COMMIT parameter, which indicates that
commitment control is not used.
v The cursor is declared with a FOR FETCH ONLY clause or there are no
dynamic statements that could run a positioned UPDATE or DELETE
statement for the cursor.
Specifying *READ can improve the overall performance of queries that meet
the above conditions and retrieve a large number of records.
621
RUNSQLSTM
*NONE: Rows are not blocked for retrieval of data for cursors.
Specifying *NONE:
v Guarantees that the data retrieved is current.
v May reduce the amount of time required to retrieve the first row of data for
a query.
v Stops the database manager from retrieving a block of data rows that is not
used by the program when only the first few rows of a query are retrieved
before the query is closed.
v Can degrade the overall performance of a query that retrieves a large
number of rows.
*ALLREAD Rows are blocked for read-only cursors if *NONE or *CHG is
specified on the COMMIT parameter. All cursors in a program that are not
explicitly able to be updated are opened for read-only processing even though
EXECUTE or EXECUTE IMMEDIATE statements may be in the program.
Specifying *ALLREAD:
v Allows record blocking under commitment control level *CHG in addition to
the blocking allowed for *READ.
v Can improve the performance of almost all read-only cursors in programs,
but limits queries in the following ways:
The Rollback (ROLLBACK) command, a ROLLBACK statement in host
languages, or the ROLLBACK HOLD SQL statement does not reposition a
read-only cursor when *ALLREAD is specified.
Dynamic running of a positioned UPDATE or DELETE statement (for
example, using EXECUTE IMMEDIATE), cannot be used to update a row
in a cursor unless the DECLARE statement for the cursor includes the
FOR UPDATE clause.
ERRLVL
Specifies whether the processing is successful, based on the severity of the
messages generated by the processing of the SQL statements. If errors that are
greater than the value specified on this parameter occur during processing, no
more statements are processed and the statements are rolled back if they are
running under commitment control.
10: Statement processing is stopped when error messages with a severity level
greater than 10 are received.
severity-level: Specify the severity level to be used.
DATFMT
Specifies the format used when accessing date result columns. For input date
strings, the specified value is used to determine whether the date is specified
in a valid format.
Note: An input date string that uses the format *USA, *ISO, *EUR, or *JIS is
always valid.
*JOB: The format specified for the job is used. Use the Display Job (DSPJOB)
command to determine the current date format for the job.
*USA: The United States date format (mm/dd/yyyy) is used.
622
RUNSQLSTM
*ISO: The International Organization for Standardization (ISO) date format
(yyyy-mm-dd) is used.
*EUR: The European date format (dd.mm.yyyy) is used.
*JIS: The Japanese Industrial Standard date format (yyyy-mm-dd) is used.
*MDY: The date format (mm/dd/yy) is used.
*DMY: The date format (dd/mm/yy) is used.
*YMD: The date format (yy/mm/dd) is used.
*JUL: The Julian date format (yy/ddd) is used.
DATSEP
Specifies the separator used when accessing date result columns.
Note: This parameter applies only when *JOB, *MDY, *DMY, *YMD, or *JUL is
specified on the DATFMT parameter.
*JOB: The date separator specified for the job is used. Use the Display Job
(DSPJOB) command to determine the current value for the job.
/: A slash (/) is used.
.: A period (.) is used.
,: A comma (,) is used.
-: A dash (-) is used.
: A blank ( ) is used.
*BLANK: A blank ( ) is used.
TIMFMT
Specifies the format used when accessing time result columns. For input time
strings, the specified value is used to determine whether the time is specified
in a valid format.
Note: An input date string that uses the format *USA, *ISO, *EUR, or *JIS is
always valid.
*HMS: The hh:mm:ss format is used.
*USA: The United States time format hh:mm xx is used, where xx is AM or
PM.
*ISO: The International Organization for Standardization (ISO) time format
hh.mm.ss is used.
*EUR: The European time format hh.mm.ss is used.
*JIS: The Japanese Industrial Standard time format hh:mm:ss is used.
623
RUNSQLSTM
TIMSEP
Specifies the separator used when accessing time result columns.
Note: This parameter applies only when *HMS is specified on the TIMFMT
parameter.
*JOB: The time separator specified for the job is used. Use the Display Job
(DSPJOB) command to determine the current value for the job.
:: A colon (:) is used.
.: A period (.) is used.
,: A comma (,) is used.
: A blank ( ) is used.
*BLANK: A blank ( ) is used.
DECMPT
Specifies the decimal point value used for numeric constants in SQL
statements.
*JOB: The value used as the decimal point for numeric constants in SQL is the
representation of decimal point specified by the job running the statement.
*SYSVAL: The QDECFMT system value is used as the decimal point.
*PERIOD: A period represents the decimal point.
*COMMA: A comma represents the decimal point.
SRTSEQ
Specifies the sort sequence table to be used for string comparisons in SQL
statements.
*JOB: The LANGID value for the job is retrieved.
*LANGIDSHR: The sort sequence table uses the same weight for multiple
characters, and is the shared-weight sort sequence table associated with the
language specified on the LANGID parameter.
*LANGIDUNQ: The unique-weight sort table for the language specified on the
LANGID parameter is used.
*HEX: A sort sequence table is not used. The hexadecimal values of the
characters are used to determine the sort sequence.
The name of the table name can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
624
RUNSQLSTM
table-name: Specify the name of the sort sequence table to be used.
LANGID
Specifies the language identifier to be used when SRTSEQ(*LANGIDUNQ) or
SRTSEQ(*LANGIDSHR) is specified.
*JOB: The LANGID value for the job is retrieved during the precompile.
language-identifier: Specify a language identifier.
DFTRDBCOL
Specifies the collection name used for the unqualified names of tables, views,
indexes, and SQL packages. This parameter applies only to static SQL
statements.
*NONE: The naming convention defined on the OPTION parameter is used.
collection-name: Specify the name of the collection identifier. This value is used
instead of the naming convention specified on the OPTION parameter.
FLAGSTD
Specifies the American National Standards Institute (ANSI) flagging function.
This parameter flags SQL statements to verify whether they conform to the
following standards.
ANSI X3.135-1992 entry
ISO 9075-1992 entry
FIPS 127.2 entry
*NONE: The SQL statements are not checked to determine whether they
conform to ANSI standards.
*ANS: The SQL statements are checked to determine whether they conform to
ANSI standards.
SAAFLAG
Specifies the IBM SQL flagging function. This parameter flags SQL statements
to verify whether they conform to IBM SQL syntax More information about
which IBM database products IBM SQL syntax is in the DRDA IBM SQL
Reference, SC26-3255-00.
*NOFLAG: The SQL statements are not checked to determine whether they
conform to IBM SQL syntax.
*FLAG: The SQL statements are checked to determine whether they conform
to IBM SQL syntax.
PRTFILE
Specifies the qualified name of the printer device file to which the
RUNSQLSTM printout is directed. The file must have a minimum length of
132 bytes. If a file with a record length of less than 132 bytes is specified,
information is lost.
The name of the printer file can be qualified by one of hte following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
Appendix D. DB2 for AS/400 CL Command Descriptions
625
RUNSQLSTM
library-name: Specify the name of the library to be searched.
QSYSPRT: If a file name is not specified, the RUNSQLSTM printout is directed
to the IBM-supplied printer file QSYSPRT.
printer-file-name: Specify the name of the printer device file to which the
RUNSQLSTM printout is directed.
626
RUNSQLSTM
*NONE: The precompiler listing is not generated.
*PRINT: The precompiler listing is generated.
DBGVIEW
Specifies the type of source debug information to be provided by the SQL
precompiler.
*NONE: The source view will not be generated.
*STMT: Allows the compiled module to be debugged using program statement
numbers and symbolic identifiers.
*LIST: Generates the listing view for debugging the compiled module object.
USRPRF
Specifies the user profile that is used when the compiled program object is run,
including the authority that the program object has for each object in static
SQL statements. The profile of either the program owner or the program user
is used to control which objects can be used by the program object.
*NAMING: The user profile is determined by the naming convention. If the
naming convention is *SQL, USRPRF(*OWNER) is used. If the naming
convention is *SYS, USRPRF(*USER) is used.
*USER: The profile of the user running the program object is used.
*OWNER: The user profiles of both the program owner and the program user
are used when the program is run.
DYNUSRPRF
Specifies the user profile to be used for dynamic SQL statements.
*USER: For local, dynamic SQL statements run under the user of the
programs user. For distributed, dynamic SQL statements run under the profile
of the SQL packages user.
*OWNER: For local, dynamic SQL statements run under the profile of the
programs owner. For distributed, dynamic SQL statements run under the
profile of the SQL packages owner.
DLYPRP
Specifies whether the dynamic statement validation for a PREPARE statement
is delayed until an OPEN, EXECUTE, or DESCRIBE statement is run. Delaying
validation improves performance by eliminating redundant validation.
*NO: Dynamic statement validation is not delayed. When the dynamic
statement is prepared, the access plan is validated. When the dynamic
statement is used in an OPEN or EXECUTE statement, the access plan is
revalidated. Because the authority or the existence of objects referred to by the
dynamic statement may change, you must still check the SQLCODE or
SQLSTATE after issuing the OPEN or EXECUTE statement to ensure that the
dynamic statement is still valid.
*YES: Dynamic statement validation is delayed until the dynamic statement is
used in an OPEN, EXECUTE, or DESCRIBE SQL statement. When the dynamic
statement is used, the validation is completed and an access plan is built. If
you specify *YES on this parameter, you should check the SQLCODE and
Appendix D. DB2 for AS/400 CL Command Descriptions
627
RUNSQLSTM
SQLSTATE after running an OPEN, EXECUTE, or DESCRIBE statement to
ensure that the dynamic statement is valid.
Note: If you specify *YES, performance is not improved if the INTO clause is
used on the PREPARE statement or if a DESCRIBE statement uses the
dynamic statement before an OPEN is issued for the statement.
Example
RUNSQLSTM
SRCFILE(MYLIB/MYFILE)
SRCMBR(MYMBR)
This command processes the SQL statements in member MYMBR found in file
MYFILE in library MYLIB.
Pgm: I
REXX: I
Exec
STRSQL
COMMIT(
*NC
*NONE
*CHG
*UR
*CS
*RS
*ALL
*RR
NAMING(
*SYS
*SQL
PROCESS(
*RUN
*VLD
*SYN
LIBOPT(
*LIBL
*CURLIB
*USRLIBL
*ALL
*ALLUSR
library-name
(1)
LISTTYPE(
*ALL
*SQL
REFRESH(
*ALWAYS
*FORWARD
ALWCPYDTA(
628
*YES
*OPTIMIZE
*NO
DATFMT(
*JOB
*USA
*ISO
*EUR
*JIS
*MDY
*DMY
*YMD
*JUL
STRSQL
(2)
*JOB
*BLANK
/
.
,
-
DATSEP(
TIMFMT(
*HMS
*USA
*ISO
*EUR
*JIS
(3)
*JOB
*BLANK
:
.
,
TIMSEP(
DECPNT(
*SYSVAL
*PERIOD
*COMMA
*JOB
(4)
*NONE
*C
*CBL
*PLI
*RPG
*FTN
PGMLNG(
(5)
(6)
SQLSTRDLM(
*QUOTESQL
*APOSTSQL
SRTSEQ(
*JOB
*JOBRUN
*LANGIDUNQ
*LANGIDSHR
*HEX
*LIBL/
table-name
*CURLIB/
library-name/
LANGID(
*JOB
*JOBRUN
language-ID
Notes:
1. All parameters preceding this point can be specified in positional form.
2. DATSEP is only valid when *MDY, *DMY, *YMD, or *JUL is specified on the
DATFMT parameter.
3. TIMSEP is only valid when TIMFMT(*HMS) is specified.
4. PGMLNG and SQLSTRDLM are valid only when PROCESS(*SYN) is specified.
629
STRSQL
5. PGMLNG and SQLSTRDLM are valid only when PROCESS(*SYN) is specified.
6. SQLSTRDLM is valid only when PGMLNG(*CBL) is specified.
Purpose
The Start Structured Query Language (STRSQL) command starts the interactive
Structured Query Language (SQL) program. The program starts the statement
entry of the interactive SQL program which immediately shows the Enter SQL
Statements display. This display allows the user to build, edit, enter, and run an
SQL statement in an interactive environment. Messages received during the
running of the program are shown on this display.
Parameters
COMMIT
Specifies whether the SQL statements are run under commitment control.
*NONE or *NC: Specifies that commitment control is not used. Uncommitted
changes in other jobs can be seen. If the SQL DROP COLLECTION statement
is included in the program, *NONE or *NC must be used. If a relational
database is specified on the RDB parameter and the relational database is on a
system that is not on an AS/400, *NONE or *NC cannot be specified.
*CHG or *UR: Specifies the objects referred to in SQL ALTER, CALL,
COMMENT ON, CREATE, DROP, GRANT, LABEL ON, RENAME, and
REVOKE statements and the rows updated, deleted, and inserted are locked
until the end of the unit of work (transaction). Uncommitted changes in other
jobs can be seen.
*CS: Specifies the objects referred to in SQL ALTER, CALL, COMMENT ON,
CREATE, DROP, GRANT, LABEL ON, RENAME, and REVOKE statements and
the rows updated, deleted, and inserted are locked until the end of the unit of
work (transaction). A row that is selected, but not updated, is locked until the
next row is selected. Uncommitted changes in other jobs cannot be seen.
*ALL or *RS: Specifies the objects referred to in SQL ALTER, CALL,
COMMENT ON, CREATE, DROP, GRANT, LABEL ON, RENAME, and
REVOKE statements and the rows selected, updated, deleted, and inserted are
locked until the end of the unit of work (transaction). Uncommitted changes in
other jobs cannot be seen.
*RR: Specifies the objects referred to in SQL ALTER, CALL, COMMENT ON,
CREATE, DROP, GRANT, LABEL ON, RENAME, and REVOKE statements and
the rows selected, updated, deleted, and inserted are locked until the end of
the unit of work (transaction). Uncommitted changes in other jobs cannot be
seen. All tables referred to in SELECT, UPDATE, DELETE, and INSERT
statements are locked exclusively until the end of the unit of work
(transaction).
|
|
Note: The default for this parameter for the CRTSQLXXX commands (when
XXX=CI, CPPI, CBL, FTN, PLI, CBLI, RPG or RPGI) is *CHG.
NAMING
Specifies the naming convention used for naming objects in SQL statements.
*SYS: The system naming convention (library-name/file-name) is used.
630
STRSQL
*SQL: The SQL naming convention (collection-name.table-name) is used.
PROCESS
Specifies the values used to process the SQL statements.
*RUN: The statements are syntax checked, data checked, and then run.
*VLD: The statements are syntax checked and data checked, but not run.
*SYN: The statements are syntax checked only.
LIBOPT
Specifies which collections and libraries are used as a basis for building a
collection list when the F4, F16, F17, or F18 function key is pressed.
The name of the collection list can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
*USRLIBL: Only the libraries in the user portion of the jobs library list are
searched.
*ALL: All libraries in the system, including QSYS, are searched.
*ALLUSR: All user libraries are searched. All libraries with names that do
not begin with the letter Q are searched except for the following:
#CGULIB
#COBLIB
#DFULIB
#DSULIB
#RPGLIB
#SDALIB
#SEULIB
Although the following Qxxx libraries are provided by IBM, they typically
contain user data that changes frequently. Therefore, these libraries are
considered user libraries and are also searched:
QDSNX
QGPL
QGPL38
QPFRDATA
QRCL
QS36F
QUSER38
QUSRADSM
QUSRBRM
QUSRIJS
QUSRINFSKR
QUSRRDARS
QUSRSYS
QUSRVxRxMx
631
STRSQL
*FORWARD: Data is refreshed only during forward scrolling to the end of the
data for the first time. When scrolling backward, a copy of the data already
viewed is shown.
ALWCPYDTA
Specifies whether a copy of the data can be used in a SELECT statement. If
COMMIT(*ALL) is specified, SQL run time ignores the ALWCPYDTA value
and uses current data.
*YES: A copy of the data is used when necessary.
*OPTIMIZE: The system determines whether to use the data retrieved from
the database or to use a copy of the data. The determination is based on which
will provide the best performance.
*NO: A copy of the data is not allowed. If a temporary copy of the data is
required to perform the query, an error message is returned.
DATFMT
Specifies the date format used in SQL statements.
*JOB: The format specified on the job attribute DATFMT is used.
*USA: The United States date format (mm/dd/yyyy) is used.
*ISO: The International Standards Organization date format (yyyy-mm-dd) is
used.
*EUR: The European date format (dd.mm.yyyy) is used.
*JIS: The Japanese Industry Standard Christian Era date format (yyyy-mm-dd)
is used.
*MDY: The month, day, and year date format (mm/dd/yy) is used.
*DMY: The day, month, and year date format (dd/mm/yy) is used.
*YMD: The year, month, and day date format (yy/mm/dd) is used.
*JUL: The Julian date format (yy/ddd) is used.
DATSEP
Specifies the date separator used in SQL statements.
*JOB: The date separator specified on the job attribute is used. If the user
specifies *JOB on a new interactive SQL session, the current value is stored and
used. Later changes to the jobs date separator are not detected by interactive
SQL.
*BLANK: A blank ( ) is used.
/: A slash (/) is used.
.: A period (.) is used.
,: A comma (,) is used.
632
STRSQL
-: A dash (-) is used.
: A blank ( ) is used.
TIMFMT
Specifies the time format used in SQL statements.
*HMS: The Hour-Minute-Second time format (hh:mm:ss) is used.
*USA: The United States time format (hh:mm xx, where xx is AM or PM) is
used.
*ISO: The International Standards Organization time format (hh.mm.ss) is
used.
*EUR: The European time format (hh.mm.ss) is used.
*JIS: The Japanese Industry Standard Christian Era time format (hh:mm:ss) is
used.
TIMSEP
Specifies the time separator used in SQL statements.
*JOB: The time separator specified on the job attribute is used. If the user
specifies *JOB on a new interactive SQL session, the current value is stored and
used. Later changes to the jobs time separator are not detected by interactive
SQL.
*BLANK: A blank ( ) is used.
:: A colon (:) is used.
.: A period (.) is used.
,: A comma (,) is used.
: A blank ( ) is used.
DECPNT
Specifies the kind of decimal point to use.
*JOB: The value used as the decimal point for numeric constants in SQL is the
representation of decimal point specified for the job running the statement.
*SYSVAL: The decimal point is extracted from the system value. If the user
specifies *SYSVAL on a new interactive SQL session, the current value is stored
and used. Later changes to the systems time separator are not detected by
interactive SQL.
*PERIOD: A period represents the decimal point.
*COMMA: A comma represents the decimal point.
PGMLNG
Specifies which program language syntax rules to use. To use this parameter,
*SYN must be selected at the PROCESS parameter.
*NONE: No specific languages syntax check rules are used.
Appendix D. DB2 for AS/400 CL Command Descriptions
633
STRSQL
The supported languages are:
*C: Syntax checking is done according to the C language syntax rules.
*CBL: Syntax checking is done according to the COBOL language syntax rules.
*PLI: Syntax checking is done according to the PL/I language syntax rules.
*RPG: Syntax checking is done according to the RPG language syntax rules.
*FTN: Syntax checking is done according to the FORTRAN language syntax
rules.
SQLSTRDLM
Specifies the SQL string delimiter. Use of this parameter requires using the
COBOL (*CBL) character set.
*QUOTESQL: A quotation mark represents the SQL string delimiter.
*APOSTSQL: An apostrophe represents the SQL string delimiter.
SRTSEQ
Specifies the sort sequence table to be used for string comparisons in SQL
statements on the Enter SQL Statements display.
*JOB: The SRTSEQ value for the job is retrieved.
*JOBRUN: The SRTSEQ value for the job is retrieved each time the user starts
interactive SQL.
*LANGIDUNQ: The unique-weight sort table for the language specified on the
LANGID parameter is used.
*LANGIDSHR: The shared-weight sort table for the language specified on the
LANGID parameter is used.
*HEX: A sort sequence table is not used. The hexadecimal values of the
characters are used to determine the sort sequence.
The name of the table name can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
table-name: Specify the name of the sort sequence table to be used with the
interactive SQL session.
LANGID
Specifies the language identifier to be used when SRTSEQ(*LANGIDUNQ) or
SRTSEQ(*LANGIDSHR) is specified.
*JOB: The LANGID value for the job is retrieved.
634
STRSQL
*JOBRUN: The LANGID value for the job is retrieved each time interactive
SQL is started.
language-ID: Specify the language identifier to be used.
Example
STRSQL PROCESS(*SYN) NAMING(*SQL)
DECPNT(*COMMA) PGMLNG(*CBL)
SQLSTRDLM(*APOSTSQL)
This command starts an interactive SQL session that checks only the syntax of SQL
statements. The character set used by the syntax checker uses the COBOL language
syntax rules. The SQL naming convention is used for this session. The decimal
point is represented by a comma, and the SQL string delimiter is represented by an
apostrophe.
635
STRSQL
636
Access plans
The SQL C for AS/400 precompiler generates access plan structures that are for use
with non-ILE programs.
637
Pgm: B,I
REXX: B,I
Exec
*CURLIB/
CRTSQLC
PGM(
program-name )
library-name/
*LIBL/
QCSRC
source-file-name
SRCFILE(
*CURLIB/
library-name/
(1)
SRCMBR(
*PGM
source-file-member-name
OPTION(
OPTION Details
)
TGTRLS(
*CURRENT
*PRV
VxRxMx
*LIBL/
*SRCFILE
source-file-name
INCFILE(
*CURLIB/
library-name/
COMMIT(
638
*CHG
*ALL
*CS
*NONE
CLOSQLCSR(
*ENDPGM
*ENDSQL
*ENDJOB
ALWCPYDTA(
*YES
*OPTIMIZE
*NO
*READ
*NONE
*ALLREAD
ALWBLK(
*NO
*YES
DLYPRP(
10
severity-level
GENLVL(
*SRCFILE
left-right
MARGINS(
*JOB
*USA
*ISO
*EUR
*JIS
*MDY
*DMY
*YMD
*JUL
DATFMT(
*JOB
'/'
'.'
','
'-'
' '
*BLANK
DATSEP(
*HMS
*USA
*ISO
*EUR
*JIS
TIMFMT(
*JOB
':'
'.'
','
' '
*BLANK
TIMSEP(
REPLACE(
*YES
*NO
RDB(
*NONE
relational-database-name
USER(
*CURRENT
user-name
PASSWORD(
*NONE
password
RDBCNNMTH(
*DUW
*RUW
DFTRDBCOL(
*NONE
collection-name
*PGMLIB/
SQLPKG(
*PGM
package-name
library-name/
Appendix E. Using the C for AS/400 and FORTRAN for AS/400 Precompilers
639
*NOFLAG
*FLAG
SAAFLAG(
FLAGSTD(
*NONE
*ANS
*LIBL/
QSYSPRT
printer-file-name
PRTFILE(
*CURLIB/
library-name/
*JOB
*JOBRUN
*LANGIDUNQ
*LANGIDSHR
*HEX
*LIBL/
SRTSEQ(
table-name
*CURLIB/
library-name/
*JOB
*JOBRUN
language-ID
LANGID(
*USER
*OWNER
DYNUSRPRF(
QTEMP/
QSQLTEMP
source-file-name
TOSRCFILE
*LIBL/
*CURLIB/
library-name/
TEXT(
*SRCMBRTXT
*BLANK
'description'
OPTION Details
*NOSRC
*NOSOURCE
*NOXREF
*NOGEN
*JOB
*SYS
*PERIOD
*SYSVAL
*COMMA
*SQL
*SOURCE
*SRC
*XREF
*NOSECLVL
*NODEBUG
*NOCNULRQD
*NOLSTDBG
*SECLVL
*DEBUG
*CNULRQD
*LSTDBG
Notes:
1. All parameters preceding this point can be specified in positional form.
640
Purpose
The Create Structured Query Language C (CRTSQLC) command calls the
Structured Query Language (SQL) precompiler which precompiles C source
containing SQL statements, produces a temporary source member.
Note: The C for AS/400 Compiler is no longer supported. This CRTSQLC
command is provided for use by other non-IBM C compilers. The supported
IBM compiler is ILE C for AS/400 and the SQL precompiler command is
CRTSQLCI.
Parameters
PGM
Specifies the qualified name of the compiled program.
The name of the compiled C program can be qualified by one of the following
library values:
*CURLIB: The compiled C program is created in the current library for the
job. If no library is specified as the current library for the job, the QGPL
library is used.
library-name: Specify the name of the library where the compiled C program
is created.
program-name: Specify the name of the compiled C program.
SRCFILE
Specifies the qualified name of the source file that contains the C source with
SQL statements.
The name of the source file can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
QCSRC: If the source file name is not specified, the IBM-supplied source file
QCSRC contains the C source.
source-file-name: Specify the name of the source file that contains the C source.
SRCMBR
Specifies the name of the source file member that contains the C source. This
parameter is specified only if the source file name in the SRCFILE parameter is
a database file. If this parameter is not specified, the PGM name specified on
the PGM parameter is used.
*PGM: Specifies that the C source is in the member of the source file that has
the same name as that specified on the PGM parameter.
source-file-member-name: Specify the name of the member that contains the C
source.
OPTION
Specifies whether one or more of the following options are used when the C
Appendix E. Using the C for AS/400 and FORTRAN for AS/400 Precompilers
641
642
Appendix E. Using the C for AS/400 and FORTRAN for AS/400 Precompilers
643
644
*CS: Specifies the objects referred to in SQL ALTER, COMMENT ON, CREATE,
DROP, GRANT, LABEL ON, and REVOKE statements and the rows updated,
deleted, and inserted are locked until the end of the unit of work (transaction).
A row that is selected, but not updated, is locked until the next row is selected.
Uncommitted changes in other jobs cannot be seen.
*NONE: Specifies that commitment control is not used. Uncommitted changes
in other jobs can be seen. If the SQL DROP COLLECTION statement is
included in the program, *NONE must be used. If a relational database is
specified on the RDB parameter and the relational database is on a system that
is not on an AS/400, *NONE cannot be specified.
CLOSQLCSR
Specifies when SQL cursors are implicitly closed, SQL prepared statements are
implicitly discarded, and LOCK TABLE locks are released. SQL cursors are
explicitly closed when you issue the CLOSE, COMMIT, or ROLLBACK
(without HOLD) SQL statements.
*ENDPGM: SQL cursors are closed and SQL prepared statements are
discarded when the program ends. LOCK TABLE locks are released when the
first SQL program on the call stack ends.
*ENDSQL: SQL cursors remain open between calls and can be fetched without
running another SQL OPEN. One of the programs higher on the call stack
must have run at least one SQL statement. SQL cursors are closed, SQL
prepared statements are discarded, and LOCK TABLE locks are released when
the first SQL program on the call stack ends. If *ENDSQL is specified for a
program that is the first SQL program called (the first SQL program on the call
stack), the program is treated as if *ENDPGM was specified.
*ENDJOB: SQL cursors remain open between calls and can be fetched without
running another SQL OPEN. The programs higher on the call stack do not
need to have run SQL statements. SQL cursors are left open, SQL prepared
statements are preserved, and LOCK TABLE locks are held when the first SQL
program on the call stack ends. SQL cursors are closed, SQL prepared
statements are discarded, and LOCK TABLE locks are released when the job
ends.
ALWCPYDTA
Specifies whether a copy of the data can be used in a SELECT statement.
*YES: A copy of the data is used only when necessary.
*OPTIMIZE: The system determines whether to use the data retrieved directly
from the database or to use a copy of the data. The decision is based on which
method provides the best performance. If COMMIT is *CHG or *CS and
ALWBLK is not *ALLREAD, or if COMMIT is *ALL or *RR, then a copy of the
data is used only when it is necessary to run a query.
*NO: A copy of the data is not used. If a temporary copy of the data is
required to perform the query, an error message is returned.
ALWBLK
Specifies whether the database manager can use record blocking, and the
extent to which blocking can be used for read-only cursors.
*READ: Records are blocked for read-only retrieval of data for cursors when:
Appendix E. Using the C for AS/400 and FORTRAN for AS/400 Precompilers
645
646
Note: If you specify *YES, performance is not improved if the INTO clause is
used on the PREPARE statement or if a DESCRIBE statement uses the
dynamic statement before an OPEN is issued for the statement.
GENLVL
Specifies the severity level at which the create operation fails. If errors occur
that have a severity level greater than or equal to this value, the operation
ends.
10: The default severity level is 10.
severity-level: Specify a value ranging from 0 through 40.
MARGINS
Specifies the part of the precompiler input record that contains source text.
*SRCFILE:The file member margin values that you specified on the SRCMBR
parameter are used. If the member is an SQLC, SQLCLE, C, or CLE source
type, the margin values are the values specified on the source entry utility
(SEU) services display. If the member is a different source type, the margin
values are the default values of 1 and 80.
Element 1: Left Margin
left: Specify the beginning position for the statements. Valid values range from
1 through 80.
Element 2: Right Margin
right: Specify the ending position for the statements. Valid values range from 1
through 80.
DATFMT
Specifies the format used when accessing date result columns. All output date
fields are returned in the specified format. For input date strings, the specified
value is used to determine whether the date is specified in a valid format.
Note: An input date string that uses the format *USA, *ISO, *EUR, or *JIS is
always valid.
If a relational database is specified on the RDB parameter and the
database is on a system that is not an AS/400 system, then *USA, *ISO,
*EUR, or *JIS must be specified.
*JOB: The format specified for the job is used. Use the Display Job (DSPJOB)
command to determine the current date format for the job.
*USA: The United States date format (mm/dd/yyyy) is used.
*ISO: The International Organization for Standardization (ISO) date format
(yyyy-mm-dd) is used.
*EUR: The European date format (dd.mm.yyyy) is used.
*JIS: The Japanese Industrial Standard date format (yyyy-mm-dd) is used.
*MDY: The date format (mm/dd/yy) is used.
Appendix E. Using the C for AS/400 and FORTRAN for AS/400 Precompilers
647
648
*JOB: The time separator specified for the job at precompile time is used. Use
the Display Job (DSPJOB) command to determine the current value for the job.
:: A colon (:) is used.
.: A period (.) is used.
,: A comma (,) is used.
: A blank ( ) is used.
*BLANK: A blank ( ) is used.
REPLACE
Specifies whether a new program or SQL package is created when a program
or SQL package of the same name exists in the same library. The value of this
parameter is passed to the C command.More information on this parameter is
in Appendix A, Expanded Parameter Descriptions in the CL Reference
(Abridged) book.
*YES: A new program or SQL package is created, and any existing program or
SQL package of the same name and type in the specified library is moved to
QRPLOBJ.
*NO: A new program or SQL package is not created if an object of the same
name and type already exists in the specified library.
RDB
Specifies the name of the relational database where the SQL package object is
created.
*NONE: An SQL package object is not created. The program object is not a
distributed program and the Create Structured Query Language Package
(CRTSQLPKG) command cannot be used.
relational-database-name: Specify the name of the relational database where the
new SQL package object is to be created. When the name of the local relational
database is specified, the program created is still a distributed SQL program.
The SQL statements will access the local database.
USER
Specifies the user name sent to the remote system when starting the
conversation. This parameter is valid only when RDB is specified.
*CURRENT: The user profile under which the current job is running is used.
user-name: Specify the user name to be used for the application server job.
PASSWORD
Specifies the password to be used on the remote system. This parameter is
valid only if RDB is specified.
*NONE: No password is sent. If this value is specified, USER(*CURRENT)
must also be specified.
password: Specify the password of the user name specified on the USER
parameter.
Appendix E. Using the C for AS/400 and FORTRAN for AS/400 Precompilers
649
RDBCNNMTH
Specifies the semantics used for CONNECT statements. Refer to the SQL
Reference, SC41-3612 book for more information.
*DUW: CONNECT (Type 2) semantics are used to support distributed unit of
work. Consecutive CONNECT statements to additional relational databases do
not result in disconnection of previous connections.
*RUW: CONNECT (Type 1) semantics are used to support remote unit of
work. Consecutive CONNECT statements result in the previous connection
being disconnected before a new connection is established.
DFTRDBCOL
Specifies the collection name used for the unqualified names of tables, views,
indexes, and SQL packages. This parameter applies only to static SQL
statements.
*NONE: The naming convention defined on the OPTION parameter is used.
collection-name: Specify the name of the collection identifier. This value is used
instead of the naming convention specified on the OPTION parameter.
SQLPKG
Specifies the qualified name of the SQL package created on the relational
database specified on the RDB parameter of this command.
The possible library values are:
*PGMLIB: The package is created in the library with the same name as the
library containing the program.
library-name: Specify the name of the library where the package is created.
*PGM: The name of the SQL package is the same as the program name.
package-name: Specify the name of the SQL package. If the remote system is not
an AS/400 system, no more than 8 characters can be specified.
SAAFLAG
Specifies the IBM SQL flagging function. This parameter flags SQL statements
to verify whether they conform to IBM SQL syntax More information about
which IBM database products IBM SQL syntax is in the DRDA IBM SQL
Reference, SC26-3255-00.
*NOFLAG: The precompiler does not check to see whether SQL statements
conform to IBM SQL standards.
*FLAG: The precompiler checks to see whether SQL statements conform to
IBM SQL standards.
FLAGSTD
Specifies the American National Standards Institute (ANSI) flagging function.
This parameter flags SQL statements to verify whether they conform to the
following standards.
ANSI X3.135-1992 entry
ISO 9075-1992 entry
FIPS 127.2 entry
*NONE: The precompiler does not check to see whether SQL statements
conform to ANSI standards.
650
Appendix E. Using the C for AS/400 and FORTRAN for AS/400 Precompilers
651
LANGID
Specifies the language identifier to be used when SRTSEQ(*LANGIDUNQ) or
SRTSEQ(*LANGIDSHR) is specified.
*JOB: The LANGID value for the job is received during the precompile.
*JOBRUN: The LANGID value for the job is retrieved when the program is
run. For distributed applications, LANGID(*JOBRUN) is valid only when
SRTSEQ(*JOBRUN) is also specified.
language-id: Specify a language identifier to be used by the program.
DYNUSRPRF
Specifies the user profile used for dynamic SQL statements.
*USER: Local dynamic SQL statements are run under the user profile of the
job. Distributed dynamic SQL statements are run under the user profile of the
application server job.
*OWNER: Local dynamic SQL statements are run under the user profile of the
programs owner. Distributed dynamic SQL statements are run under the user
profile of the SQL packages owner.
TOSRCFILE
Specifies the qualified name of the source file that is to contain the output
source member that has been processed by the SQL precompiler. If the
specified source file is not found, it will be created. The output member will
have the same name as the name that is specified for the SRCMBR parameter.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
source-file-name: Specify the name of the source file to contain the output source
member.
TEXT
Specifies the text that briefly describes the function. More information on this
parameter is in Appendix A, Expanded Parameter Descriptions in the CL
Reference book.
*SRCMBRTXT: The text is taken from the source file member being used to
create the FORTRAN program. Text can be added or changed for a database
source member by using the Start Source Entry Utility (STRSEU) command, or
by using either the Add Physical File Member (ADDPFM) or Change Physical
File Member (CHGPFM) command. If the source file is an inline file or a
device file, the text is blank.
652
Example
CRTSQLC
PAYROLL
TEXT('Payroll Program')
This command runs the SQL precompiler which precompiles the source and stores
the changed source in member PAYROLL in file QSQLTEMP in library QTEMP.
Pgm: B,I
REXX: B,I
Exec
*CURLIB/
CRTSQLFTN
PGM(
program-name )
library-name/
*LIBL/
QFTNSRC
source-file-name
SRCFILE(
*CURLIB/
library-name/
(1)
SRCMBR(
*PGM
source-file-member-name
OPTION(
OPTION Details
)
TGTRLS(
*CURRENT
*PRV
VxRxMx
*LIBL/
INCFILE(
*SRCFILE
source-file-name
*CURLIB/
library-name/
Appendix E. Using the C for AS/400 and FORTRAN for AS/400 Precompilers
653
*UR
*CHG
*ALL
*RS
*CS
*NONE
*NC
*RR
COMMIT(
CLOSQLCSR(
)
*ENDPGM
*ENDSQL
*ENDJOB
*YES
*OPTIMIZE
*NO
ALWCPYDTA(
ALWBLK(
*READ
*NONE
*ALLREAD
*NO
*YES
DLYPRP(
10
severity-level
GENLVL(
*JOB
*USA
*ISO
*EUR
*JIS
*MDY
*DMY
*YMD
*JUL
DATFMT(
*JOB
'/'
'.'
','
'-'
' '
*BLANK
DATSEP(
*HMS
*USA
*ISO
*EUR
*JIS
TIMFMT(
*JOB
':'
'.'
','
' '
*BLANK
TIMSEP(
*YES
*NO
REPLACE(
RDB(
*LOCAL
relational-database-name
*NONE
USER(
*CURRENT
user-name
PASSWORD(
654
*NONE
password
RDBCNNMTH(
*DUW
*RUW
*NONE
collection-name
DFTRDBCOL(
*PGMLIB/
*PGM
package-name
SQLPKG(
library-name/
*NOFLAG
*FLAG
SAAFLAG(
FLAGSTD(
*NONE
*ANS
*LIBL/
QSYSPRT
printer-file-name
PRTFILE(
*CURLIB/
library-name/
*JOB
*JOBRUN
*LANGIDUNQ
*LANGIDSHR
*HEX
*LIBL/
SRTSEQ(
table-name
*CURLIB/
library-name/
*JOB
*JOBRUN
language-ID
LANGID(
USRPRF(
*NAMING
*OWNER
*USER
*USER
*OWNER
DYNUSRPRF(
QTEMP/
QSQLTEMP
source-file-name
TOSRCFILE(
*LIBL/
*CURLIB/
library-name/
TEXT(
*SRCMBRTXT
*BLANK
'description'
OPTION Details
*NOSRC
*NOSOURCE
*NOXREF
*GEN
*PERIOD
*SYS
*XREF
*NOGEN
*JOB
*SYSVAL
*COMMA
*SQL
*SOURCE
*SRC
Appendix E. Using the C for AS/400 and FORTRAN for AS/400 Precompilers
655
*NOSECLVL
*NODEBUG
*SECLVL
*DEBUG
Notes:
1. All parameters preceding this point can be specified in positional form.
Purpose
The Create Structured Query Language FORTRAN (CRTSQLFTN) command calls
the Structured Query Language (SQL) precompiler which precompiles FORTRAN
source containing SQL statements, produces a temporary source member, and then
optionally calls the FORTRAN compiler to compile the program.
Parameters
PGM
Specifies the qualified name of the compiled program.
The name of the compiled FORTRAN program can be qualified by one of the
following library values:
*CURLIB: The compiled FORTRAN program is created in the current library
for the job. If no library is specified as the current library for the job, the QGPL
library is used.
library-name: Specify the name of hte library where the compiled FORTRAN
program is created.
program-name: Specify the name of the compiled FORTRAN program.
SRCFILE
Specifies the qualified name of the source file that contains the FORTRAN
source with SQL statements.
The name of the source file can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
QFTNSRC: If the source file name is not specified, the IBM-supplied source
file QFTNSRC contains the FORTRAN source.
source-file-name: Specify the name of the source file that contains the FORTRAN
source.
SRCMBR
Specifies the name of the source file member that contains the C source. This
parameter is specified only if the source file name in the SRCFILE parameter is
a database file. If this parameter is not specified, the PGM name specified on
the PGM parameter is used.
*PGM: Specifies that the FORTRAN source is in the member of the source file
that has the same name as that specified on the PGM parameter.
656
657
658
INCFILE
Specifies the qualified name of the source file that contains members included
in the program with any SQL INCLUDE statement.
The name of the source file can be qualified by one of the following library
values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
*SRCFILE: The qualified source file specified in the SRCFILE parameter
contains the source file members specified on any SQL INCLUDE statement.
source-file-name: Specify the name of the source file that contains the source file
members specified on any SQL INCLUDE statement. The record length of the
source file the user specifies here must be no less than the record length of the
source file specified on the SRCFILE parameter.
COMMIT
Specifies whether SQL statements in the compiled program are run under
commitment control. Files referred to in the host language source are not
affected by this option. Only SQL tables, SQL views, and SQL packages
referred to in SQL statements are affected.
*CHG or *UR: Specifies the objects referred to in SQL ALTER, CALL,
COMMENT ON, CREATE, DROP, GRANT, LABEL ON, RENAME, and
REVOKE statements and the rows updated, deleted, and inserted are locked
until the end of the unit of work (transaction). Uncommitted changes in other
jobs can be seen.
*ALL or *RS: Specifies the objects referred to in SQL ALTER, CALL,
COMMENT ON, CREATE, DROP, GRANT, LABEL ON, RENAME, and
REVOKE statements and the rows selected, updated, deleted, and inserted are
locked until the end of the unit of work (transaction). Uncommitted changes in
other jobs cannot be seen.
*CS: Specifies the objects referred to in SQL ALTER, CALL, COMMENT ON,
CREATE, DROP, GRANT, LABEL ON, RENAME, and REVOKE statements and
the rows updated, deleted, and inserted are locked until the end of the unit of
work (transaction). A row that is selected, but not updated, is locked until the
next row is selected. Uncommitted changes in other jobs cannot be seen.
*NONE or *NC: Specifies that commitment control is not used. Uncommitted
changes in other jobs can be seen. If the SQL DROP COLLECTION statement
is included in the program, *NONE or *NC must be used. If a relational
database is specified on the RDB parameter and the relational database is on a
system that is not on an AS/400, *NONE or *NC cannot be specified.
*RR: Specifies the objects referred to in SQL ALTER, CALL, COMMENT ON,
CREATE, DROP, GRANT, LABEL ON, RENAME, and REVOKE statements and
the rows selected, updated, deleted, and inserted are locked until the end of
the unit of work (transaction). Uncommitted changes in other jobs cannot be
Appendix E. Using the C for AS/400 and FORTRAN for AS/400 Precompilers
659
660
*NONE: Rows are not blocked for retrieval of data for cursors.
Specifying *NONE:
v Guarantees that the data retrieved is current.
v May reduce the amount of time required to retrieve the first row of data for
a query.
v Stops the database manager from retrieving a block of data rows that is not
used by the program when only the first few rows of a query are retrieved
before the query is closed.
v Can degrade the overall performance of a query that retrieves a large
number of rows.
*ALLREAD: Rows are blocked for read-only cursors if *NONE or *CHG is
specified on the COMMIT parameter. All cursors in a program that are not
explicitly able to be updated are opened for read-only processing even though
EXECUTE or EXECUTE IMMEDIATE statements may be in the program.
Specifying *ALLREAD:
v Allows record blocking under commitment control level *CHG in addition to
the blocking allowed for *READ.
v Can improve the performance of almost all read-only cursors in programs,
but limits queries in the following ways:
The Rollback (ROLLBACK) command, a ROLLBACK statement in host
languages, or the ROLLBACK HOLD SQL statement does not reposition a
read-only cursor when *ALLREAD is specified.
Dynamic running of a positioned UPDATE or DELETE statement (for
example, using EXECUTE IMMEDIATE), cannot be used to update a row
in a cursor unless the DECLARE statement for the cursor includes the
FOR UPDATE clause.
DLYPRP
Specifies whether the dynamic statement validation for a PREPARE statement
is delayed until an OPEN, EXECUTE, or DESCRIBE statement is run. Delaying
validation improves performance by eliminating redundant validation.
*NO: Dynamic statement validation is not delayed. When the dynamic
statement is prepared, the access plan is validated. When the dynamic
statement is used in an OPEN or EXECUTE statement, the access plan is
revalidated. Because the authority or the existence of objects referred to by the
dynamic statement may change, you must still check the SQLCODE or
SQLSTATE after issuing the OPEN or EXECUTE statement to ensure that the
dynamic statement is still valid.
*YES: Dynamic statement validation is delayed until the dynamic statement is
used in an OPEN, EXECUTE, or DESCRIBE SQL statement. When the dynamic
statement is used, the validation is completed and an access plan is built. If
you specify *YES on this parameter, you should check the SQLCODE and
SQLSTATE after running an OPEN, EXECUTE, or DESCRIBE statement to
ensure that the dynamic statement is valid.
Note: If you specify *YES, performance is not improved if the INTO clause is
used on the PREPARE statement or if a DESCRIBE statement uses the
dynamic statement before an OPEN is issued for the statement.
Appendix E. Using the C for AS/400 and FORTRAN for AS/400 Precompilers
661
GENLVL
Specifies the severity level at which the create operation fails. If errors occur
that have a severity level greater than or equal to this value, the operation
ends.
10: The default severity level is 10.
severity-level: Specify a value ranging from 0 through 40.
DATFMT
Specifies the format used when accessing date result columns. All output date
fields are returned in the specified format. For input date strings, the specified
value is used to determine whether the date is specified in a valid format.
Note: An input date string that uses the format *USA, *ISO, *EUR, or *JIS is
always valid.
If a relational database is specified on the RDB parameter and the
database is on a system that is not an AS/400 system, then *USA, *ISO,
*EUR, or *JIS must be specified.
*JOB: The format specified for the job is used. Use the Display Job (DSPJOB)
command to determine the current date format for the job.
*USA: The United States date format (mm/dd/yyyy) is used.
*ISO: The International Organization for Standardization (ISO) date format
(yyyy-mm-dd) is used.
*EUR: The European date format (dd.mm.yyyy) is used.
*JIS: The Japanese Industrial Standard date format (yyyy-mm-dd) is used.
*MDY: The date format (mm/dd/yy) is used.
*DMY: The date format (dd/mm/yy) is used.
*YMD: The date format (yy/mm/dd) is used.
*JUL: The Julian date format (yy/ddd) is used.
DATSEP
Specifies the separator used when accessing date result columns.
Note: This parameter applies only when *JOB, *MDY, *DMY, *YMD, or *JUL is
specified on the DATFMT parameter.
*JOB: The date separator specified for the job at precompile time is used. Use
the Display Job (DSPJOB) command to determine the current value for the job.
/: A slash (/) is used.
.: A period (.) is used.
,: A comma (,) is used.
-: A dash (-) is used.
662
: A blank ( ) is used.
*BLANK: A blank ( ) is used.
TIMFMT
Specifies the format used when accessing time result columns. For input time
strings, the specified value is used to determine whether the time is specified
in a valid format.
Note: An input date string that uses the format *USA, *ISO, *EUR, or *JIS is
always valid.
If a relational database is specified on the RDB parameter and the
database is on a system that is not another AS/400 system, the time
format must be *USA, *ISO, *EUR, *JIS, or *HMS with a time separator
of colon or period.
*HMS: The (hh:mm:ss) format is used.
*USA: The United States time format (hh:mm xx) is used, where xx is AM or
PM.
*ISO: The International Organization for Standardization (ISO) time format
(hh.mm.ss) is used.
*EUR: The European time format (hh.mm.ss) is used.
*JIS: The Japanese Industrial Standard time format (hh:mm:ss) is used.
TIMSEP
Specifies the separator used when accessing time result columns.
Note: This parameter applies only when *HMS is specified on the TIMFMT
parameter.
*JOB: The time separator specified for the job at precompile time is used. Use
the Display Job (DSPJOB) command to determine the current value for the job.
:: A colon (:) is used.
.: A period (.) is used.
,: A comma (,) is used.
: A blank ( ) is used.
*BLANK: A blank ( ) is used.
REPLACE
Specifies whether a new program or SQL package is created when a program
or SQL package of the same name exists in the same library. The value of this
parameter is passed to the CRTFTNPGM command. More information on this
parameter is in Appendix A, Expanded Parameter Descriptions in the CL
Reference (Abridged) book.
Appendix E. Using the C for AS/400 and FORTRAN for AS/400 Precompilers
663
*YES: A new program or SQL package is created, and any existing program or
SQL package of the same name and type in the specified library is moved to
QRPLOBJ.
*NO: A new program or SQL package is not created if an object of the same
name and type already exists in the specified library.
RDB
Specifies the name of the relational database where the SQL package object is
created.
*LOCAL: The program is created as a distributed SQL program. The SQL
statements will access the local database. An SQL package object is not created
as part of the precompile process. The Create Structured Query Language
Package (CRTSQLPKG) command can be used.
relational-database-name: Specify the name of the relational database where the
new SQL package object is to be created. When the name of the local relational
database is specified, the program created is still a distributed SQL program.
The SQL statements will access the local database.
*NONE: An SQL package object is not created. The program object is not a
distributed program and the Create Structured Query Language Package
(CRTSQLPKG) command cannot be used.
USER
Specifies the user name sent to the remote system when starting the
conversation. This parameter is valid only when RDB is specified.
*CURRENT: The user profile under which the current job is running is used.
user-name: Specify the user name being used for the application server job.
PASSWORD
Specifies the password to be used on the remote system. This parameter is
valid only if RDB is specified.
*NONE: No password is sent. If this value is specified, USER(*CURRENT)
must also be specified.
password: Specify the password of the user name specified on the USER
parameter.
RDBCNNMTH
Specifies the semantics used for CONNECT statements. Refer to the SQL
Reference book for more information.
*DUW: CONNECT (Type 2) semantics are used to support distributed unit of
work. Consecutive CONNECT statements to additional relational databases do
not result in disconnection of previous connections.
*RUW: CONNECT (Type 1) semantics are used to support remote unit of
work. Consecutive CONNECT statements result in the previous connection
being disconnected before a new connection is established.
664
DFTRDBCOL
Specifies the collection name used for the unqualified names of tables, views,
indexes, and SQL packages. This parameter applies only to static SQL
statements.
*NONE: The naming convention defined on the OPTION parameter is used.
collection-name: Specify the name of the collection identifier. This value is used
instead of the naming convention specified on the OPTION parameter.
SQLPKG
Specifies the qualified name of the SQL package created on the relational
database specified on the RDB parameter of this command.
The possible library values are:
*PGMLIB: The package is created in the library with the same name as the
library containing the program.
library-name: Specify the name of the library where the package is created.
*PGM: The package name is the same as the program name.
package-name: Specify the name of the package created on the remote database
specified on the RDB parameter.
SAAFLAG
Specifies the IBM SQL flagging function. This parameter flags SQL statements
to verify whether they conform to IBM SQL syntax More information about
which IBM database products IBM SQL syntax is in the DRDA IBM SQL
Reference, SC26-3255-00.
*NOFLAG: The precompiler does not check to see whether SQL statements
conform to IBM SQL syntax.
*FLAG: The precompiler checks to see whether SQL statements conform to
IBM SQL syntax.
FLAGSTD
Specifies the American National Standards Institute (ANSI) flagging function.
This parameter flags SQL statements to verify whether they conform to the
following standards.
ANSI X3.135-1992 entry
ISO 9075-1992 entry
FIPS 127.2 entry
*NONE: The precompiler does not check to see whether SQL statements
conform to ANSI standards.
*ANS: The precompiler checks to see whether SQL statements conform to
ANSI standards.
PRTFILE
Specifies the qualified name of the printer device file to which the listing is
directed. The file must have a minimum record length of 132 bytes or
information is lost.
The name of the printer file can be qualified by one of the following library
values:
Appendix E. Using the C for AS/400 and FORTRAN for AS/400 Precompilers
665
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
QSYSPRT: If a file name is not specified, the precompiler printout is directed
to the IBM-supplied printer file QSYSPRT.
printer-file-name: Specify the name of the printer device file to which the
precompiler printout is directed.
SRTSEQ
Specifies the sort sequence table to be used for string comparisons in SQL
statements.
Note: *HEX must be specified for this parameter on distributed applications
where the application server is not on an AS/400 system or the release
level is prior to V2R3M0.
Specifies the sort sequence table to be used for string comparisons in SQL
statements.
Note: *HEX must be specified for this parameter on distributed applications
where the application server is not on an AS/400 system or the release
level is prior to V2R3M0.
*JOB: The SRTSEQ value for the job is retrieved during the precompile.
*JOBRUN: The SRTSEQ value for the job is retrieved when the program is
run. For distributed applications, SRTSEQ(*JOBRUN) is valid only when
LANGID(*JOBRUN) is also specified.
*LANGIDUNQ: The unique-weight sort table for the language specified on the
LANGID parameter is used.
*LANGIDSHR: The shared-weight sort table for the language specified on the
LANGID parameter is used.
*HEX: A sort sequence table is not used. The hexadecimal values of the
characters are used to determine the sort sequence.
The name of the sort sequence table can be qualified by one of the following
library values:
*LIBL: All libraries in the jobs library list are searched until the first match
is found.
*CURLIB: The current library for the job is searched. If no library is
specified as the current library for the job, the QGPL library is used.
library-name: Specify the name of the library to be searched.
table-name: Specify the name of the sort sequence table to be used.
LANGID
Specifies the language identifier to be used when SRTSEQ(*LANGIDUNQ) or
SRTSEQ(*LANGIDSHR) is specified.
666
*JOB: The LANGID value for the job is retrieved during the precompile.
*JOBRUN: The LANGID value for the job is retrieved when the program is
run. For distributed applications, LANGID(*JOBRUN) is valid only when
SRTSEQ(*JOBRUN) is also specified.
language-id: Specify a language identifier to be used by the program.
USRPRF
Specifies the user profile that is used when the compiled program object is run,
including the authority that the program object has for each object in static
SQL statements. The profile of either the program owner or the program user
is used to control which objects can be used by the program object.
*NAMING: The user profile is determined by the naming convention. If the
naming convention is *SQL, USRPRF(*OWNER) is used. If the naming
convention is *SYS, USRPRF(*USER) is used.
*USER: The profile of the user running the program object is used.
*OWNER: The user profiles of both the program owner and the program user
are used when the program is run.
DYNUSRPRF
Specifies the user profile used for dynamic SQL statements.
*USER: Local dynamic SQL statements are run under the user profile of the
job. Distributed dynamic SQL statements are run under the user profile of the
application server job.
*OWNER: Local dynamic SQL statements are run under the user profile of the
programs owner. Distributed dynamic SQL statements are run under the user
profile of the SQL packages owner.
|
|
|
|
|
|
TOSRCFILE
Specifies the qualified name of the source file that is to contain the output
source member that has been processed by the SQL precompiler. If the
specified source file is not found, it will be created. The output member will
have the same name as the name that is specified for the SRCMBR parameter.
The possible library values are:
|
|
|
|
library-name: Specify the name of the library that is to contain the output
source file.
|
|
|
|
source-file-name: Specify the name of the source file to contain the output source
member.
Appendix E. Using the C for AS/400 and FORTRAN for AS/400 Precompilers
667
TEXT
Specifies the text that briefly describes the LANGID. More information on this
parameter is in Appendix A, Expanded Parameter Descriptions in the CL
Reference (Abridged) book.
*SRCMBRTXT: The text is taken from the source file member being used to
create the FORTRAN program. Text can be added or changed for a database
source member by using the Start Source Entry Utility (STRSEU) command, or
by using either the Add Physical File Member (ADDPFM) or Change Physical
File Member (CHGPFM) command. If the source file is an inline file or a
device file, the text is blank.
*BLANK: Text is not specified.
description: Specify no more than 50 characters of text, enclosed in
apostrophes.
Example
CRTSQLFTN
PAYROLL
TEXT('Payroll Program')
This command runs the SQL precompiler, which precompiles the source and stores
the changed source in member PAYROLL in file QSQLTEMP in library QTEMP.
The FORTRAN compiler is called to create program PAYROLL in the current
library by using the source member created by the SQL precompiler.
668
SQLCAID)
SQLCABC)
SQLCODE)
SQLERRML)
SQLERRMC)
SQLERRP)
SQLERRD)
SQLWARN)
SQLSTATE)
INTEGER*4 SQLCOD
SQLERR(6)
INTEGER*2 SQLTXL
CHARACTER SQLERP*8,
669
C
C
C
C
C
C
C
C
SQLWRN(0:7)*1,
SQLWRX(1:3)*1,
SQLTXT*70,
SQLSTT*5,
SQLWRNWK*8,
SQLWRXWK*3,
SQLERRWK*24,
SQLERRDWK*24
EQUIVALENCE (SQLWRN(1), SQLWRNWK)
EQUIVALENCE (SQLWRX(1), SQLWRXWK)
EQUIVALENCE (SQLCA(97), SQLERRDWK)
EQUIVALENCE (SQLERR(1), SQLERRWK)
COMMON /SQLCA1/SQLCOD,SQLERR,SQLTXTL
COMMON /SQLCA2/SQLERP,SQLWRN,SQLTXT,SQLWRX,SQLSTT
670
C
C
C
An SQL statement cannot be followed on the same line by another SQL statement
or by a FORTRAN statement.
FORTRAN does not require the use of blanks to delimit words within a statement,
but the SQL language does. The rules for embedded SQL follow the rules for SQL
syntax, which requires the use of one or more blanks as delimiters.
Comments
In addition to SQL comments (--), FORTRAN comments can be included within the
embedded SQL statements wherever a blank is allowed, except between the
keywords EXEC and SQL.
The comment extends to the end of the line. Comment lines can appear between
the lines of a continued SQL statement. The character (!) indicates a comment,
except when it appears in a character context or in column 6.
Debug Lines
Lines contain debug statements (D or d in column 1) are treated as comments
lines by the precompiler.
671
Constants containing DBCS data can be continued across multiple lines by placing
the shift-in character in column 73 of the continued line and placing the shift-out
character in column 6 of the continuation line.
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'<AABBCC>
<DDEEFFGGHHIIJJKK>'
Including Code
SQL statements or FORTRAN statements can be included by embedding the
following SQL statement at the point in the source code where the statements are
to be embedded:
EXEC SQL INCLUDE member-name
Margins
Code the SQL statements (starting with EXEC SQL) in coding columns 7 to 72.
Names
Any valid FORTRAN variable name can be used for a host variable and is subject
to the following restrictions:
Do not use host variable names or external entry names that begin with 'SQ', 'SQL',
'RDI', or 'DSN'. These names are reserved for the database manager.
Do not use the following keywords to identify host variables:
FUNCTION
IMPLICIT
PROGRAM
SUBROUTINE
Statement Labels
Executable SQL statements can have statement numbers associated with them,
specified in columns 1 to 5. However, during program preparation, a labelled SQL
statement causes a CONTINUE statement with that label to be generated before
the code runs the statement. A labelled SQL statement should not be the last
statement in a DO loop. Because CONTINUE statements can be run, SQL
statements that occur before the first statement that can be run in a FORTRAN
program (for example, INCLUDE and BEGIN DECLARE SECTION) should not be
labelled.
672
WHENEVER Statement
The target for the GOTO clause in the SQL WHENEVER statement must be a label
in the FORTRAN source and must reference a statement in the same subprogram.
A WHENEVER statement only applies to SQL statements in the same subprogram.
673
Numeric
INTEGER*2
INTEGER
*4
REAL
*4
REAL*8
DOUBLE PRECISION
,
variable-name
/
numeric-constant /
Character
CHARACTER
*n
variable-name
*n
character-constant /
674
SQLTYPE of
Host Variable
INTEGER*2
500
SMALLINT
INTEGER*4
496
INTEGER
REAL*4
480
FLOAT (single
precision)
Table 47. FORTRAN Declarations Mapped to Typical SQL Data Types (continued)
FORTRAN Data Type
SQLTYPE of
Host Variable
REAL*8
480
FLOAT (double
precision)
CHARACTER*n
452
CHAR(n)
The following table can be used to determine the FORTRAN data type that is
equivalent to a given SQL data type.
Table 48. SQL Data Types Mapped to Typical FORTRAN Declarations
SQL Data Type
FORTRAN Equivalent
Explanatory Notes
SMALLINT
INTEGER*2
INTEGER
INTEGER*4
DECIMAL(p,s) or
NUMERIC(p,s)
No exact equivalent
REAL*4
REAL*8
CHAR(n)
CHARACTER*n
VARCHAR(n)
No exact equivalent
GRAPHIC(n)
Not supported
Not supported
VARGRAPHIC(n)
Not supported
Not supported
DATE
CHARACTER*n
TIME
CHARACTER*n
n must be at least 6; to
include seconds, n must be at
least 8.
TIMESTAMP
CHARACTER*n
Use REAL*8
675
676
Bibliography
This guide lists publications that provide
additional information about topics described or
referred to in this guide. The manuals in this
section are listed with their full title and order
number, but when referred to in text, a shortened
version of the title is used.
v Backup and Recovery, SC41-5304
This guide contains a subset of the information
found in the Backup and Recovery book The
manual contains information about planning a
backup and recovery strategy, the different
types of media available to save and restore
procedures, and disk recovery procedures. It
also describes how to install the system again
from backup.
v Data Management, SC41-5710
This guide provides information about using
files in application programs.
v DB2 for AS/400 Database Programming,
SC41-5701
This guide provides a detailed description of
the DB2 for AS/400 database organization,
including information on how to create,
describe, and update database files on the
system.
v CL Programming, SC41-5721
This guide provides a wide-ranging discussion
of the AS/400 programming topics, including a
general discussion of objects and libraries, CL
programming, controlling flow and
communicating between programs, working
with objects in CL programs, and creating CL
programs. Other topics include predefined and
impromptu messages and handling, defining
and creating user-defined commands and
menus, application testing, including debug
mode, breakpoints, traces, and display
functions.
v CL Reference (Abridged), SC41-5722
This guide provides a description of the
AS/400 control language (CL) and its OS/400
commands. (Non-OS/400 commands are
described in the respective licensed program
publications.) It also provides an overview of
all the CL commands for the AS/400 system,
and it describes the syntax rules needed to
code them.
v Security - Reference, SC41-5302
Copyright IBM Corp. 1997, 1998
677
678
Notices
This information was developed for products and services offered in the U.S.A.
IBM may not offer the products, services, or features discussed in this document in
other countries. Consult your local IBM representative for information on the
products and services currently available in your area. Any reference to an IBM
product, program, or service is not intended to state or imply that only that IBM
product, program, or service may be used. Any functionally equivalent product,
program, or service that does not infringe any IBM intellectual property right may
be used instead. However, it is the users 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 give you
any license to these patents. You can send license inquiries, in writing, to:
IBM Director of Licensing
IBM Corporation
500 Columbus Avenue
Thornwood, NY 10594
U.S.A.
For license inquiries regarding double-byte (DBCS) information, contact the IBM
Intellectual Property Department in your country or send inquiries, in writing, to:
IBM World Trade Asia Corporation
Licensing
2-31 Roppongi 3-chome, Minato-ku
Tokyo 106, Japan
The following paragraph does not apply to the United Kingdom or any other
country where such provisions are inconsistent with local law:
INTERNATIONAL BUSINESS MACHINES CORPORATION PROVIDES THIS
PUBLICATION AS IS WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS
FOR A PARTICULAR PURPOSE. Some states do not allow disclaimer of express or
implied warranties in certain transactions, therefore, this statement may not apply
to you.
This information could include technical inaccuracies or typographical errors.
Changes are periodically made to the information herein; these changes will be
incorporated in new editions of the publication. IBM may make improvements
and/or changes in the product(s) and/or the program(s) described in this
publication at any time without notice.
Licensees of this program who wish to have information about it for the purpose
of enabling: (i) the exchange of information between independently created
programs and other programs (including this one) and (ii) the mutual use of the
information which has been exchanged, should contact:
IBM Corporation
Software Interoperability Coordinator
3605 Highway 52 N
Rochester, MN 55901-7829
U.S.A.
Copyright IBM Corp. 1997, 1998
679
Trademarks
The following terms are trademarks of International Business Machines
Corporation in the United States, or other countries, or both:
Advanced 36
AFP
AnyNet
APPN
AS/400
AS/400e
C for AS/400
Client Access
Client Access/400
COBOL for AS/400
DATABASE 2
DB2
DB2 Universal Database
Distributed Relational Database Architecture
680
DRDA
FORTRAN/400
IBM
Integrated Language Environment
Operating System/400
OS/390
OS/400
RPG for AS/400
System/36
System/38
Ultimedia
VisualAge
400
C-bus is a trademark of Corollary, Inc.
Microsoft, Windows, Windows NT, and the Windows 95 logo are registered
trademarks of Microsoft Corporation.
Java and HotJava are trademarks of Sun Microsystems, Inc.
UNIX is a registered trademark in the United States and other countries licensed
exclusively through X/Open Company Limited.
PC Direct is a registered trademark of Ziff Communications Company and is used
by IBM Corporation under license.
Other company, product, and service names may be trademarks or service marks
of others.
Notices
681
682
Index
Special Characters
% (percent sign)
use with LIKE 73
: (colon)
C++ host variable 176
C host variable 176
COBOL 199
FORTRAN 673
ILE RPG for AS/400 247
PL/I 220
REXX 261
RPG for AS/400 234
- (dash)
in COBOL host variable 199
- (minus)
COBOL 199
%INCLUDE directive 226
PL/I 219
*APOST 198
*CNULRQD 178
/COPY
ILE RPG for AS/400 246, 249
RPG for AS/400 233, 236
#include directive
C 174
C++ 174
*NOCNULRQD 178
*NOCVTDT 250
*NOSEQSRC
ILE RPG for AS/400 246
RPG for AS/400 233
#pragma mapinc directive
C 189
C++ 189
*QUOTE 198
*SEQSRC
ILE RPG for AS/400 246
RPG for AS/400 233
A
access method
dataspace scan 328
hashing access 342
index-from-index 341
index only access 340
key positioning 335
key selection 333
parallel data space scan 331
parallel key positioning 338
parallel key selection access method
334
parallel pre-fetch 330
parallel pre-load 341
row selection method 326
summary table 345
access path
definition 325
keyed sequence 325
sequential 325
Copyright IBM Corp. 1997, 1998
303
683
authorization (continued)
for running using a package 401
ID 296
testing 309, 310
auxiliary storage pools 299, 307
B
basic SQL statements and clauses 31
BEGIN DECLARE SECTION statement
C 176
C++ 176
COBOL 199
FORTRAN 673
ILE RPG for AS/400 246
PL/I 220
RPG for AS/400 234
BETWEEN clause, multiple search
condition 72
BETWEEN keyword 72
bibliography 677
binding 276
blocked insert statement 70
blocking, SQL
improving performance 379
blocking consideration
using, affect on performance 378
C
C++ program
#include directive 174
#pragma mapinc directive 189
apostrophes 193
BEGIN/END DECLARE SECTION
176
coding SQL statements 171
comment 174
compiler parameters 273
continuation 174
dynamic SQL coding 172
error and warning message during a
compile 275
external file description 189
host structure
array indicator structure, declaring
188
arrays, declaring 185
declaring 182
indicator array 185
host variable 176
character 177
declaring 176
externally described 189
graphic 180
numeric 176
using pointers 188
INCLUDE statement 174
including code 174
margin 175
naming convention 175
null 175
preprocessor sequence 175
quotation marks 193
SQL data types
determining equivalent C++ 190
SQLCA, declaring 171
684
catalog (continued)
QSYS2 views 6
table 95
CCSID
connection to non-DB2 for AS/400
405
delimited identifier effect 405
dynamic SQL statement 146
include file 266
package considerations 405
printer file 267
rule for using 164
source file 266
temporary source file 267
Change Class (CHGCLS) command 297
change information
in table
host variables 33, 34
Change Job (CHGJOB) command 297
Change Logical File (CHGLF) command
297
Change Physical File (CHGPF) command
297
Change Query Attribute (CHGQRYA)
command 331
Change Query Attributes (CHGQRYA)
command 311
change session attributes
interactive SQL 287
changing
data 33
information in a table 25
table definition 91, 398
character host variable
C 177
C++ 177
COBOL 202
FORTRAN 674
ILE RPG for AS/400 248, 250
PL/I 221
RPG for AS/400 235, 237
check constraints 97
check pending 105, 305
checking syntax in interactive SQL 283
CHGPF command 33
CHGQRYA (Change Query Attributes)
command 311
CL_SCHED table 429
class schedule table 429
clause 46
AND 74
DISTINCT 72
FROM 36
GROUP BY
example 40
HAVING 42
INTO
example 32
PREPARE statement, use with
148
restriction 153
NOT 74
null value 45
OR 74
ORDER BY 43
SELECT 38
SET 33
clause (continued)
USING DESCRIPTOR 158
VALUES 31
WHENEVER NOT FOUND 60
WHERE
character string 31
example 38, 158
expression 39
joining tables 76
multiple search condition within
74
NOT keyword 40
WHERE CURRENT OF 61
CLI 2
CLOSQLCSR parameter
effect on implicit disconnect 409
using 386
COBOL program 212
BEGIN/END DECLARE SECTION
199
COBOL COPY statement 198, 212
COBOL PROCESS statement 198
coding SQL statements 195, 217
comment 197
compile-time option 198
compiler parameters 272
continuation 197
debug lines 197
dynamic SQL coding 196
error and warning message during a
compile 276
external file description 212
host structure
array indicator structure, declaring
211
arrays, declaring 208
declaring 205
indicator array 207
host variable 199
character 202
declaring 199, 205
externally described 212
floating point 201
graphic 203
numeric 199
including code 198
indicator structure 216
indicator variable 216
margin 198
multiple source programs 199
naming convention 198
REDEFINES 215
sample program with SQL statements
457
sequence numbers 198
SQL 457
SQL data types
determining equivalent COBOL
213
SQLCA, declaring 195
SQLCODE, declaring 195
SQLDA, declaring 196
SQLSTATE, declaring 195
statement label 199
WHENEVER statement 199
coded character set conversion error 38
Index
685
command, CL (continued)
CRTSQLPKG (Create Structured
Query Language Package) 598
Delete Structured Query Language
Package (DLTSQLPKG) 615
DLTSQLPKG (Delete Structured
Query Language Package) 615
command (CL) 653, 668
Change Class (CHGCLS) 297
Change Job (CHGJOB) 297
Change Logical File (CHGLF) 297
Change Physical File (CHGPF) 297
Change Query Attribute (CHGQRYA)
command 331
Change Query Attributes (CHGQRYA)
311
CHGCLS (Change Class) 297
CHGJOB (Change Job) 297
CHGLF (Change Logical File) 297
CHGPF (Change Physical File) 297
CHGQRYA (Change Query Attribute)
command 331
CHGQRYA (Change Query Attributes)
311
Convert SQL C++ (CVTSQLCPP) 615
Create Duplicate Object (CRTDUPOBJ)
310
Create Source Physical File
(CRTSRCPF) command 267
Create SQL C++ (CRTSQLCPPI) 551
Create SQL COBOL (CRTSQLCBL)
504
Create SQL ILE C for AS/400
(CRTSQLCI) 535
Create SQL ILE COBOL
(CRTSQLCBLI) 519
Create SQL ILE/RPG (CRTSQLRPGI)
597
Create SQL Package (CRTSQLPKG)
401, 600
Create SQL PL/I (CRTSQLPLI) 566
Create SQL RPG (CRTSQLRPG) 581
Create User Profile (CRTUSRPRF)
296
CRTDUPOBJ (Create Duplicate Object)
command 310
CRTUSRPRF (Create User Profile)
296
Delete Library (DLTLIB) 304
Delete Override (DLTOVR) 376
Delete SQL Package (DLTSQLPKG)
401, 616
Display Job (DSPJOB) 311
Display Journal (DSPJRN) 378
Display Message Description
(DSPMSGD) 431
Display Module (DSPMOD) 277
Display Program (DSPPGM) 277
Display Program References
(DSPPGMREF) 277
Display Service Program
(DSPSRVPGM) 277
DLTLIB (Delete Library) 304
DLTOVR (Delete Override) 376
DSPJOB (Display Job) 311
DSPJRN (Display Journal) 378
686
comment (continued)
REXX 260
RPG for AS/400 233
COMMENT ON statement
using, example 49
COMMIT
keyword 300
prepared statements 147
statement 403
statement description 6
commitment control
activation group
example 405
committable updates 411
description 299
displaying 311
distributed connection restrictions
414
DRDA resource 411
INSERT statement 33
job-level commitment definition 409,
414
protected resource 411
rollback required 416
RUNSQLSTM command 292
SQL statement processor 292
sync point manager 411
two-phase commit 411
unprotected resource 411
common database problem
solving 395
comparison operators 40
compile step
warning 275
compile-time option
COBOL 198
compiled application program object
managing object 9
output source file member 10
program 9
user source file member 10
compiling
application program
ILE 273
non-ILE 272
application program object
output source file member 10
program 11
user source file member 10
error message 275
warning message 275
completing a unit of work 68
complex search condition
keyword for use in 72
multiple search condition 72
performing 72
WHERE clause 31
concept
assignment rule, using SQL with host
language 162
host language, using SQL with
handling return code 167
host structure 166
host variable 161
SQLCODEs 167
SQLSTATEs 167
SQLSTATEs 167
concurrency
data 297
definition 297
condition
keyword for use in search 72
multiple search within a WHERE
clause 74
performing complex search 72
CONNECT statement 399, 403
interactive SQL 290
connection
DDM 417
determining type 411
ending DDM 417
protected 411
unprotected 411
connection management
ARD programs 421
commitment control restrictions 414
distributed unit of work
considerations 416
ending connections
DDMCNV effect on 417
DISCONNECT statement 417
RELEASE statement 417
example 405
implicit connection
default activation group 409
nondefault activation group 410
implicit disconnection
default activation group 409
nondefault activation group 410
multiple connections to same
relational database 409
connection status
determining 415
example 420
consistency token 404
constant
definition 39
SET clause, value 33
constraint 304
definition 8
referential 8
unique 8
constraints
check 97
referential
check pending 105
creating tables 98
delete rules 103
deleting from tables 102
inserting into tables 100
removing 100
update rules 101
updating tables 101
continuation
C 174
C++ 174
COBOL 197
FORTRAN 671
ILE RPG for AS/400 245
PL/I 219
RPG for AS/400 233
control, commitment 299
control structures 11
controlling parallel processing 391
convention
SQL naming 4
system naming 3
conversion error 37
Convert SQL C++ (CVTSQLCPP)
command 615
copy of the data
using to improve performance 382
COPY statement
COBOL 198
externally described 212
CORPDATA.DEPARTMENT (department)
423
CORPDATA.EMP_ACT (employee to
project activity) 425
CORPDATA.EMP_ACT table 425
CORPDATA.EMPLOYEE table 424
CORPDATA.PROJECT (project) 428
CORPDATA.PROJECT table 428
correlated
names 89
references 89
correlated subquery
definition 87
DELETE statement, use in 90
examples
HAVING clause 89
UPDATE statement 90
WHERE clause 87
note on using 91
correlation
definition 84
name 23, 79
using subquery 84
cost estimation
query optimizer 348
CREATE COLLECTION statement 13
Create Duplicate Object (CRTDUPOBJ)
command 310
CREATE INDEX
sort sequence 53
CREATE SCHEMA
statement 292
Create Source Physical File (CRTSRCPF)
command
precompile use 267
Create SQL C++ (CRTSQLCPPI)
command 551
Create SQL C (CRTSQLC) command 653
Create SQL COBOL (CRTSQLCBL)
command 504
Create SQL FORTRAN (CRTSQLFTN)
command 668
Create SQL ILE C for AS/400
(CRTSQLCI) command 535
Create SQL ILE COBOL (CRTSQLCBLI)
command 519
Create SQL ILE/RPG (CRTSQLRPGI)
command 597
Create SQL Package (CRTSQLPKG)
command 272, 401, 600
authority required 402
Create SQL PL/I (CRTSQLPLI) command
566
Create SQL RPG (CRTSQLRPG)
command 581
687
cursor (continued)
positions
retaining across program call 384,
385
rules for retaining 384
using to improve performance
384, 385
retrieving SELECT statement result
157
scrollable
positioning within a table 55
serial
positioning within a table 55
using 55
WITH HOLD clause 68
CURTIME scalar function 46
CVTSQLCPP (Convert SQL C++)
command 615
D
damage tolerance 305
dash
in COBOL host variable 199
data
adding to the end of table 396
paging
interactively displayed to improve
performance 380
retrieved 395
retrieving
in reverse order 395
selecting from multiple tables
affect on performance 375
updating
as it is retrieved 396
previously retrieved 398
view, processing 36
data definition statement (DDL) 4
data dictionary
WITH DATA DICTIONARY clause
CREATE COLLECTION statement
6
CREATE SCHEMA statement 6
data independence 32, 38
data integrity 97
atomic operation 303
commitment control 299
concurrency 297
constraint 304
damage tolerance 305
data definition statements (DDL) 303
function 297
index recovery 306
journaling 299
save/restore 305
data items
ILE RPG for AS/400 248
RPG for AS/400 235
data manipulation statement (DML) 4
data mapping error 37
data path, open 318
data protection 295
data type
determining equivalent
C 190
C++ 190
COBOL 213
688
DECLARE statement
144
definitions (continued)
NULL value 40
null value 45
open data path 318
outer-level SELECT 83
output source file member 10
package 3, 9, 11, 401
parallel data space scan method 331
parallel key positioning access method
338
parallel key selection access method
334
parallel pre-fetch access method 330
physical file 3
predicate 38
primary table 351
program 11
record 3
referential integrity 8
remote unit of work 399
row 3, 6
search condition 38
secondary tables 351
sequential access path 325
special register 40
SQL package 3
SQLCODE 431
SQLSTATE 431
stored procedure 8
subquery 83
symmetrical multiprocessing 326
table 3, 6
trigger 8
user profile 3
user source file member 10
USER special register 45
view 3, 7
delete current row 61
Delete Library (DLTLIB) command 304
Delete Override (DLTOVR) command
376
Delete SQL Package (DLTSQLPKG)
command 401, 616
DELETE statement
correlated subquery, use in 90
description 27, 34
Delete Structured Query Language
Package (DLTSQLPKG) command 615
deleted rows
getting rid of using REUSEDLT(*YES)
328
getting rid of using RGZPFM 328
deleting
structured query language package
615
deleting information in a table 27
department table
CORPDATA.DEPARTMENT 423
DESCRIBE statement
use with dynamic SQL 147
DESCRIBE TABLE statement 403
description
SQLCODEs and SQLSTATEs 433
descriptions, C for AS/400 external file
637
descriptor-name
in REXX 258
designing
dynamic SQL application 145
DFTRDBCOL (default collection name)
parameter 3
DISCONNECT statement 399, 403
ending connection 417
Display Job (DSPJOB) command 311
Display Journal (DSPJRN) command
378
Display Message Description (DSPMSGD)
command 431
Display Module (DSPMOD) 277
Display Program (DSPPGM) command
277
Display Program References
(DSPPGMREF) command 277
Display Service Program (DSPSRVPGM)
277
displaying SQLCODE and SQLSTATE
description 431
DISTINCT 71
clause 72
keyword 397
distributed data management (DDM)
278
distributed relational database
accessing remote databases 289
application requester 399
application server 399
committable updates 411, 415
connection management 405
multiple connections 409
connection restrictions 414
connection type
determining 411
protected 411
unprotected 411
consideration for creating packages
402
creating packages 402
DB2 for AS/400 support 399
determining connection status 415
distributed RUW example program
400
distributed unit of work 399, 410,
418
ending connections
DDMCNV effect on 417
DISCONNECT statement 417
RELEASE statement 417
first failure data capture (FFDC) 421
implicit connection
default activation group 409
nondefault activation group 410
implicit disconnection
default activation group 409
nondefault activation group 410
interactive SQL 289
packages 401
statement in 402
precompiler diagnostic messages 402
problem handling 421
protected connection 411
protected resource 411
remote unit of work 399, 410
rollback required state 416
session attributes 290
E
Edit Check Pending Constraints
(EDTCPCST) command 305
Edit Rebuild of Access Paths
(EDTRBDAP) command 305
Index
689
690
examples (continued)
CURRENT TIMEZONE 47
cursor 56
cursor in DUW program 420
defining stored procedures
with CREATE PROCEDURE 115
deleting information in a table 27
determining connection status 420
distributed RUW program 400
distributed unit of work program
418
dynamic CALL 124
embedded CALL 122, 123
EXISTS 86
getting catalog information about
column 96
table 95
getting comment 49
getting information about
column using catalog 95
table using catalog 95
getting information from
multiple tables 23
single table 20
governor 323
host variable in SQL statement 161
IN 73
index 366
inserting
add row to table 32
into a table 19
multiple rows into a table 69
invoking stored procedures 124
where a CREATE PROCEDURE
exists 122
where no CREATE PROCEDURE
exists 123
join 76
LABEL ON statement 16, 48
LIKE 73
list function in interactive SQL 284
multiple search condition (WHERE
clause) 74
OR 75
ORDER BY
sort sequence 50
output from precompiler, COBOL
268
preventing duplicate rows 71
QSYSPRT listing
SQL statement processor 293
reducing the number of open database
operation 376
removing information
from table 27, 34
returning completion status
to calling program 132
RPG for AS/400
declare variable 240
sample table 423
search 72
SELECT records
sort sequence 51
SELECT statement allocating storage
for SQLDA 153
selecting data from multiple tables
375
examples (continued)
selecting into table
host variables 36
special register 47
stored procedures
returning completion status 132
subquery 83
Union
simple 82
UNION
using host variables 80
UNION ALL
using host variables 82
UPDATE statement 25
using index 95
variable declaration 216
view
sort sequence 52
WITH CASCADED CHECK OPTION
108
WITH LOCAL CHECK OPTION 108
working with index 95
exception condition 168
exception join 77
EXECSQL REXX command 257, 259
EXECUTE IMMEDIATE statement 145
EXECUTE privileges
for packages 401
EXECUTE statement 145, 146
EXISTS keyword, use in subquery 86
exiting interactive SQL 288
expression
definition 39
SET clause, value 34
using in the WHERE clause 39
extended dynamic
QSQPRCED 2
external file description
C 189
C++ 189
C for AS/400 637
COBOL 212
host structure arrays
COBOL 213
ILE RPG for AS/400 250
RPG for AS/400 237
ILE RPG for AS/400 249
PL/I 226
RPG for AS/400 236
F
failed session, recovering 288
FETCH
using host structure array
multiple-row 63
FETCH statement 157
multiple-row
ILE RPG for AS/400 248, 255
RPG for AS/400 235
FFDC (first failure data capture) 421
field 3
file description
external
C 189
C++ 189
C for AS/400 637
G
getting
catalog information about
column 96
table 95
comment 49
information
from multiple table 23
from single table 20
governor 321
*DFT 322
*RQD 322
governor (continued)
*SYSRPYL 322
CHGQRYA 321
JOB 322
QRYTIMLMT 321
time limit 322
Grant Object Authority (GRTOBJAUT)
command 295
GRANT PACKAGE statement 399
graphic host variable
C 180
C++ 180
COBOL 203
ILE RPG for AS/400 250
GROUP BY
clause 40
keyword 397
using null value with 41
grouping optimization 363
grouping the row you select 41
H
halfword binary integer (SMALLINT)
164
handling
error return code
SQLCODEs and SQLSTATEs 167
exception condition (WHENEVER
statement) 168
hash join 352
hashing access method 342
HAVING clause 42
host language
concepts and rules 161
host structure
C 182
C++ 182
COBOL 205
definition 161
ILE RPG for AS/400 248
indicator array
C 185, 188
C++ 185, 188
COBOL 207, 211
PL/I 223, 225
PL/I 222
RPG for AS/400 235
used to set null value 167
using arrays
C 185
C++ 185
COBOL 208, 213
ILE RPG for AS/400 248
PL/I 224
RPG for AS/400 235
using indicator variable with, example
166
host structure array
multiple-row FETCH 63
host structure indicator array
C 185
C++ 185
COBOL 207
PL/I 223
host variable 176
assignment rule 162
C 176
I
ID, authorization 296
IDDU (interactive data definition utility)
6
ILE (Integrated Language Environment)
compiling application 273
Index
691
ILE C program
SQL statements in, sample
ILE COBOL program
450
692
indicator variable
C 193
C++ 193
COBOL 216
definition 165
FORTRAN 676
ILE RPG for AS/400 255
PL/I 229
REXX 263
RPG for AS/400 240
used to set null value 167
used with host structure, example
166
with host structure 166
indicator variables
stored procedures 129
information, inserting into
table 17
information messages
open data path 318, 320
performance 312, 318
inner join 75
INSERT n ROWS
improving performance 380
INSERT statement
blocked 31
ILE RPG for AS/400 248
RPG for AS/400 235
column value 162
default value 19, 32
description 31
example 19
VALUES clause 31
inserting
information into table 17
multiple rows
into tables 69
note 70
Integrated Language Environment (ILE)
module 11
program 11
service program 12
integrity
catalog 307
data 97, 297
referential 97
interactive data definition utility 6
interactive interface
concepts 1
Interactive SQL 1
interactive SQL
accessing remote databases 289
Interactive SQL
adding DBCS data 283
interactive SQL
change session attributes 287
description 279
exiting 288
function 279
general use 279
getting started 280
overview 279
package 290
Interactive SQL
prompting 284
interactive SQL
prompting
DBCS consideration 283
overview 279
session services 279, 286, 288
statement entry 279, 281
statement processing mode 283
Interactive SQL
syntax checking 283
interactive SQL
terminology 3
testing your SQL statements with
279, 288
interactively displayed data, paging
affect on performance 380
INTO clause
description 32
PREPARE statements 148
restriction 153
J
JOB 322
job attribute
DDMCNV 417
job-level commitment definition 409, 414
join
cross 78
definitions 29
exception 77
hash 352
inner 75
left outer 77
optimization 350
join operation
definition 23
in a view 29
join optimization
performance tips 365
join order
optimization 355
join position 315
join secondary dials
costing 356
joining
data from multiple tables 75
table with WHERE clause 76
technique 79
journal 6
journal receiver 6
journaling 299
K
key positioning
access method 335
key range estimate 349
key selection
access method 333
keyed sequence
access path 325
keyword
AND 74
BETWEEN 72
COMMIT 300
DISTINCT 397
EXISTS 86
keyword (continued)
GROUP BY 397
IN 73, 86
LIKE 73
NOT 40
OR 74
search condition, use in 72
UNION 80, 397
UNION ALL, specifying 82
L
LABEL ON statement 16, 48
information in catalog 48
package 404
language, host
concepts and rules 161
learn how to
prompt
using interactive SQL 284
leaving interactive SQL 288
left outer join 77
library
definition 3
LIKE keyword 73
limit, time 322
list function 286
list function in interactive SQL
description 284
listing
output from precompiler 267
live data
using to improve performance 381
locks
analyzing 311
logical file 3, 7
long object names
performance 387
Loosely Coupled Parallelism 2
LR indicator
ending RPG for AS/400 programs
241
M
mapping error
data 37
margins
C 175
C++ 175
COBOL 198
FORTRAN 672
PL/I 219
REXX 260
MARGINS parameter
C 175
C++ 175
marker, parameter 158
member
output source file 10
user source file 10
message
analyzing error and warning messages
275
cause and user response 312
message (continued)
error and warning during a compile
275
open data path information 318, 320
performance information 312, 318
running in debug mode 312
minus
COBOL 199
mode
interactive SQL 283
module
Integrated Language Environment
(ILE)
object 11
monitoring
database query performance 390
multiple
row
inserting into a table 69
notes on inserting 70
search condition within a WHERE
clause 74
table
improving performance when
selecting data from 375
joining data from 75
multiple-row FETCH statement
using
descriptor area 64
host structure arrays 63
row storage area 64
with languages 63
N
naming convention
*SQL 3
*SYS 3
C 175
C++ 175
COBOL 198
FORTRAN 672
ILE RPG for AS/400 246
PL/I 219
REXX 260
RPG for AS/400 234
SQL 4
system 3
negative SQLCODEs 434
nested loop join 351
non-SELECT statements, processing
NOT keyword 40, 74
Notices 679
NOW scalar function 46
NUL-terminator
C 178
C++ 178
character host variables
C 177
C++ 177
null
usage in C 175
usage in C++ 175
null string in REXX 260
NULL value 14
null value 45
Index
145
693
NULL value
definition 40
null value
INSERT statement 32
inserting in a view 94
set by indicator variable 167
SET clause, value 33
UPDATE statement 33
used with GROUP BY clause 41
used with ORDER BY clause 44
null value, SQL
contrasted with null value in REXX
260
number of calls
using a FETCH statement 379
number of open database operations
improving performance by reducing
376
numbers
sequence
COBOL 198
ILE RPG for AS/400 246
RPG for AS/400 233
numeric assignment rule
host variable, using 164
numeric conversion error 38
numeric host variable
C 176
C++ 176
COBOL 199
FORTRAN 673
ILE RPG for AS/400 250
PL/I 220
RPG for AS/400 237
O
object
application program 9
collection 3
module 9
Integrated Language Environment
(ILE) 11
package 9
program
Integrated Language Environment
(ILE) 11
service program 9
Integrated Language Environment
(ILE) 12
SQL 5
occurrence data structure
ILE RPG for AS/400 248
RPG for AS/400 235
ODBC 145
ODP (open data path) 376
open
closing 376
determing number 378
effect on performance 376
reducing number 376
open cursor
during a unit of work 68
open data path 376
definition 318
information messages 318
open database connectivity (ODBC) 145
694
P
package
authority to create 401
authority to run 401
bind to an application 9
CCSID considerations for 405
consistency token 404
Create SQL Package (CRTSQLPKG)
command 401
authority required 402
creating
authority required 401
effect of ARD programs 421
errors during 402
on local system 404
RDB parameter 401
RDBCNNMTH parameter 404
TGTRLS parameter 403
type of connection 404
unit of work boundary 404
creating on a non-DB2 for AS/400
errors during 402
required precompiler options for
DB2 Common Server 402
unsupported precompiler options
402
DB2 for AS/400 support 401
definition 9, 11, 401
Delete SQL Package (DLTSQLPKG)
command 401
deleting 401
interactive SQL 290
labeling 404
restore 404
package (continued)
save 404
SQL statement size 403
statements that do not require
package 403
page fault 326
paging
interactively displayed data 380
retrieved data 395
parallel data space scan
access method 331
parallel key positioning access method
338
parallel key selection access method 334
parallel pre-fetch
access method 330
parallel pre-load
index-based 341
table-based 341
parallel processing
controlling
in jobs (CHGQRYA command)
392
system wide (QQRYDEGREE)
value 391
parameter passing
differences 390
PL/I 229
RPG for AS/400 241
stored procedures 125, 129
table 126
parameters
marker 158
parameters, command
ALWCPYDTA (allow copy data) 381,
382
CLOSQLCSR (close SQL cursor) 384,
385
path, open data 318
pending
check 105
performance 325
information messages 312, 318
monitoring query 390
open data path messages 318, 320
using long object names 387
performance considerations 323
performance improvement
blocking, using 378
paging interactively displayed data
380
PREPARE statement 387
reducing number of open database
operation 376
retaining cursor positions across
program call 384, 385
SELECT statements, using effectively
381
selecting data from multiple tables
375
SQL blocking 379
using copy of the data 382
using INSERT n ROWS 380
using live data 381
using precompile options 388
performance verification 311
performing complex search condition 72
physical file 3, 6
PL/I
SQL statements in, sample 465
PL/I program
%INCLUDE directive 219, 226
BEGIN/END DECLARE SECTION
220
coding SQL statements 217, 230
comment 219
compiler parameters 272
continuation 219
dynamic SQL coding 218
error and warning message during a
compile 275
external file description 226
host structure
array indicator structure, declaring
225
arrays, declaring 224
declaring 222
indicator array 223
host variable 220
character 221
declaring 220, 222
externally described 226
numeric 220
INCLUDE statement 219
including code 219
indicator structure 229
indicator variable 229
margin 219
naming convention 219
SQL data types
determining equivalent PL/I 227
SQLCA, declaring 217
SQLCODE, declaring 217
SQLDA, declaring 218
SQLSTATE, declaring 217
structure parameter passing 229
WHENEVER statement 220
pointer
C 188
C++ 188
positive SQLCODEs 433
pre-fetching 328
precompile options
improving performance, using 388
precompiler
basic process 265
complete diagnostics 266
concepts 1
diagnostic messages 402
diagnostics 267
displaying
options 277
errors 275
include file
CCSID 266
input to 266
other preprocessors 266
output from
listing 267
sample 268
temporary source file member
267
parameters passed to compiler 272
precompiler (continued)
passing
host variables 389
record number 269
reference column 271
secondary input 266
sequence number 269
source file
CCSID 266
containing DBCS constants 266
margins 266
source record 269
VisualAge C++ for AS/400 274
warning 275
precompiler command
CRTSQLC 653
CRTSQLCBL 272
CRTSQLCBLI 273
CRTSQLCI 175, 178, 180, 181, 273
CRTSQLCPPI 175, 178, 180, 181, 273
CRTSQLFTN 668
CRTSQLPLI 219, 272
CRTSQLRPG 272
CRTSQLRPGI 273
CRTSQLxxx 50, 402
CVTSQLCPP 175, 178, 180, 181, 273
default 385
description 272
precompiler file
QSQLTEMP 267
QSQLTEMP1 267
precompiler parameter
*CVTDT 249
*NOCVTDT 249, 250
ALWCPYDTA 381
CLOSQLCSR 386
DATFMT 247, 250
DATSEP 247, 250
DBGVIEW(*SOURCE) 310
displayed on listing 267
INCFILE 266
MARGINS 219, 266, 275
C 175
C++ 175
OBJ 267
OBJTYPE(*MODULE) 273
OBJTYPE(*PGM) 273
OBJTYPE(*SRVPGM) 273
OPTION(*APOST) 198
OPTION(*CNULRQD) 178, 180
OPTION(*CVTDT) 249
OPTION(*NOCNULRQD) 178, 181
OPTION(*NOGEN) 272, 273
OPTION(*NOSEQSRC) 246
OPTION(*SEQSRC) 233
OPTION(*QUOTE) 198
OPTION(*SEQSRC) 246
OPTION(*SOURCE) 266
OPTION(*XREF) 266, 267
OUTPUT 266
parameters passed to compiler 272
PGM 267
PRTFILE 267
RDB
Effect on precompile 265
TIMFMT 247, 250
TIMSEP 247, 250
predicate
definition 38
transitive closure 360
Predictive Query Governor 321
PREPARE statement
improving performance 387
non-SELECT statement 146
restrictions 145
using 158
prepared statement
distributed unit of work 420
preparing program with SQL statements
265
preprocessor
usage with SQL C++ program 175
usage with SQL C program 175
with SQL 266
preventing duplicate rows 71
Print SQL Information (PRTSQLINF)
277, 312, 323
printer file 267
CCSID 267
printing current session 287
problem handling 167
problems
join query performance 362
problems, solving database 395
process, basic
precompiler 265
PROCESS statement
COBOL 198
FORTRAN 673
processing
data in a view 36
non-SELECT statements 145
SELECT statement with SQLDA 147
producing reports from sample programs
487
program
application 309
compiling application
ILE 273
non-ILE 272
debugging 310
definition 11
Integrated Language Environment
(ILE) object 11
non-ILE object 11
performance verification 311
preparing and running with SQL
statements 265
reference 277
report produced by sample 487
running with embedded SQL
DDM consideration 278
instruction 278
override consideration 278
return code 278
sample 449
SQL statements in
COBOL 457
ILE C 450
ILE COBOL 457
ILE RPG for AS/400 program 478
PL/I 465
REXX 484
RPG for AS/400 472
Index
695
program calls
rules for retaining cursor positions
386
project table 428
prompt
using interactive SQL 279, 284
prompting
CREATE TABLE 283
function 279, 281
overview 279
subqueries 283
protected connections
dropping 414
protected resource 411
protection, data 295
PRTSQLINF (Print SQL Information)
command 618
public authority 295
Q
QDT 350
QRYTIMLMT parameter
CHGQRYA (Change Query Attributes)
command 311
QSQCHKS 2
QSQLTEMP 267
QSQLTEMP1 267
QSQPRCED 2
package 9
QSYS2
catalog views 6
QSYSPRT listing
SQL statement processor
example 293
query
cancelling 322
Query Definition Template (QDT) 350
query optimizer 325
cost estimation 348
decision-making rules 350
default filter factors 349
optimization goals 348
query performance
monitoring 390
query time limit 322
quotation mark
C 193
C++ 193
R
read-only
table 59
view 94
read-only connection 411
receiver, journal 6
Reclaim DDM connections
(RCLDDMCNV) command 417
record, definition 3
record selection 51
sort sequence, using 49
recovering
effect on open cursor 68
index 306
interactive SQL
saved or failed session 288
696
REXX 2
coding SQL statements 257, 263
SQL statements in
sample 484
ROLLBACK
prepared statements 147
rollback
rollback required state 416
ROLLBACK statement 403
row
definition 3, 6
delete current 61
inserting multiple
into a table 69
note 70
preventing duplicate 71
ROWS, INSERT n
improving performance 380
RPG 231, 243
RPG for AS/400 program 243
/COPY statement 233, 236
character host variables 235
coding SQL statements 231, 241
comment 233
compiler parameters 272
continuation 233
dynamic SQL coding 232
ending
using LR indicator 241
using RETRN statement 241
error and warning message during a
compile 276
external file description 236
host structure
array, declaring 235
declaring 235
host variable 234
character 237
declaring 234
externally described 236
numeric 237
including code 233
indicator structure 240
indicator variable 240
naming convention 234
occurrence data structure 235
sequence numbers 233
SQL data types
determining equivalent RPG 237
SQL statements in
sample 472
SQLCA
placement 231
statement label 234
structure parameter passing 241
using the SQLDA 232
WHENEVER statement 234
RRN scalar function 77
rule
host variable, using 164
retaining cursor positions
program calls 386
rule 162, 164, 165
SQL with host language, using 161
run mode
interactive SQL 283
S
sample programs
DB2 for AS/400 statements, using
449
distributed RUW program 400
report 487
SQL statements in
COBOL 457
ILE C 450
ILE COBOL 457
ILE RPG for AS/400 program 478
PL/I 465
REXX 484
RPG for AS/400 472
sample tables DB2 for AS/400 423
save/restore 305
packages 404
saved session
in a source file 287, 288
recovering 288
schedule table
class 429
schemas
SQL statement processor 292
scrollable cursor 55
search condition
definition 38
performing complex 72
subqueries 84
using keyword in 72
security 295
authorization 310
authorization ID 296
commitment control 299
data integrity 297
concurrency 297
public authority 295
view 296
SELECT clause 38
select information
into host variables 36
SELECT INTO statement
column value 162
restriction 145
retrieving row 35
SELECT statement
definition 20
697
698
300
statements (continued)
DROP PACKAGE 399
dynamic 4
EXECUTE 145, 146
FETCH 157
FOR n ROWS 379
multiple-row 62
number of calls 379
GRANT PACKAGE 399
host variable in SQL, using 161
INSERT
assignment operation 162
example 19
n ROWS 380
using 31
LABEL ON statement
example 48
examples 16
multiple-row FETCH 64
OPEN 158
package not required 403
packages 402
PREPARE
cursor 158
improving performance 387
non-SELECT statement 146
using 145
preparing and running a program
with 265
processing non select 145
RELEASE 399
REVOKE PACKAGE 399
ROLLBACK 6
sample programs 449
select 20
SELECT INTO
column value 162
example 35
processing data (view) 36
restriction 145
specifying column 38
SET CONNECTION 399
SQL packages 402
testing
in application program 309
using interactive SQL 279, 288
time value 46
timestamp value 46
UPDATE
assignment operation 162
changing data value 25
example 33
WHENEVER 176, 199, 220, 673
handling exception condition 168
ILE RPG for AS/400 246
RPG for AS/400 234
WHENEVER SQLERROR 167
stopping interactive SQL 288
storage, allocating for SQLDA 153
stored procedures 115, 141
definition 8
parameter passing 125
indicator variables 129
table 126
string assignment
rule using host variable 163
STRSQL (Start SQL) command 280, 635
T
table
adding data to the end 396
changing definition 91, 398
changing information in 25
CL_SCHED (class schedule) 429
CORPDATA.DEPARTMENT
(department) 423
CORPDATA.EMP_ACT (employee to
project activity) 425
CORPDATA.EMPLOYEE 424
CORPDATA.PROJECT (project) 428
creating
CREATE TABLE statement 14
view 28
data management methods 345
DB2 for AS/400 sample 423
defining name 48
definition 3, 6
deleting information in 27
establishing position at the end 395
getting catalog information
about column 95
getting information
from multiple 23
from one 20
IN_TRAY 430
inserting
information into 17
multiple rows into 69
table (continued)
joining 75
the WHERE clause 76
multiple
creating view over 29
improving performance when
selecting data from 375
sample 423
used in examples
CORPDATA.DEPARTMENT
(department) 423
CORPDATA.EMP_ACT (employee
to project activity) 425
CORPDATA.EMPLOYEE 424
CORPDATA.PROJECT (project)
428
using 14
table name
system 17
TAG statement
ILE RPG for AS/400 246
RPG for AS/400 234
technique
coding 31, 55, 69
solving database problem 395
temporary keyed access path 359
temporary source file member
output from precompiler 267
terminology
interactive SQL 3
relational database 3
relationship table
*SQL 3
*SYS 3
testing
authorization 309, 310
debugging your program 310
input data 309
performance verification 311
SQL statements using interactive SQL
279, 288
statements in application program
309
view 309
time assignment rule
host variable, using 165
time format 46
specifying current value 47
timestamp assignment rule
host variable, using 165
timestamp format 46
specifying current value 47
TIMFMT
ILE RPG for AS/400 247, 250
TIMSEP
ILE RPG for AS/400 247, 250
tolerance, damage 305
Trace Job (TRCJOB) command 312, 378
transitive closure 360
TRCJOB (Trace Job) command 312
trigger
definition 8
event 8
trigger support 109
trigraph
C 175
C++ 175
truncation error 36
two-phase commit 411
typing
interactive SQL 281
U
union
C 176
C++ 176
UNION ALL, specifying 82
UNION keyword
restriction 397
using to combine subselects 80
unique constraint
definition 8
unit of work
distributed 399
effect on open cursor 68
package creation 404
remote 399
rollback required 416
unit of work boundary
package creation 404
unprotected resource 411
UPDATE statement
assignment operation 162
correlated subquery, using in 90
description 33
WHERE clause 25
updating data
as it is retrieved, restrictions 396
committable updates 411
previously retrieved 398
user auxiliary storage pool (ASP) 307
user profile
authorization ID 3
authorization name 3
user source file member
definition 10
USER special register 45
using
a copy of the data 381, 382
allow copy data (ALWCPYDTA) 381,
382
blocked insert statement 70
USING
clause 155
using
close SQL cursor (CLOSQLCSR) 381,
386
cursor
example 56
retrieve row 60
date value 46
USING
DESCRIPTOR clause 158
using
FETCH statement 379
index 95
null value 45
ORDER BY 50
parameter markers 158
parameter passing techniques
performance improvement 389
record selection 51
sort sequence 49
Index
699
using (continued)
time value 46
timestamp value 46
Using
views 93
using interactive SQL 279
after first time 286
list selection function 284
prompting 281
statement entry 281
using JOB parameter 323
using SQL
application programs 325
V
validate mode
interactive SQL 283
value
default 14, 19
inserting
into table or view 31
VALUES clause 31
variable 176, 193
host
REXX 261
indicator 165
use of indicator with host structure,
example 166
used to set null value 167
variable-length data
tips 373
varying-list SELECT statement
definition 148
using 148
verification
performance 311
view
creating 93
CREATE VIEW statement 28
on a table 28
over multiple tables 29
definition 3, 7
limiting access 28
processing data in 36
read-only 94
security 296
sort sequence 52
testing 309
using 93
WITH CASCADED CHECK 106
WITH CHECK 106
WITH LOCAL CHECK 107
WHENEVER statement
C 176
C++ 176
COBOL 199
FORTRAN 673
handling exception condition with
168
ILE RPG for AS/400 246
PL/I 220
REXX, substitute for 261
RPG for AS/400 234
WHERE clause
character string 31
constant 39
description 38
example 158
expression in, using 39
joining tables 76
multiple search condition within a
74
NOT keyword 40
WHERE CURRENT OF clause 61
WITH CASCADED CHECK OPTION
106
WITH CHECK OPTION 106
WITH DATA DICTIONARY clause
CREATE COLLECTION statement 6
CREATE SCHEMA statement 6
creating data dictionary 6
WITH LOCAL CHECK OPTION 107
working with
index 95
X
X/Open call level interface
W
warning
test for negative SQLCODEs 167
warning message during a compile 275
C++ program 275
C program 275
COBOL program 275, 276
PL/I program 275
RPG program 275, 276
WHENEVER NOT FOUND clause 60
WHENEVER SQLERROR 167
700
AS/400e series
DB2 for AS/400 SQL Programming
Version 4
Publication No. SC41-5611-02
Overall, how satisfied are you with the information in this book?
Overall satisfaction
Very Satisfied
h
Satisfied
h
Neutral
h
Dissatisfied
h
Very Dissatisfied
h
Neutral
h
h
h
h
h
h
Dissatisfied
h
h
h
h
h
h
Very Dissatisfied
h
h
h
h
h
h
How satisfied are you that the information in this book is:
Accurate
Complete
Easy to find
Easy to understand
Well organized
Applicable to your tasks
Very Satisfied
h
h
h
h
h
h
Satisfied
h
h
h
h
h
h
h Yes
h No
When you send comments to IBM, you grant IBM a nonexclusive right to use or distribute your comments in any
way it believes appropriate without incurring any obligation to you.
Name
Company or Organization
Phone No.
Address
SC41-5611-02
IBMR
___________________________________________________________________________________________________
Cut or Fold
Along Line
_ _ _ _ _ _ _Fold
_ _ _ and
_ _ _Tape
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _Please
_ _ _ _ do
_ _ not
_ _ _staple
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _Fold
_ _ _and
_ _ Tape
______
NO POSTAGE
NECESSARY
IF MAILED IN THE
UNITED STATES
PERMIT NO. 40
IBM CORPORATION
ATTN DEPT 542 IDCLERK
3605 HWY 52 N
ROCHESTER MN 55901-7829
________________________________________________________________________________________
Fold and Tape
Please do not staple
Fold and Tape
SC41-5611-02
Cut or Fold
Along Line
IBMR
SC41-5611-02
Spine information:
IBM
AS/400e series
Version 4
SC41-5611-02