SQL Programming

March 27, 2018 | Author: maharet74 | Category: Database Index, Ibm Db2, Sql, Databases, Ibm System I


Comments



Description

AS/400eDB2 UDB for AS/400 SQL Programming V ersion 4 RBAF-Y000-00 AS/400e DB2 UDB for AS/400 SQL Programming V ersion 4 RBAF-Y000-00 © Copyright International Business Machines Corporation 1997, 1999. All rights reserved. Note to U.S. Government Users — Documentation related to restricted rights — Use, duplication or disclosure is subject to restrictions set forth in GSA ADP Schedule Contract with IBM Corp. Contents About DB2 UDB for AS/400 SQL Programming. . . . 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. . . . . . . . . . How this book has changed . . . . . . . . . . . . Prerequisite and related information . . . . . . . . . How to send your comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii xvii xvii xviii xix xx xxi xxi xxi Chapter 1. Introduction to DB2 UDB for AS/400 Structured Language . . . . . . . . . . . . . . . . . . SQL Concepts . . . . . . . . . . . . . . . . . . Relational Database and Terminology . . . . . . . . Types of SQL Statements . . . . . . . . . . . . SQL Objects . . . . . . . . . . . . . . . . . . Collections . . . . . . . . . . . . . . . . . . Tables, Rows, and Columns. . . . . . . . . . . . Aliases . . . . . . . . . . . . . . . . . . . Views . . . . . . . . . . . . . . . . . . . . Indexes . . . . . . . . . . . . . . . . . . . Constraints . . . . . . . . . . . . . . . . . . Triggers . . . . . . . . . . . . . . . . . . . Stored Procedures . . . . . . . . . . . . . . . User-defined functions . . . . . . . . . . . . . . Packages . . . . . . . . . . . . . . . . . . Application Program Objects . . . . . . . . . . . . User Source File Member . . . . . . . . . . . . Output Source File Member . . . . . . . . . . . . Program . . . . . . . . . . . . . . . . . . . Package . . . . . . . . . . . . . . . . . . . Module . . . . . . . . . . . . . . . . . . . Service Program . . . . . . . . . . . . . . . . Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 . 1 . 3 . 4 . 5 . 6 . 6 . 7 . 7 . 8 . 8 . 8 . 9 . 9 . 9 . 9 . 11 . 11 . 11 . 12 . 12 . 12 . . . . . . . . . . . . . . . . . . . 13 13 13 13 14 14 16 16 18 18 20 23 25 25 28 28 28 29 30 Chapter 2. Getting Started with SQL . . . . . . . . . . . . . Starting Interactive SQL . . . . . . . . . . . . . . . . . . Creating an SQL Collection . . . . . . . . . . . . . . . . . Example: Creating the SQL Collection (SAMPLECOLL) . . . . . Creating and Using a Table . . . . . . . . . . . . . . . . . Example: Creating a Table (INVENTORY_LIST) . . . . . . . . Creating the Supplier Table (SUPPLIERS) . . . . . . . . . . Using the LABEL ON Statement . . . . . . . . . . . . . . . Inserting Information into a Table . . . . . . . . . . . . . . . Example: Inserting Information into a Table (INVENTORY_LIST) . . Getting Information from a Single Table . . . . . . . . . . . . Getting Information from More Than One Table. . . . . . . . . . Changing Information in a Table . . . . . . . . . . . . . . . Example: Changing Information in a Table . . . . . . . . . . Deleting Information from a Table. . . . . . . . . . . . . . . Example: Deleting Information from a Table (INVENTORY_LIST) . . Creating and Using a View . . . . . . . . . . . . . . . . . Example: Creating a view on a single table . . . . . . . . . . Example: Creating a view combining data from more than one table . © Copyright IBM Corp. 1997, 1999 iii Chapter 3. Basic Concepts and Techniques . . . . . . . Using Basic SQL Statements and Clauses . . . . . . . . The INSERT Statement . . . . . . . . . . . . . . The UPDATE Statement . . . . . . . . . . . . . . The DELETE Statement . . . . . . . . . . . . . . The SELECT INTO Statement . . . . . . . . . . . . Data retrieval errors. . . . . . . . . . . . . . . . The SELECT Clause . . . . . . . . . . . . . . . The WHERE Clause . . . . . . . . . . . . . . . The GROUP BY Clause . . . . . . . . . . . . . . The HAVING Clause . . . . . . . . . . . . . . . The ORDER BY Clause . . . . . . . . . . . . . . Using Null Values . . . . . . . . . . . . . . . . . Using Special Registers . . . . . . . . . . . . . . . Using Date, Time, and Timestamp . . . . . . . . . . . Specifying Current Date and Time Values. . . . . . . . Date/Time Arithmetic . . . . . . . . . . . . . . . Creating and using ALIAS names. . . . . . . . . . . . Using LABEL ON. . . . . . . . . . . . . . . . . . Using COMMENT ON . . . . . . . . . . . . . . . . Getting Comments . . . . . . . . . . . . . . . . Using Sort Sequence in SQL . . . . . . . . . . . . . Sort Sequence Used with ORDER BY and Record Selection ORDER BY . . . . . . . . . . . . . . . . . . . Record selection . . . . . . . . . . . . . . . . . Sort Sequence and Views . . . . . . . . . . . . . Sort Sequence and the CREATE INDEX Statement . . . . Sort Sequence and Constraints . . . . . . . . . . . Chapter 4. Using a Cursor . . . . . . . . . . . . . Types of cursors . . . . . . . . . . . . . . . . . Serial cursor . . . . . . . . . . . . . . . . . Scrollable cursor . . . . . . . . . . . . . . . . Example of Using a Cursor . . . . . . . . . . . . . Step 1: Define the Cursor . . . . . . . . . . . . Step 2: Open the Cursor . . . . . . . . . . . . . Step 3: Specify What to Do When End-of-Data Is Reached Step 4: Retrieve a Row Using a Cursor . . . . . . . Step 5a: Update the Current Row . . . . . . . . . Step 5b: Delete the Current Row . . . . . . . . . . Step 6: Close the Cursor . . . . . . . . . . . . . Using the Multiple-Row FETCH Statement . . . . . . . Multiple-Row FETCH Using a Host Structure Array . . . Multiple-Row FETCH Using a Row Storage Area . . . . Unit of Work and Open Cursors . . . . . . . . . . . Chapter 5. Advanced Coding Techniques . . . . . Advanced Insert Techniques . . . . . . . . . . Inserting Rows into a Table Using a Select-Statement Using the Blocked Insert Statement . . . . . . . Advanced Update Techniques . . . . . . . . . . Preventing Duplicate Rows . . . . . . . . . . . Performing Complex Search Conditions . . . . . . Keywords for Use in Search Conditions . . . . . Joining Data from More Than One Table . . . . . . Inner Join . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 31 31 33 34 35 36 38 38 40 42 43 45 45 47 47 47 48 48 49 50 50 50 51 52 53 53 54 55 55 55 55 56 58 59 59 60 61 61 62 62 63 64 68 69 69 69 70 70 71 72 72 75 75 iv DB2 UDB for AS/400 SQL Programming V4R4 Left Outer Join . . . . . . . . . . . . . . . Exception Join. . . . . . . . . . . . . . . . Cross Join . . . . . . . . . . . . . . . . . Using multiple join types in one statement . . . . . Notes on Joins . . . . . . . . . . . . . . . Using Table Expressions . . . . . . . . . . . . . Using the UNION Keyword to Combine Subselects . . . Specifying UNION ALL. . . . . . . . . . . . . Using Subqueries . . . . . . . . . . . . . . . Correlation . . . . . . . . . . . . . . . . . Subqueries and Search Conditions . . . . . . . . How Subqueries Are Used . . . . . . . . . . . Using Subqueries with UPDATE and DELETE . . . . Notes on Using Subqueries . . . . . . . . . . . Correlated Subqueries . . . . . . . . . . . . . Using Correlated Subqueries in an UPDATE Statement Using Correlated Subqueries in a DELETE Statement . Notes on Using Correlated Subqueries. . . . . . . Changing a Table Definition . . . . . . . . . . . . Adding a column . . . . . . . . . . . . . . . Changing a column . . . . . . . . . . . . . . Allowable Conversions. . . . . . . . . . . . . Deleting a column . . . . . . . . . . . . . . Order of operations for ALTER TABLE statement . . . Creating and Using Views . . . . . . . . . . . . Adding Indexes . . . . . . . . . . . . . . . . Using the Catalog in Database Design . . . . . . . . Getting Catalog Information about a Table . . . . . Getting Catalog Information about a Column . . . . Chapter 6. Data Integrity . . . . . . . . . Adding and Using Check Constraints . . . . . Referential Integrity . . . . . . . . . . . . Adding or dropping referential constraints . . . Removing Referential Constraints . . . . . Inserting into Tables with Referential Constraints Updating Tables with Referential Constraints . Deleting from Tables with Referential Constraints Check Pending . . . . . . . . . . . . WITH CHECK OPTION on a View . . . . . . WITH CASCADED CHECK OPTION . . . . WITH LOCAL CHECK OPTION . . . . . . DB2 UDB for AS/400 Trigger Support . . . . . Trigger Sample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 77 78 78 79 79 80 83 84 85 85 86 88 88 88 91 92 92 93 93 93 93 95 95 95 96 97 97 98 99 99 99 100 102 102 103 105 107 108 108 109 111 111 117 117 117 118 124 124 125 125 127 128 132 Chapter 7. Stored Procedures . . . . . . . . . . . . . . . . . Creating a Procedure . . . . . . . . . . . . . . . . . . . . . Defining an External Procedure . . . . . . . . . . . . . . . . . Defining an SQL Procedure . . . . . . . . . . . . . . . . . . . Invoking a Stored Procedure . . . . . . . . . . . . . . . . . . Using CALL Statement Where Procedure Definition Exists . . . . . . Using Embedded CALL Statement Where No Procedure Definition Exists . Using Embedded CALL Statement With an SQLDA . . . . . . . . . Using Dynamic CALL Statement Where No CREATE PROCEDURE Exists Parameter Passing Conventions for Stored Procedures . . . . . . . . Indicator Variables and Stored Procedures . . . . . . . . . . . . . Contents v Returning a Completion Status to the Calling Program . . . . . . . . . . 134 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . 135 Example 1. ILE C and PL/I Procedures Called From ILE C Applications . . 136 Chapter 8. Using the Object-Relational Capabilities . . Why Use the DB2 Object Extensions? . . . . . . . . DB2 Approach to Supporting Objects . . . . . . . . Using Large Objects (LOBs) . . . . . . . . . . . Understanding Large Object Data Types (BLOB, CLOB, Understanding Large Object Locators . . . . . . . Example: Using a Locator to Work With a CLOB Value . Indicator Variables and LOB Locators . . . . . . . LOB File Reference Variables . . . . . . . . . . Example: Extracting a Document To a File . . . . . Example: Inserting Data Into a CLOB Column . . . . Display Layout of LOB Columns . . . . . . . . . Journal Entry Layout of LOB Columns . . . . . . . User-Defined Functions (UDF) . . . . . . . . . . . Why Use UDFs? . . . . . . . . . . . . . . . UDF Concepts. . . . . . . . . . . . . . . . Implementing UDFs . . . . . . . . . . . . . . Registering UDFs . . . . . . . . . . . . . . Examples of Registering UDFs . . . . . . . . . Using UDFs . . . . . . . . . . . . . . . . User-defined Distinct Types (UDT) . . . . . . . . . Why Use UDTs? . . . . . . . . . . . . . . . Defining a UDT . . . . . . . . . . . . . . . Resolving Unqualified UDTs . . . . . . . . . . . Examples of Using CREATE DISTINCT TYPE . . . . Defining Tables with UDTs . . . . . . . . . . . Manipulating UDTs . . . . . . . . . . . . . . Examples of Manipulating UDTs . . . . . . . . . Synergy Between UDTs, UDFs, and LOBs . . . . . . Combining UDTs, UDFs, and LOBs . . . . . . . . Examples of Complex Applications . . . . . . . . Using DataLinks . . . . . . . . . . . . . . . . NO LINK CONTROL . . . . . . . . . . . . . FILE LINK CONTROL (with File System Permissions) . FILE LINK CONTROL (with Database Permissions) . . Commands Used for Working with DataLinks . . . . Chapter 9. Writing User-Defined Functions UDF runtime environment . . . . . . . Length of time that the UDF runs . . . . Threads considerations . . . . . . . Parallel processing . . . . . . . . . Writing function code . . . . . . . . . Writing UDFs as SQL functions . . . . Writing UDFs as external functions . . . Examples of UDF code . . . . . . . . Example: Square of a number UDF . . . Example: Counter . . . . . . . . . (UDFs) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . DBCLOB) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 145 146 146 147 147 148 151 151 152 154 155 155 156 156 158 160 161 161 164 169 169 170 171 171 171 172 173 177 177 177 180 181 181 181 182 185 185 185 186 186 186 186 187 193 193 194 Chapter 10. Dynamic SQL Applications. . . . . . . . . . . . . . . 197 Designing and Running a Dynamic SQL Application . . . . . . . . . . . 199 Processing Non-SELECT statements . . . . . . . . . . . . . . . . 199 vi DB2 UDB for AS/400 SQL Programming V4R4 CCSID of Dynamic SQL Statements. . . . . . . Using the PREPARE and EXECUTE Statements . . Processing SELECT Statements and Using an SQLDA. Fixed-List SELECT Statements . . . . . . . . Varying-List Select-Statements . . . . . . . . . The SQL Descriptor Area (SQLDA) . . . . . . . SQLDA Format . . . . . . . . . . . . . . Example of a Select-Statement for Allocating Storage Using a Cursor . . . . . . . . . . . . . . Using Parameter Markers . . . . . . . . . . . . . . . . . for . . . . . . . . . . . . . . . . . . . . . . . SQLDA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200 200 201 201 202 203 204 208 212 213 Chapter 11. Common Concepts and Rules for Using SQL with Host Languages . . . . . . . . . . . . . . . . . . . . . . Using Host Variables in SQL Statements . . . . . . . . . . . . Assignment Rules . . . . . . . . . . . . . . . . . . . Indicator Variables . . . . . . . . . . . . . . . . . . . Handling SQL Error Return Codes . . . . . . . . . . . . . . Handling Exception Conditions with the WHENEVER Statement . . . Chapter 12. Coding SQL Statements in C and C++ Applications Defining the SQL Communications Area . . . . . . . . . . Defining SQL Descriptor Areas. . . . . . . . . . . . . . Embedding SQL Statements . . . . . . . . . . . . . . Comments . . . . . . . . . . . . . . . . . . . . Continuation for SQL Statements . . . . . . . . . . . . Including Code . . . . . . . . . . . . . . . . . . Margins . . . . . . . . . . . . . . . . . . . . . Names . . . . . . . . . . . . . . . . . . . . . NULLs and NULs . . . . . . . . . . . . . . . . . Statement Labels . . . . . . . . . . . . . . . . . Preprocessor Sequence . . . . . . . . . . . . . . . Trigraphs. . . . . . . . . . . . . . . . . . . . . WHENEVER Statement . . . . . . . . . . . . . . . Using Host Variables . . . . . . . . . . . . . . . . . Declaring Host Variables . . . . . . . . . . . . . . . Using Host Structures . . . . . . . . . . . . . . . . . Host Structure Declarations . . . . . . . . . . . . . . Host Structure Indicator Array . . . . . . . . . . . . . Using Arrays of Host Structures . . . . . . . . . . . . . Host Structure Array . . . . . . . . . . . . . . . . Host Structure Array Indicator Structure . . . . . . . . . Using Pointer Data Types . . . . . . . . . . . . . . . Using ILE C for AS/400 External File Descriptions . . . . . . Determining Equivalent SQL and C or C++ Data Types. . . . . Notes on C and C++ Variable Declaration and Usage . . . . Using Indicator Variables . . . . . . . . . . . . . . . . Chapter 13. Coding SQL Statements in COBOL Applications Defining the SQL Communications Area . . . . . . . . . Defining SQL Descriptor Areas. . . . . . . . . . . . . Embedding SQL Statements . . . . . . . . . . . . . Comments . . . . . . . . . . . . . . . . . . . Continuation for SQL Statements . . . . . . . . . . . Including Code . . . . . . . . . . . . . . . . . Margins . . . . . . . . . . . . . . . . . . . . Sequence Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215 215 216 219 221 222 225 225 226 227 228 228 228 229 229 229 229 229 229 230 230 230 239 240 241 241 242 244 244 245 246 249 249 251 251 252 253 253 253 254 254 254 Contents vii Names . . . . . . . . . . . . . . . . . . . COBOL Compile-Time Options. . . . . . . . . . . Statement Labels . . . . . . . . . . . . . . . WHENEVER Statement . . . . . . . . . . . . . Multiple source programs. . . . . . . . . . . . . Using Host Variables . . . . . . . . . . . . . . . Declaring Host Variables . . . . . . . . . . . . . Using Host Structures . . . . . . . . . . . . . . . Host Structure . . . . . . . . . . . . . . . . . Host Structure Indicator Array . . . . . . . . . . . Using Host Structure Arrays . . . . . . . . . . . . Host Structure Array . . . . . . . . . . . . . . Host Array Indicator Structure . . . . . . . . . . . Using External File Descriptions . . . . . . . . . . . Using External File Descriptions for Host Structure Arrays. Determining Equivalent SQL and COBOL Data Types . . . Notes on COBOL Variable Declaration and Usage . . . Using Indicator Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 254 255 255 255 255 255 264 265 268 268 269 272 272 273 274 276 276 279 279 280 280 281 281 281 281 281 282 282 282 282 282 286 287 288 289 290 291 292 294 294 297 297 298 298 298 299 299 299 299 299 300 300 300 Chapter 14. Coding SQL Statements in PL/I Applications. . . . . Defining the SQL Communications Area . . . . . . . . . . . . Defining SQL Descriptor Areas. . . . . . . . . . . . . . . . Embedding SQL Statements . . . . . . . . . . . . . . . . Example . . . . . . . . . . . . . . . . . . . . . . . Comments . . . . . . . . . . . . . . . . . . . . . . Continuation for SQL Statements . . . . . . . . . . . . . . Including Code . . . . . . . . . . . . . . . . . . . . Margins . . . . . . . . . . . . . . . . . . . . . . . Names . . . . . . . . . . . . . . . . . . . . . . . Statement Labels . . . . . . . . . . . . . . . . . . . WHENEVER Statement . . . . . . . . . . . . . . . . . Using Host Variables . . . . . . . . . . . . . . . . . . . Declaring Host Variables . . . . . . . . . . . . . . . . . Using Host Structures . . . . . . . . . . . . . . . . . . . Host Structures . . . . . . . . . . . . . . . . . . . . Host Structure Indicator Arrays. . . . . . . . . . . . . . . Using Host Structure Arrays . . . . . . . . . . . . . . . . . Host Structure Array . . . . . . . . . . . . . . . . . . Using External File Descriptions . . . . . . . . . . . . . . . Determining Equivalent SQL and PL/I Data Types. . . . . . . . . Using Indicator Variables . . . . . . . . . . . . . . . . . . Differences in PL/I Because of Structure Parameter Passing Techniques Chapter 15. Coding SQL Statements in RPG for AS/400 Applications Defining the SQL Communications Area . . . . . . . . . . . . Defining SQL Descriptor Areas. . . . . . . . . . . . . . . . Embedding SQL Statements . . . . . . . . . . . . . . . . Example . . . . . . . . . . . . . . . . . . . . . . . Comments . . . . . . . . . . . . . . . . . . . . . . Continuation for SQL Statements . . . . . . . . . . . . . . Including Code . . . . . . . . . . . . . . . . . . . . Sequence Numbers . . . . . . . . . . . . . . . . . . . Names . . . . . . . . . . . . . . . . . . . . . . . Statement Labels . . . . . . . . . . . . . . . . . . . WHENEVER Statement . . . . . . . . . . . . . . . . . Using Host Variables . . . . . . . . . . . . . . . . . . . viii DB2 UDB for AS/400 SQL Programming V4R4 Declaring Host Variables . . . . . . . . . . . . . . . . . Using Host Structures . . . . . . . . . . . . . . . . . . . Using Host Structure Arrays . . . . . . . . . . . . . . . . . Using External File Descriptions . . . . . . . . . . . . . . . External File Description Considerations for Host Structure Arrays. . Determining Equivalent SQL and RPG for AS/400 Data Types . . . . Notes on RPG for AS/400 Variable Declaration and Usage . . . . Using Indicator Variables . . . . . . . . . . . . . . . . . . Example . . . . . . . . . . . . . . . . . . . . . . . Differences in RPG for AS/400 Because of Structure Parameter Passing Techniques . . . . . . . . . . . . . . . . . . . . . . Ending a Called RPG for AS/400 Program Correctly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300 300 301 302 303 303 306 306 306 . . . 307 . . . 307 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309 309 310 311 311 311 311 312 312 312 312 312 312 313 314 314 315 315 316 316 316 317 318 322 322 322 323 325 325 325 327 328 328 328 329 329 329 329 329 329 330 331 Chapter 16. Coding SQL Statements in ILE RPG for AS/400 Applications Defining the SQL Communications Area . . . . . . . . . . . . . . Defining SQL Descriptor Areas. . . . . . . . . . . . . . . . . . Embedding SQL Statements . . . . . . . . . . . . . . . . . . Example . . . . . . . . . . . . . . . . . . . . . . . . . Comments . . . . . . . . . . . . . . . . . . . . . . . . Continuation for SQL Statements . . . . . . . . . . . . . . . . Including Code . . . . . . . . . . . . . . . . . . . . . . Sequence Numbers . . . . . . . . . . . . . . . . . . . . . Names . . . . . . . . . . . . . . . . . . . . . . . . . Statement Labels . . . . . . . . . . . . . . . . . . . . . WHENEVER Statement . . . . . . . . . . . . . . . . . . . Using Host Variables . . . . . . . . . . . . . . . . . . . . . Declaring Host Variables . . . . . . . . . . . . . . . . . . . Using Host Structures . . . . . . . . . . . . . . . . . . . . . Using Host Structure Arrays . . . . . . . . . . . . . . . . . . . Declaring LOB Host Variables . . . . . . . . . . . . . . . . . . LOB Host Variables . . . . . . . . . . . . . . . . . . . . . LOB Locators . . . . . . . . . . . . . . . . . . . . . . . LOB File Reference Variables . . . . . . . . . . . . . . . . . Using External File Descriptions . . . . . . . . . . . . . . . . . External File Description Considerations for Host Structure Arrays. . . . Determining Equivalent SQL and RPG Data Types . . . . . . . . . . Notes on ILE/RPG 400 Variable Declaration and Usage . . . . . . . Using Indicator Variables . . . . . . . . . . . . . . . . . . . . Example . . . . . . . . . . . . . . . . . . . . . . . . . SQLDA Example of the SQLDA for a Multiple Row-Area Fetch . . . . . . Chapter 17. Coding SQL Statements in REXX Applications Using the SQL Communications Area . . . . . . . . . Using SQL Descriptor Areas . . . . . . . . . . . . Embedding SQL Statements . . . . . . . . . . . . Comments . . . . . . . . . . . . . . . . . . Continuation of SQL Statements . . . . . . . . . . Including Code . . . . . . . . . . . . . . . . Margins . . . . . . . . . . . . . . . . . . . Names . . . . . . . . . . . . . . . . . . . Nulls . . . . . . . . . . . . . . . . . . . . Statement Labels . . . . . . . . . . . . . . . Handling Errors and Warnings . . . . . . . . . . . Using Host Variables . . . . . . . . . . . . . . . Determining Data Types of Input Host Variables . . . . The Format of Output Host Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Contents ix Avoiding REXX Conversion . . . . . . . . . . . . . . . . . . . 332 Using Indicator Variables . . . . . . . . . . . . . . . . . . . . . 332 Chapter 18. Preparing and Running a Program with SQL Statements Basic Processes of the SQL Precompiler . . . . . . . . . . . . Input to the Precompiler . . . . . . . . . . . . . . . . . Source File CCSIDs . . . . . . . . . . . . . . . . . . Output from the Precompiler . . . . . . . . . . . . . . . Non-ILE Precompiler Commands . . . . . . . . . . . . . . . Compiling a Non-ILE Application Program . . . . . . . . . . ILE Precompiler Commands. . . . . . . . . . . . . . . . . Compiling an ILE Application Program . . . . . . . . . . . . Precompiling for the VisualAge C++ for OS/400 Compiler . . . . . Interpreting Application Program Compile Errors . . . . . . . . . Error and Warning Messages during a Compile . . . . . . . . Binding an Application . . . . . . . . . . . . . . . . . . . Program References . . . . . . . . . . . . . . . . . . Displaying Precompiler Options . . . . . . . . . . . . . . . Running a Program with Embedded SQL . . . . . . . . . . . . OS/400 DDM Considerations . . . . . . . . . . . . . . . Override Considerations . . . . . . . . . . . . . . . . . SQL Return Codes . . . . . . . . . . . . . . . . . . . Chapter 19. Using Interactive SQL Basic Functions of Interactive SQL . Starting Interactive SQL . . . . Using Statement Entry Function . Prompting . . . . . . . . . Using the List Selection Function . Session Services Description . . Exiting Interactive SQL . . . . Using an existing SQL Session . Recovering an SQL Session . . Accessing Remote Databases with . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Interactive . . . . . . . . . . . . . . . . . . . . SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333 333 334 334 335 340 340 341 341 342 343 343 344 345 345 346 346 346 347 349 349 350 351 351 354 356 357 358 358 359 361 362 362 362 363 365 365 366 366 366 366 367 368 369 373 375 375 376 376 377 Chapter 20. Using the SQL Statement Processor . . . Execution of Statements After Errors Occur . . . . . . Commitment Control in the SQL Statement Processor . . Schemas in the SQL Statement Processor . . . . . . Source Member Listing for the SQL Statement Processor . Chapter 21. DB2 UDB for AS/400 Security . . . . . . . . . . Authorization ID . . . . . . Views . . . . . . . . . . Auditing . . . . . . . . . Data Integrity . . . . . . . . Concurrency . . . . . . . Journaling . . . . . . . . Commitment Control . . . . Atomic Operations . . . . . Constraints . . . . . . . . Save/Restore . . . . . . . Damage Tolerance . . . . . Index Recovery . . . . . . Catalog Integrity . . . . . . Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . Protection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . x DB2 UDB for AS/400 SQL Programming V4R4 User Auxiliary Storage Pool (ASP) . . . . . . . . . . . . . . . . 378 Chapter 22. Testing SQL Statements in Application Programs . . Establishing a Test Environment . . . . . . . . . . . . . . Designing a Test Data Structure . . . . . . . . . . . . . Testing Your SQL Application Programs . . . . . . . . . . . The Program Debug Phase . . . . . . . . . . . . . . . The Performance Verification Phase. . . . . . . . . . . . CL Command Usage for SQL Application Performance Verification Performance Information Messages . . . . . . . . . . . . Performance Information Messages and Open Data Paths . . . Chapter 23. Using the DB2 UDB for AS/400 Predictive Query Cancelling a Query . . . . . . . . . . . . . . . . . General Implementation Considerations . . . . . . . . . User Application Implementation Considerations . . . . . . Controlling the Default Reply to the Inquiry Message . . . . Using the Governor for Performance Testing. . . . . . . . Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379 379 379 380 380 381 381 382 388 391 392 392 392 393 393 394 Governor . . . . . . . . . . . . . . . . . . . . . . . . Chapter 24. DB2 UDB for AS/400 Data Management and Query Optimizer Tips . . . . . . . . . . . . . . . . . . . . . . . . . . General Optimization Tips . . . . . . . . . . . . . . . . . . . Data Management Methods . . . . . . . . . . . . . . . . . . . Access Path . . . . . . . . . . . . . . . . . . . . . . . Access Method . . . . . . . . . . . . . . . . . . . . . . Data Access Methods . . . . . . . . . . . . . . . . . . . . . The Optimizer . . . . . . . . . . . . . . . . . . . . . . . . Cost Estimation . . . . . . . . . . . . . . . . . . . . . . Access Plan Validation. . . . . . . . . . . . . . . . . . . . Optimizer Decision-Making Rules . . . . . . . . . . . . . . . . Join Optimization . . . . . . . . . . . . . . . . . . . . . . Grouping Optimization . . . . . . . . . . . . . . . . . . . . Effectively Using SQL Indexes . . . . . . . . . . . . . . . . . . Using Indexes With Sort Sequence . . . . . . . . . . . . . . . . Using Indexes and Sort Sequence With Selection, Joins, or Grouping . . Ordering . . . . . . . . . . . . . . . . . . . . . . . . . Example Indexes . . . . . . . . . . . . . . . . . . . . . . Tips for using VARCHAR and VARGRAPHIC data types . . . . . . . . Chapter 25. Additional SQL performance considerations . . . . . . . Improving Performance by Using Database Manager Blocking Considerations Improving Performance Using FETCH FOR n ROWS . . . . . . . . . Improving Performance with SQL Blocking . . . . . . . . . . . . . Improving Performance Using INSERT n ROWS . . . . . . . . . . . Improving Performance When Paging Interactively Displayed Data . . . . Improving Performance by Using SELECT Statements Effectively . . . . . Improving Performance by Using Live Data . . . . . . . . . . . . . Improving Performance by Using the ALWCPYDTA Parameter . . . . . . Improving Performance by Using the Optimize Clause . . . . . . . . . Improving Performance by Retaining Cursor Positions . . . . . . . . . Improving Performance by Retaining Cursor Positions for Non-ILE Program Calls . . . . . . . . . . . . . . . . . . . . . . . . . Improving Performance by Retaining Cursor Positions across ILE Program Calls . . . . . . . . . . . . . . . . . . . . . . . . . . General Rules for Retaining Cursor Positions For All Program Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395 395 396 396 397 420 422 423 425 425 426 442 446 449 449 450 450 456 459 461 462 462 463 463 464 464 465 466 467 . 467 . 468 . 469 Contents xi Improving Performance of SQL PREPARE Statements . . . . . . . . Effects on Performance When Using Long Object Names . . . . . . . Improving Performance Using the Precompile Options . . . . . . . . Improving Performance by Using Structure Parameter Passing Techniques Background Information on Parameter Passing. . . . . . . . . . Some Differences Because of Structure Parameter Passing Techniques Controlling Parallel Processing . . . . . . . . . . . . . . . . . Controlling Parallel Processing System Wide . . . . . . . . . . Controlling Parallel Processing for a Job . . . . . . . . . . . . Chapter 26. Monitoring and Optimizing Query Performance Tools Optimizing Query Performance Using Query Optimization Tools . . Query optimizer debug messages . . . . . . . . . . . . . Print SQL information . . . . . . . . . . . . . . . . . . Database monitor statistics . . . . . . . . . . . . . . . . Start Database Monitor (STRDBMON) Command . . . . . . . End Database Monitor (ENDDBMON) Command . . . . . . . Database Monitor Performance Records . . . . . . . . . . Query Optimizer Index Advisor . . . . . . . . . . . . . . Database Monitor Examples . . . . . . . . . . . . . . Database Monitor Physical File DDS . . . . . . . . . . . Database Monitor Logical File DDS . . . . . . . . . . . . Memory Resident Database Monitor APIs. . . . . . . . . . . External API Description . . . . . . . . . . . . . . . . External File Description . . . . . . . . . . . . . . . . Record Identification . . . . . . . . . . . . . . . . . Comparison table of query optimization tools . . . . . . . . Change query attributes . . . . . . . . . . . . . . . . . Query Options File QAQQINI . . . . . . . . . . . . . . . Specifying the QAQQINI file. . . . . . . . . . . . . . . Creating the QAQQINI Query Options File . . . . . . . . . Chapter 27. Solving Common Database Problems Paging through Retrieved Data . . . . . . . . Retrieving in Reverse Order. . . . . . . . . . Establishing Position at the End of a Table . . . . Adding Data to the End of a Table . . . . . . . Updating Data as It Is Retrieved from a Table . . . Restrictions . . . . . . . . . . . . . . . Updating Data Previously Retrieved . . . . . . . Changing the Table Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470 470 471 472 472 473 473 474 474 477 477 477 478 478 479 480 481 482 482 489 493 524 525 525 542 542 543 543 544 544 551 551 551 551 552 552 553 553 554 555 555 556 557 558 558 561 561 561 562 563 563 565 565 Chapter 28. Distributed Relational Database Function . . . . . . DB2 UDB for AS/400 Distributed Relational Database Support . . . . DB2 UDB for AS/400 Distributed Relational Database Example Program SQL Package Support . . . . . . . . . . . . . . . . . . . Valid SQL Statements in an SQL Package . . . . . . . . . . Considerations for Creating an SQL Package . . . . . . . . . CCSID Considerations for SQL . . . . . . . . . . . . . . . Connection Management and Activation Groups . . . . . . . . . Connections and conversations . . . . . . . . . . . . . . Source Code for PGM1: . . . . . . . . . . . . . . . . . Source Code for PGM2: . . . . . . . . . . . . . . . . . Source Code for PGM3: . . . . . . . . . . . . . . . . . Multiple Connections to the Same Relational Database. . . . . . Implicit Connection Management for the Default Activation Group . . xii DB2 UDB for AS/400 SQL Programming V4R4 Implicit Connection Management for Nondefault Activation Groups Distributed Support . . . . . . . . . . . . . . . . . . . Determining Connection Type . . . . . . . . . . . . . . Connect and Commitment Control Restrictions . . . . . . . . Determining Connection Status . . . . . . . . . . . . . Distributed Unit of Work Connection Considerations . . . . . . Ending Connections. . . . . . . . . . . . . . . . . . Distributed Unit of Work . . . . . . . . . . . . . . . . . Managing Distributed Unit of Work Connections . . . . . . . Cursors and Prepared Statements . . . . . . . . . . . . Application Requester Driver Programs . . . . . . . . . . . Problem Handling . . . . . . . . . . . . . . . . . . . Appendix A. DB2 UDB for AS/400 Sample Tables . . . Department Table (CORPDATA.DEPARTMENT) . . . . DEPARTMENT . . . . . . . . . . . . . . . Employee Table (CORPDATA.EMPLOYEE) . . . . . . Employee to Project Activity Table (CORPDATA.EMP_ACT) EMP_ACT . . . . . . . . . . . . . . . . . Project Table (CORPDATA.PROJECT) . . . . . . . . PROJECT . . . . . . . . . . . . . . . . . Class Schedule Table (CL_SCHED) . . . . . . . . . In Tray Table (IN_TRAY) . . . . . . . . . . . . . Appendix B. SQLCODEs and SQLSTATEs SQLCODE and SQLSTATE Descriptions . . Positive SQLCODEs . . . . . . . . Negative SQLCODEs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 566 566 567 570 570 572 573 573 574 576 577 578 579 579 580 580 581 582 584 584 585 585 587 589 589 591 605 605 606 613 621 628 634 640 643 645 645 648 648 661 661 664 664 678 678 681 681 695 695 699 699 712 Appendix C. Sample Programs Using DB2 UDB for AS/400 Statements Examples of programs that use SQL statements . . . . . . . . . . SQL Statements in ILE C and C++ Programs . . . . . . . . . . . SQL Statements in COBOL and ILE COBOL Programs. . . . . . . . SQL Statements in PL/I . . . . . . . . . . . . . . . . . . . SQL Statements in RPG for AS/400 Programs . . . . . . . . . . . SQL Statements in ILE RPG for AS/400 Programs . . . . . . . . . SQL Statements in REXX Programs. . . . . . . . . . . . . . . Report Produced by Sample Programs. . . . . . . . . . . . . . Appendix D. DB2 UDB for AS/400 CL Command Descriptions . . . . CRTSQLCBL (Create Structured Query Language COBOL) Command . . Purpose . . . . . . . . . . . . . . . . . . . . . . . . Parameters . . . . . . . . . . . . . . . . . . . . . . . Example . . . . . . . . . . . . . . . . . . . . . . . . CRTSQLCBLI (Create SQL ILE COBOL Object) Command . . . . . . Purpose . . . . . . . . . . . . . . . . . . . . . . . . Parameters . . . . . . . . . . . . . . . . . . . . . . . Example . . . . . . . . . . . . . . . . . . . . . . . . CRTSQLCI (Create Structured Query Language ILE C Object) Command . Purpose . . . . . . . . . . . . . . . . . . . . . . . . Parameters . . . . . . . . . . . . . . . . . . . . . . . Example . . . . . . . . . . . . . . . . . . . . . . . . CRTSQLCPPI (Create Structured Query Language C++ Object) Command Purpose . . . . . . . . . . . . . . . . . . . . . . . . Parameters . . . . . . . . . . . . . . . . . . . . . . . Example . . . . . . . . . . . . . . . . . . . . . . . . Contents xiii CRTSQLPLI (Create Structured Query Language PL/I) Command. . . . . Purpose . . . . . . . . . . . . . . . . . . . . . . . . . Parameters . . . . . . . . . . . . . . . . . . . . . . . . Example . . . . . . . . . . . . . . . . . . . . . . . . . CRTSQLRPG (Create Structured Query Language RPG) Command . . . . Purpose . . . . . . . . . . . . . . . . . . . . . . . . . Parameters . . . . . . . . . . . . . . . . . . . . . . . . Example . . . . . . . . . . . . . . . . . . . . . . . . . CRTSQLRPGI (Create SQL ILE RPG Object) Command . . . . . . . . Purpose . . . . . . . . . . . . . . . . . . . . . . . . . Parameters . . . . . . . . . . . . . . . . . . . . . . . . Example . . . . . . . . . . . . . . . . . . . . . . . . . CRTSQLPKG (Create Structured Query Language Package) Command . . Purpose . . . . . . . . . . . . . . . . . . . . . . . . . Parameters . . . . . . . . . . . . . . . . . . . . . . . . Example . . . . . . . . . . . . . . . . . . . . . . . . . CVTSQLCPP (Convert Structured Query Language C++ Source) Command . Purpose . . . . . . . . . . . . . . . . . . . . . . . . . Parameters . . . . . . . . . . . . . . . . . . . . . . . . Example . . . . . . . . . . . . . . . . . . . . . . . . . DLTSQLPKG (Delete Structured Query Language Package) Command. . . 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 . . . . . . . . . . . . . . . . . . . . . . . . . Appendix E. Using the C for AS/400 and FORTRAN for AS/400 Precompilers . . . . . . . . . . . . . . . . . . . . . . . Using the C for AS/400 Precompiler . . . . . . . . . . . . . . . . Access plans . . . . . . . . . . . . . . . . . . . . . . . Host variable data types . . . . . . . . . . . . . . . . . . . Using external file descriptions . . . . . . . . . . . . . . . . . CRTSQLC (Create Structured Query Language C) Command . . . . . Using the FORTRAN/400 Precompiler . . . . . . . . . . . . . . . CRTSQLFTN (Create Structured Query Language FORTRAN) Command . Appendix F. Coding SQL Statements in FORTRAN Applications Defining the SQL Communications Area . . . . . . . . . . Defining SQL Descriptor Areas. . . . . . . . . . . . . . Embedding SQL Statements . . . . . . . . . . . . . . Comments . . . . . . . . . . . . . . . . . . . . Debug Lines . . . . . . . . . . . . . . . . . . . Continuation for SQL statements . . . . . . . . . . . . Including Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 712 715 715 728 728 731 732 744 744 748 748 761 762 763 763 765 766 769 769 781 781 782 782 783 783 783 783 784 784 786 786 792 794 794 796 796 801 . . . . . . . . . . . . . . . . 803 803 803 803 803 804 819 819 837 837 838 839 839 839 839 840 xiv DB2 UDB for AS/400 SQL Programming V4R4 Margins . . . . . . . . . . . . . . . . . Names . . . . . . . . . . . . . . . . . Statement Labels . . . . . . . . . . . . . WHENEVER Statement . . . . . . . . . . . FORTRAN Compile-Time Options . . . . . . . Using Host Variables . . . . . . . . . . . . . Declaring Host Variables . . . . . . . . . . . Determining Equivalent SQL and FORTRAN Data Types Notes on FORTRAN Variable Declaration and Usage Using Indicator Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 840 840 840 841 841 841 841 842 843 844 Bibliography . . . . . . . . . . . . . . . . . . . . . . . . . 845 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . 847 Readers’ Comments — We’d Like to Hear from You. . . . . . . . . . 879 Contents xv xvi DB2 UDB for AS/400 SQL Programming V4R4 ILE C++. v DATABASE 2/400 Advanced Database Functions.″ use the collection CORPDATA. and optimize an application program containing SQL statements. AS/400 PL/I. 1997. v Calculated columns are enclosed in parentheses. (). EXEC SQL and END-EXEC are used to delimit an SQL statement in a COBOL program. Table names that are not found in Appendix A.″ A description of how to use SQL statements in an ILE C program is provided in ″Coding SQL Statements in C Applications. v A sort sequence of *HEX is used. GG24-4249. ILE C for AS/400. or ILE RPG for AS/400 language and who can understand basic database applications. []. test. VisualAge C++ for AS/400. ILE COBOL for AS/400. Release 4. 1999 xvii . RPG III (part of RPG for AS/400). Assumptions Relating to Examples of SQL Statements The examples of SQL statements shown in this guide are based on the sample tables in Appendix A. ″DB2 UDB for AS/400 Sample Tables. © Copyright IBM Corp. and brackets. unless otherwise noted.″ v Each SQL example is shown on several lines. 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.About DB2 UDB for AS/400 SQL Programming This book explains to programmers and database administrators: v How to use the DB2 SQL for AS/400 licensed program v How to access data in a database v How to prepare. Character string literals within SQL and host language statements are delimited by apostrophes (’). Who should read this book | | | | | This guide should be used by application programmers and database administrators who are familiar with and can program with COBOL for AS/400. v Table names provided in Appendix A. REXX.″ and assume the following: v They are shown in the interactive SQL environment or they are written in ILE C or in COBOL. with each clause of the statement on a separate line. ″DB2 UDB for AS/400 Sample Tables. see the following books: v DB2 UDB for AS/400 SQL Reference v DB2 UDB for AS/400 SQL Call Level Interface Note: The DB2 UDB for AS/400 library will only be available in the AS/400e Information Center beginning in Version 4. For more information on DB2 UDB for AS/400 SQL guidelines and examples for implementation in an application programming environment. A description of how to use SQL statements in a COBOL program is provided in ″Coding SQL Statements in COBOL Applications. ″DB2 UDB for AS/400 Sample Tables. v SQL keywords are highlighted. run.″ should use collections you create. required_item required_choice1 required_choice2 If choosing one of the items is optional. The ─── symbol indicates that a statement is continued from the previous line. that item has no effect on the execution of the statement and is used only for readability. xviii DB2 UDB for AS/400 SQL Programming V4R4 . most of the examples are shown as if they were written in an application program. The ─── symbol indicates that the statement syntax is continued on the next line. required_item v Optional items appear below the main path. when using interactive SQL. How to Interpret Syntax Diagrams in this Guide Throughout this book. If you must choose one of the items. Because this guide is for the application programmer. following the path of the line. syntax is described using the structure defined as follows: v Read the syntax diagrams from left to right. For the complete description and syntax of any of the statements described in this guide. many examples can be slightly changed and run interactively by using interactive SQL. The ─── symbol indicates the beginning of a statement. they appear vertically. one item of the stack appears on the main path. required_item optional_item If an optional item appears above the main path. differs slightly from the format of the same statement when it is embedded in a program. see the DB2 UDB for AS/400 SQL Reference Whenever the examples vary from these assumptions. it is stated. The syntax of an SQL statement. Diagrams of syntactical units other than complete statements start with the ─── symbol and end with the ─── symbol. However. the entire stack appears below the main path. The ─── symbol indicates the end of a statement. v Required items appear on the horizontal line (the main path). from top to bottom.v The complete syntax of the SQL statement is usually not shown in any one example. in a stack. optional_item required_item v If you can choose from two or more items. above the main line. arithmetic operators. printing. required_item repeatable_item If the repeat arrow contains a comma. v Keywords appear in uppercase (for example. you can manage and administer your AS/400 systems from your Windows desktop. security. With AS/400 Operations Navigator. default_choice required_item optional_choice optional_choice v An arrow returning to the left. parentheses. you must enter them as part of the syntax. or other such symbols are shown. database. it will appear above the main path and the remaining choices will be shown below. You can use Operations Navigator to manage communications. and other system operations. FROM). Figure 1 on page xx shows an example of the Operations Navigator display: About DB2 UDB for AS/400 SQL Programming xix . v If punctuation marks.required_item optional_choice1 optional_choice2 If one of the items is the default. required_item repeatable_item A repeat arrow above a stack indicates that you can repeat the items in the stack. indicates an item that can be repeated. Variables appear in all lowercase letters (for example. AS/400 Operations Navigator AS/400 Operations Navigator is a powerful graphical interface for Windows clients. They must be spelled exactly as shown. Operations Navigator includes Management Central for managing multiple AS/400 systems centrally. column-name). They represent user-supplied names or values. you must separate repeated items with a comma. . you must have Client Access installed on your Windows PC. IBM recommends that you use AS/400 Operations Navigator. consult Client Access Express for Windows . AS/400 Operations Navigator Display This new interface has been designed to make you more productive and is the only user interface to new. xx DB2 UDB for AS/400 SQL Programming V4R4 . Select AS/400 Operations Navigator. double-click the AS400 Operations Navigator icon on your desktop to access Operations Navigator and create an AS/400 connection.Figure 1. For help in connecting your Windows PC to your AS/400 system. Therefore. AS/400 Operations Navigator is a separately installable component of Client Access that contains many subcomponents.) 1. you can add subcomponents by using Client Access Selective Setup. you may still need to use a traditional emulator such as PC5250 to do some of your tasks. which has online help to guide you. If you are installing for the first time and you use the Typical installation option. and printers) To select the subcomponents that you want to install. While this interface is being developed. After you install Client Access. Display the list of currently installed subcomponents in the Component Selection window of Custom installation or Selective Setup. advanced features of OS/400. select the Custom installation option. 2. the following options are installed by default: v Operations Navigator base support v Basic operations (messages. printer output.Setup. Installing Operations Navigator To use AS/400 Operations Navigator. (After Operations Navigator has been installed. SC41-5507-00. 3. Select any additional subcomponents that you want to install and continue with Custom installation or Selective Setup. ibm.com Be sure to include the following: v The name of the book. see the “Bibliography” on page 845. fill out the readers’ comment form at the back of this book. use either of the following numbers: – United States and Canada: 1-800-937-3430 – Other countries: 1-507-253-5192 v If you prefer to send comments electronically.How this book has changed | | | | | The major new features covered in this manual include: v Large objects (LOBs) v DataLinks v User-defined types v User-defined functions v Derived tables Prerequisite and related information Use the AS/400 Information Center as your starting point for looking up AS/400 technical information. Java. If you are mailing a readers’ comment form from a country other than the United States.ibm. use the readers’ comment form with the address that is printed on the back.com IBMMAIL.ibm. use one of these e-mail addresses: – Comments on books: [email protected]/pubs/html/as400/infocenter. to IBMMAIL(USIB56RZ) – Comments on the AS/400 Information Center: RCHINFOC@us. TCP/IP. You can access the Information Center from the AS/400e Information Center CD-ROM (English version: SK3T-2027) or from one of these Web sites: http://www. v If you prefer to send comments by mail. If you have any comments about this book or any other AS/400 documentation.com/infocenter http://publib. Included in the Information Center is a link that describes at a high level the differences in information between the Information Center and the Online Library. you can give the form to the local IBM branch office or IBM representative for postage-paid mailing. It also contains Internet links to Web sites such as the AS/400 Online Library and the AS/400 Technical Studio. v If you prefer to send comments by FAX. How to send your comments Your feedback is important in helping to provide the most accurate and high-quality information. and secured networks.as400. About DB2 UDB for AS/400 SQL Programming xxi .ibm.htm The AS/400 Information Center contains important topics such as logical partitioning.boulder. clustering. v The publication number of the book. For a list of related publications. Web serving. xxii DB2 UDB for AS/400 SQL Programming V4R4 .v The page number or topic to which your comment applies. For more information on interactive SQL. SQL manages information based on the relational model of data. using the IBM Distributed Relational Database Architecture* (DRDA*). Interactive SQL is part of the DB2 UDB Query Manager and SQL Development Kit licensed program. or run interactively. Distributed Relational Database Function. of this guide. 1997. 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 UDB Query Manager and SQL Development Kit licensed program is not installed. v Run SQL Statements CL command © Copyright IBM Corp. The host language compilers then compile the precompiled host source programs. Using Interactive SQL. This function is described in Chapter 28. Further information about DRDA is contained in the Distributed Database Programming book. v SQL precompilers SQL precompilers support precompiling embedded SQL statements in host languages. The precompiler support is part of the DB2 UDB Query Manager and SQL Development Kit licensed program. SQL Concepts DB2 UDB 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. SQL consists of statements and clauses that describe what you want to do with the data in a database and under what conditions you want to do it. Introduction to DB2 UDB for AS/400 Structured Query Language This guide describes the AS/400* system implementation of the Structured Query Language (SQL) using DB2 UDB for AS/400 and the DB2 UDB Query Manager and SQL Development Kit Version 4 licensed program. 1999 1 . see Chapter 18. For more information on precompiling. The following languages are supported: – ILE C for AS/400* – ILE C++ for AS/400 – VisualAge C++ for AS/400 – ILE COBOL for AS/400* – – – – COBOL for AS/400* AS/400 PL/I* RPG III (part of RPG for AS/400*) ILE RPG for AS/400* The SQL host language precompilers prepare an application program containing SQL statements. SQL statements can be embedded in high-level languages.Chapter 1. SQL can access data in a remote relational database. see Chapter 19. v SQL interactive interface SQL interactive interface allows you to create and run SQL statements. Preparing and Running a Program with SQL Statements. dynamically prepared and run. 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. For more information on the QSQCHKS API. Query Manager is part of the DB2 UDB Query Manager and SQL Development Kit licensed program. See “Controlling Parallel Processing” on page 473 for information on how to control parallel processing.RUNSQLSTM allows you to run a series of SQL statements. v v v v 2 DB2 UDB for AS/400 SQL Programming V4R4 . Coding SQL Statements in REXX Applications. and run reports on the databases. QSQPRCED is part of the OS/400 licensed program. see the DB2 UDB for AS/400 SQL Call Level Interface book. refer to the DB2 UDB for AS/400 Query Manager Use book. see the DB2 Multisystem for AS/400 book. 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. This interface is part of the DB2 UDB Query Manager and SQL Development Kit licensed program. v SQL Call Level Interface DB2 UDB for AS/400 supports the SQL Call Level Interface. and even do advanced functions such as accessing the catalogs and binding program variables to output columns. see the System API Reference book. For a complete description of all the available functions. which are stored in a source file. see Chapter 17. add data. Using the SQL Statement Processor for more information on the Run SQL Statements command. For more information on the QSQPRCED API. execute SQL statements. and their syntax. v SQL REXX Interface The SQL REXX interface allows you to run SQL statements in a REXX procedure. see the System API Reference book. For more information on DB2 Multisystem. 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. 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. QSQCHKS is part of the OS/400 licensed program. DB2 UDB Symmetric Multiprocessing This feature of the operating system provides the query optimizer with additional methods for retrieving data that include parallel processing. QSQCHKS API This API syntax checks SQL statements. Using the SQL Call Level Interface. Statements prepared into a package by this API persist until the package or statement is explicitly dropped. See Chapter 20. DB2 Multisystem This feature of the operating system allows your data to be distributed across multiple AS/400 systems. This is a standard set of procedure calls to prepare SQL statements. maintain data. one can perform all the SQL functions without the need for a precompile. For more information on using SQL statements in REXX procedures. fetch rows of data. 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. The RUNSQLSTM command is part of the DB2 UDB Query Manager and SQL Development Kit licensed program. For more information. journal receiver. The horizontal part of a table containing a serial set of columns. Groups related objects and allows Collection. selected through the SET OPTION statement. The following table shows the relationship between AS/400 system terms and SQL relational database terms. RPG for the RPG for AS/400 language. SQL statements. A set of fields. A subset of fields and records View. the default collection name is used. Row. all data is perceived as existing in tables. Chapter 1. DB2 UDB for AS/400 objects are created and maintained as AS/400 system objects. CBLI for the ILE COBOL for AS/400 language. see the DB2 UDB for AS/400 Database Programming book. data type. An object type that is used to run run SQL statements. A subset of columns and rows of one of one or more physical files. Logical file. User Profile Authorization name or Authorization ID. If the table name is not explicitly qualified and the default collection name is not specified. An object type that is used to Package. Physical file. System naming (*SYS): In the system naming convention. Field. The xxx in this command refers to the host language indicators: CI for the ILE C for AS/400 language. The naming convention used affects the method for qualifying file and table names and the terms used on the interactive SQL displays. One or more characters of related Column. for REXX. The vertical part of a table of one information of one data type. Relationship of System Terms to SQL Terms System Terms SQL Terms Library. PLI for the AS/400 PL/I language. Table. SQL Terminology There are two naming conventions that can be used in DB2 UDB for AS/400 programming: system (*SYS) and SQL (*SQL). or more tables. A set of columns and rows. 1. Record. The CVTSQLCPP command is considered part of this group of commands even though it does not start with CRT. an SQL catalog. SQL Package. The naming convention used is selected by a parameter on the SQL commands or. Consists of a library. Table 1. CBL for the COBOL for AS/400 language. a journal. For more information on database. – CREATE INDEX – The index is created into the collection or library that contains the table on which the index is being built. A collection groups related objects and allows you to find the objects by name. Introduction to DB2 UDB for AS/400 Structured Query Language 3 . and RPGI for the ILE RPG for AS/400 language. and optionally a data dictionary. a you to find the objects by name. A set of records.Relational Database and Terminology In the relational model of data. 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. – CREATE VIEW – The view is created in the first library referenced in the subselect. CPPI for the ILE C++ for AS/400 language. 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). and miscellaneous statements. 4 DB2 UDB for AS/400 SQL Programming V4R4 . the alias is created in the current library (*CURLIB). whether or not they reside in an SQL collection. Program-described files appear as a table with only a single column. dynamic SQL statements. v All other SQL statements cause SQL to search the library list (*LIBL) for the unqualified table. They do not refer to the IDDU dictionary definition for program-described files. the default qualifier is the user profile of the program owner. the default qualifier is the user profile of the job running the statement. v For dynamic SQL or interactive SQL. SQL naming (*SQL): In the SQL naming convention. the rules are: v For static SQL. the default collection name is used. data manipulation language (DML) statements. SQL statements can operate on objects that are created by SQL as well as AS/400 externally described physical files and AS/400 single-format logical files. If the table is not qualified or is not found. Types of SQL Statements There are four basic types of SQL statements: data definition language (DDL) statements.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. tables are qualified by the collection name in the form: collection. The default relational database collection (DFTRDBCOL) parameter applies only to static SQL statements. If the table name is not explicitly qualified and the default collection name is not specified.| | | – CREATE ALIAS – The alias is created into the collection or library that contains the table for which you defined the alias. Introduction to DB2 UDB for AS/400 Structured Query Language 5 . views. SQL creates and maintains these objects as AS/400 database objects.SQL DDL Statements ALTER TABLE COMMENT ON CREATE ALIAS CREATE COLLECTION CREATE DISTINCT TYPE CREATE FUNCTION CREATE INDEX CREATE PROCEDURE CREATE SCHEMA CREATE TABLE CREATE VIEW DROP ALIAS DROP COLLECTION DROP DISTINCT TYPE DROP FUNCTION DROP INDEX DROP PACKAGE DROP PROCEDURE DROP SCHEMA DROP TABLE DROP VIEW GRANT DISTINCT TYPE GRANT FUNCTION GRANT PACKAGE GRANT PROCEDURE GRANT TABLE LABEL ON RENAME REVOKE DISTINCT TYPE REVOKE FUNCTION REVOKE PACKAGE REVOKE PROCEDURE REVOKE TABLE Dynamic SQL Statements DESCRIBE EXECUTE EXECUTE IMMEDIATE PREPARE SQL DML Statements CLOSE COMMIT DECLARE CURSOR DELETE FETCH INSERT LOCK TABLE OPEN ROLLBACK SELECT INTO SET variable UPDATE VALUES INTO Miscellaneous Statements BEGIN DECLARE SECTION CALL CONNECT DECLARE PROCEDURE DECLARE STATEMENT DECLARE VARIABLE DESCRIBE TABLE DISCONNECT END DECLARE SECTION FREE LOCATOR INCLUDE RELEASE SET CONNECTION SET OPTION SET PATH SET RESULT SETS SET TRANSACTION WHENEVER SQL Objects SQL objects used on the AS/400 system are collections. SQL packages. aliases. tables. Chapter 1. indexes. A brief description of these objects follows. and catalogs. packages. indexes. views. Tables. A catalog is automatically created when you create a collection. 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. indexes. The journal and journal receiver are then used in processing SQL COMMIT and ROLLBACK statements. then it is automatically maintained by the system. The row is the horizontal part containing one or more columns. see the IDDU Use book. The journal and journal receiver can also be used as an audit trail or for forward or backward recovery. views. Catalogs An SQL catalog consists of a set of tables and views which describe tables. The column is the vertical part containing one or more rows of data of one data type. For more information on journaling. Journals and Journal Receivers A journal and journal receiver are used to record changes to tables and views in the database. indexes. and system objects (such as programs) can be created. and constraints in the collection. files. or restored into any AS/400 library. A collection consists of a library. You cannot drop or explicitly change the catalog. and optionally. Rows. and Columns A table is a two-dimensional arrangement of data consisting of rows and columns.Collections A collection provides a logical grouping of SQL objects. moved. a journal. Library QSYS2 also contains a set of catalog views built over the QSYS catalog tables which describe information about all the tables. views. v AS/400 logical files cannot be placed in an SQL collection because they cannot be described in the data dictionary. and constraints. files. moved. All data for a 6 DB2 UDB for AS/400 SQL Programming V4R4 . 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. You can create and own many collections. If SQL created the dictionary. see the Backup and Recovery book. packages. packages. see the DB2 UDB for AS/400 SQL Reference book. A data dictionary is a set of tables containing object definitions. or restored into an SQL collection. views. In each SQL collection there is a set of views built over the catalog tables which contains information about the tables. and constraints on the system. This information is contained in a set of cross-reference tables in libraries QSYS and QSYS2. For more information on IDDU. You can work with data dictionaries by using the interactive data definition utility (IDDU). which is part of the OS/400 program. procedures. a journal receiver. Tables. a data dictionary. All AS/400 files can be created or moved into an SQL collection if the SQL collection does not contain a data dictionary. a catalog. files. For more information about SQL catalogs. procedures. The following is a sample SQL table: Columns PROJNO Rows MA2100 MA2110 MA2112 MA2113 . a view contains no data. Data in a table can be distributed across AS/400 systems. RV2W573-0 Aliases An alias is an alternate name for a table or view. and can contain all the rows of given tables or some subset of them. see the DB2 Multisystem for AS/400 book. Introduction to DB2 UDB for AS/400 Structured Query Language 7 . A view can contain all the columns of given tables or some subset of them. PROJNAME MFG AUTOMATION MFG PROGRAMMING ROBOT DESIGN PROD CONTROL PROG .. DEPTNO D11 E21 E01 D11 . see the DB2 UDB for AS/400 SQL Reference book... A table in SQL is a keyed or nonkeyed physical file.. A view in SQL is a special form of a nonkeyed logical file. The columns can be arranged differently in a view than they are in the tables from which they are taken. The following figure shows a view created from the preceding example of an SQL table. See the section on data types in the DB2 UDB for AS/400 SQL Reference book for a description of data types.. 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.. It is created over one or more tables.. however.column must be of the same type.. Views A view appears like a table to an application program.. PRSTAFF 12 3 3 3 . DEPTMGR 000060 000100 000050 000060 . For more information about distributed tables. Columns PROJNO Rows MA2100 MA2110 PROJNAME MFG AUTOMATION MFG PROGRAMMING RV2W574-0 Chapter 1. Notice that the view is created only over the PROJNO and PROJNAME columns of the table and for rows MA2110 and MA2100. For more information on aliases.. Data Integrity in this book or see the DB2 UDB for AS/400 Database Programming book. Creating an index is optional. To satisfy the constraint.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. An SQL index is a keyed logical file. and joining. These arrangements are used for ordering (ORDER BY clause). see Chapter 6. Each index contains a separate arrangement. 2. UPDATE. You can create or drop an index at any time. and DELETE statements. each row of data inserted or updated in the table must make the specified condition either TRUE or unknown (due to a null value). update. However. or – Some component of the foreign key is null. grouping (GROUP BY clause). 2 Unique constraints are enforced during the execution of INSERT and UPDATE statements. For more information on triggers. a large number of indexes can adversely affect the performance of applications that change the table. Unique constraints can be created using the CREATE TABLE and ALTER TABLE statements. Check constraints can be added using the CREATE TABLE and ALTER TABLE statements. because the indexes are maintained by the system. such an index is not a constraint. Referential constraints are enforced during the execution of INSERT. The index is automatically maintained by the system. 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 delete operation. An event can be an insert. The difference is that a PRIMARY KEY cannot contain any nullable columns. The trigger can be run either before or after the event. A PRIMARY KEY constraint is a form of UNIQUE constraint. Data Integrity. You can create any number of indexes. 8 DB2 UDB for AS/400 SQL Programming V4R4 . Check constraints are enforced during the execution of INSERT and UPDATE statements. Although CREATE INDEX can create a unique index that also guarantees uniqueness. Constraints Constraints are rules enforced by the database manager. For more information on constraints. Triggers A trigger is a set of actions that are executed automatically whenever a specified event occurs to a specified base table. v Check constraints A check constraint is a rule that limits the values allowed in a column or group of columns. see Chapter 6. DB2 UDB 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. The index is used by the system for faster data retrieval. Preparing and Running a Program with SQL Statements. External functions can be any AS/400 ILE program or service program. and sourced functions. DB2 UDB for AS/400 supports both non-ILE and ILE precompilers. An SQL procedure is defined entirely in SQL and can contain SQL statements including SQL control statements. This section briefly describes the process of creating a DB2 UDB for AS/400 application. A sourced function is built over any built-in or any existing user-defined function. see “Chapter 9. Additional information on creating DB2 UDB for AS/400 application programs is in Chapter 18. The following shows the objects Chapter 1. Packages can also be created using the CRTSQLPKG command. External stored procedures can be any AS/400 program or REXX procedure. see Chapter 7. DB2 UDB for AS/400 supports external functions. or service programs. Distributed Relational Database Function SQL packages can also be created using the QSQPRCED API.Stored Procedures | | | | | | | | | | | | | | | A stored procedure is a program that can be called using the SQL CALL statement. An SQL function is defined entirely in SQL and can contain SQL statements. Introduction to DB2 UDB for AS/400 Structured Query Language 9 . see Chapter 28. For more information on stored procedures. Application Program Objects The process of creating a DB2 UDB for AS/400 application program may result in the creation of several objects. DB2 UDB for AS/400 supports external stored procedures and SQL procedures. For more information on user-defined functions. 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. the module object for ILE programs v The program or service program v The SQL package for distributed programs With a nondistributed non-ILE DB2 UDB for AS/400 program. including SQL control statements. The DBMS uses the control structure to process SQL statements encountered while running the application program. you must manage only the original source and the resulting program. With DB2 UDB for AS/400 you may need to manage the following objects: v The original source v Optionally. Writing User-Defined Functions (UDFs)” on page 185. For more information on QSQPRCED. 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). User-defined functions A user-defined function is a program that can be invoked like any built-in function. Application programs may be either distributed or nondistributed. see the System API Reference book. For more information about packages and distributed relational database function. Stored Procedures. They cannot be System/36 programs or procedures. SQL functions. the resulting program.involved and steps that happen during the precompile and compile processes for a nondistributed non-ILE DB2 UDB for AS/400 program: User Source File Member Precompile Temporary Source File Member Processed SQL Statements Compile Program Access Plan RV2W565-1 With a nondistributed ILE DB2 UDB for AS/400 program. The following shows the objects and steps that occur during the precompile and compile processes for a distributed ILE DB2 UDB for AS/400 program: 10 DB2 UDB for AS/400 SQL Programming V4R4 . An SQL package can be created for each distributed module in a distributed ILE program or service program. you must manage the original source. module objects. you must manage the original source. and the resulting program or service program. you may need to manage the original source. the resulting program or service program. the modules. and the resulting packages. The following shows the objects and steps that occur during the precompile and compile processes for a distributed non-ILE DB2 UDB for AS/400 program: Create Compile Program SQL Package Access Plan SQL Package User Source File Member Precompile Temporary Source File Member Processed SQL Statements Access Plan RV2W566-2 With a distributed ILE DB2 UDB for AS/400 program. The following shows the objects involved and steps that happen during the precompile and compile processes for a nondistributed ILE DB2 UDB for AS/400 program when OBJTYPE(*PGM) is specified on the precompile command: User Source Precompile File Member Temporary Source File Member Processed SQL Statements Compile Module Bind Program Processed SQL Statements Access Plan RV2W569-0 With a distributed non-ILE DB2 UDB for AS/400 program. and the resulting package. If the precompile process uses the QTEMP library. 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. Preparing and Running a Program with SQL Statements. see Chapter 18. If. You can create and maintain the source file member by using the source entry utility (SEU). User Source File Member A source file member contains the programmer’s application language and SQL statements. A member with the same name as the program name is added to the output source file. You can specify the output source file as a permanent file name on the precompile commands. Introduction to DB2 UDB for AS/400 Structured Query Language 11 . a negative SQLCODE is returned. By default. 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. For more information on precompilers. Chapter 1. which have replaced embedded SQL statements v Parsed and syntax-checked SQL statements By default. Access plans are stored and maintained in the program object for nondistributed SQL programs and in the SQL package for distributed SQL programs. the table or view still cannot be found or you are still not authorized. This member contains the following items: v Calls to the SQL run-time support. the precompile process (CRTSQLxxx commands) creates a temporary source file called QSQLTEMP (QSQLTEMP1 for CRTSQLRPGI) in library QTEMP. a part of the AS/400 Application Development Tools licensed program. Output Source File Member The SQL precompile creates an output source file member. at that time. It is created only when the program has successfully created. the system automatically deletes the file when the job completes.User Source File Member Precompile Temporary Source File Member Processed SQL Statements Compile Module Bind Program Create SQL Package SQL Package Processed SQL Statements Access Plan Access Plan RV2W570-1 Note: The access plans associated with the DB2 UDB for AS/400 distributed program object are not created until the program is run locally. the precompiler calls the host language compiler. An access plan is a set of internal structures and information that tells SQL how to run an embedded SQL statement most effectively. 12 DB2 UDB for AS/400 SQL Programming V4R4 . CBL. v When the Create SQL Package (CRTSQLPKG) command is run. the SQL access plans are not created until the modules are bound into either a program or service program. however. 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.Package An SQL package contains the access plans for a distributed SQL program. Because the name of the SQL package is critical for running distributed SQL programs. This improves call performance to these routines without including the code in the calling program. the name of the SQL package and an internal consistency token are saved in the 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. CPP. When a distributed SQL program is created. You usually bind several modules together. You can run a module only if you use the Create Program (CRTPGM) command to bind it into a program. Modules contain information about the SQL statements. but you can bind a module by itself. These are used at run time to find the SQL package and to verify that the SQL package is correct for this program. Bound programs and other service programs can access these routines by resolving their imports to the exports provided by a service program. an SQL package cannot be: v v v v Moved Renamed Duplicated Restored to a different library Module A module is an Integrated Language Environment (ILE) object that is created by compiling source code using the CRTxxxMOD command (or any of the CRTBNDxxx commands where xxx is C. The connections to these services are made when the calling programs are created. or RPG). Using Interactive SQL. 1999 13 . and other objects. tables. A description of how to use SQL statements and clauses in more complex situations is provided in Chapter 3. Creating an SQL Collection | | | An SQL collection is the basic object in which tables. the examples use the interactive SQL interface to show the execution of SQL statements. see “Example: Creating the SQL Collection (SAMPLECOLL)”. indexes. option 1 (Change session attributes). | | | | | | In this chapter. In those cases. The syntax for each of the SQL statements used in this chapter is described in detail in the DB2 UDB for AS/400 SQL Reference book. Some tasks described here can also be done using Operations Navigator. Getting Started with SQL | | This chapter describes how to create and work with SQL collections. When the Enter SQL Statements display appears. For an example of creating a collection using interactive SQL. Or you can use the SQL CREATE COLLECTION statement. the information about the task notes that it can be done using Operations Navigator. views. Advanced Coding Techniques. Basic Concepts and Techniques and Chapter 5. and views using SQL statements. You can specify this on the F13 (Services) panel. Example: Creating the SQL Collection (SAMPLECOLL) | | You can create a sample collection. Starting Interactive SQL To start using interactive SQL for the following examples. 1997. One way to create a collection (called a library) is by using Operations Navigator.Chapter 2. named SAMPLECOLL. and methods for reading data from the objects. For more information on interactive SQL and the STRSQL command. Each SQL interface provides methods for using SQL statements to define tables. views. and packages are placed. methods for updating the objects. you are ready to start typing SQL Statements. make sure that you set the naming mode to SQL naming. see Chapter 19. If you are reusing an existing interactive SQL session. type: STRSQL NAMING(*SQL) and press Enter. by typing the following SQL statement on the Enter SQL Statements display and pressing Enter: © Copyright IBM Corp. | | | | | | | | | | | | | | | | | Enter SQL Statements Type SQL statement. and order quantity will have user supplied default values. type CREATE TABLE and press F4 (Prompt). and the number last ordered. views. their cost. It means ″unknown″. you can create tables. For more information on the default values used by INSERT. define the physical attributes of the columns in the table. see “The INSERT Statement” on page 31 Example: Creating a Table (INVENTORY_LIST) We are going to create a table to maintain information about the current inventory of a business. see “Example: Creating a Table (INVENTORY_LIST)”. It will have information about the items kept in the inventory. quantity on hand. not even to other null values. press Enter. It cannot be null. It is not equal to any value. A default value is assigned to a column when a row is added to a table and no value is specified for that column. views. On the Enter SQL Statements display. The last order date and quantity ordered will allow the null value. Tables. The item name. A null value indicates the absence of a column value for a row. either a default value or a user supplied value. a value must be assigned to the column. and define constraints to restrict the values that are allowed in the table. | | | | | | | | | | | | | | | | | | | When creating a table. you need to understand the concepts of null value and default value. The following display is shown (with the input areas not yet filled in): 14 DB2 UDB for AS/400 SQL Programming V4R4 . After you have successfully created a collection. The CREATE TABLE statement allows you to create a table. quantity currently on hand. the last order date. If a column does not allow the null value. The item number will be a required value. the system default value will be used. Creating and Using a Table | | | | You can create a table by using the SQL CREATE TABLE statement or by using Operations Navigator. and indexes can also be created in libraries instead of collections. If a specific default value is not defined for a column. For an example of creating a table using interactive SQL. It is not the same as a value of zero or all blanks. and indexes in it. Current connection is to relational database SYSTEM1 ===> CREATE COLLECTION SAMPLECOLL_________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ Bottom F3=Exit F4=Prompt F6=Insert line F9=Retrieve F10=Copy line F12=Cancel F13=Services F24=More keys Note: Running this statement causes several objects to be created and takes several seconds. | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Specify CREATE TABLE Statement Type information. . . . . N Y=Yes. . . N=No F5=Refresh F12=Cancel F6=Insert line F14=Delete line F10=Copy line F24=More keys F3=Exit F4=Prompt F11=Display more attributes Note: Another way of entering column definitions is to press F4 (Prompt) with your cursor on one of the column entries in the list. . . . . . Chapter 2. . F4 for list 1=NULL. and the null attribute. Data: INVENTORY_LIST______ SAMPLECOLL__ Name Name. . . . . . . . . Each column you want to define for the table is represented by an entry in the list on the lower part of the display. . . Collection . INVENTORY_LIST in SAMPLECOLL. press Enter to create the table. for the Table and Collection prompts. Press F11 to see more attributes that can be specified for the columns. . N=No Y=Yes. 2=SBCS. N Y=Yes. . . . . . . . . For each column. . 4=CCSID Data _ _ _ _ _ _ _ Allocate _____ _____ _____ _____ _____ _____ _____ Column ITEM NUMBER_______ ITEM NAME_________ UNIT_COST_________ QUANTITY_ON_HAND__ LAST_ORDER_DATE___ ORDER_QUANTITY____ __________________ CCSID CONSTRAINT Default _____ N __________________ _____ N '***UNKNOWN***'___ _____ N __________________ _____ N NULL______________ _____ N __________________ _____ N 20________________ _____ _ __________________ Bottom Table CONSTRAINT . . 3=NOT NULL WITH DEFAULT FOR Column ____________ ____________ ____________ ____________ ____________ ____________ ____________ Type CHAR___________ VARCHAR________ DECIMAL________ SMALLINT_______ DATE___________ SMALLINT_______ _______________ N N Length Scale 6____ __ 20___ __ 8____ 2_ _____ __ _____ __ _____ __ _____ __ Y=Yes. . . . The Enter SQL Statements display will be shown again with a message indicating that the table has been created. . Distributed Table . . Table . press Enter. . . . . . . When all the values have been entered. . type the name of the column. . Nulls: INVENTORY_LIST______ SAMPLECOLL__ Name Name. . Getting Started with SQL 15 . N=No Nulls 2 3 3 1 1 1 3 Bottom Column ITEM_NUMBER_______ ITEM_NAME_________ UNIT_COST_________ QUANTITY_ON_HAND__ LAST_ORDER_DATE___ ORDER_QUANTITY____ __________________ Table CONSTRAINT . . F3=Exit F4=Prompt F11=Display more attributes F5=Refresh F12=Cancel F6=Insert line F14=Delete line F10=Copy line F24=More keys Type the table name and collection name of the table you are creating. . its length and scale. . . . . press Enter. N=No Distributed Table . . Specify CREATE TABLE Statement Type information. . the data type of the column. . . . . Collection . Table . . . . 2=NOT NULL. . 3=MIXED. . . . This is where a default value may be specified. F4 for list 1=BIT. . . . . . This will bring up a display that shows all of the attributes for defining a single column. . we will need a second table as well. LAST_ORDER_DATE DATE. The following display will appear: 16 DB2 UDB for AS/400 SQL Programming V4R4 . which items they supply. To create it. ITEM_NUMBER CHAR(6) NOT NULL.| | | | | | | | | | You can directly key in this CREATE TABLE statement on the Enter SQL Statements display as follows: CREATE TABLE SAMPLECOLL. UNIT_COST DECIMAL(8.INVENTORY_LIST (ITEM_NUMBER CHAR(6) NOT NULL. either type it in directly on the Enter SQL Statements display or press F4 (Prompt) to use the interactive SQL displays to create the definition.2)) Using the LABEL ON Statement Normally. It will also allow us to see more columns of our data on a single display. Since we are going to be running our examples in interactive SQL. This table will contain information about suppliers of our inventory items. Even though the column names are descriptive. we will use the LABEL ON statement to change the column headings.2) NOT NULL WITH DEFAULT. ITEM_NAME VARCHAR(20) NOT NULL WITH DEFAULT '***UNKNOWN***'. ORDER_QUANTITY SMALLINT DEFAULT 20) Creating the Supplier Table (SUPPLIERS) Later in our examples. the column name is used as the column heading when showing the output of a SELECT statement in interactive SQL.SUPPLIERS (SUPPLIER_NUMBER CHAR(4) NOT NULL. QUANTITY_ON_HAND SMALLINT DEFAULT NULL. you can create a more descriptive label for the column name. it will be easier to read if the column headings show each part of the name on a single line. and the cost of the item from that supplier. By using the LABEL ON statement. type LABEL ON COLUMN on the Enter SQL Statements display and press F4 (Prompt). To change the labels for our columns. SUPPLIER_COST DECIMAL(8. CREATE TABLE SAMPLECOLL. .... .. not the name that was actually specified in the statement. .2.+..+..3..1...+.. INVENTORY_LIST______ SAMPLECOLL__ 1 F3=Exit F4=Prompt F5=Refresh F21=Display statement F12=Cancel F20=Display full names Type in the name of the table and collection containing the columns for which you want to add labels and press Enter. Option . The table name in the message is the system table name for this table. The ruler across the top of the column heading entry area can be used to easily space the headings correctly. The following message indicates that the LABEL ON statement was successful. Getting Started with SQL 17 .. 2 1=Table or view 2=Column 3=Package 4=Alias Name. 'ITEM NUMBER'___________________________ 'ITEM NAME'_____________________________ 'UNIT COST'_____________________________ 'QUANTITY ON HAND'_________ 'LAST ORDER DATE'_________ 'NUMBER ORDERED'__________________________ F3=Exit F14=Delete line 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.Specify LABEL ON Statement Type choices.+. press Enter. . Column ITEM_NUMBER ITEM_NAME UNIT_COST QUANTITY_ON_HAND LAST_ORDER_DATE ORDER_QUANTITY Column Heading .. F4 for list Name. DB2 UDB for AS/400 maintains Chapter 2....... .+. .. ...5.. F4 for list 1=Column heading 2=Text Table or view Collection .. .. LABEL ON for INVEN00001 in SAMPLECOLL completed.4. press Enter.. Label on . . 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...... prompting you for each of the columns in the table. press Enter. The following display will be shown. When the headings are typed.. Specify LABEL ON Statement Type information.. . . see “Example: Inserting Information into a Table (INVENTORY_LIST)”. information (data) into it by using Operations Navigator. Select columns to insert INTO . WITH isolation level . COST'. For more information on system table names. Type choices. . Collection . Press Enter to see the display where the columns you want to insert values into can be selected. or add. . 4=CS. Change the Select columns to insert INTO prompt to Yes. . 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'. . 1 1=Current level. 5=RS (ALL) 6=RR INVENTORY_LIST______ SAMPLECOLL__ Y 1 Name. . . on the Enter SQL Statements display. . . . press Enter. | | | | | | | | | | | | | | | | | | | | | | | | | | | | For an example of inserting data into a table using interactive SQL. . press Enter. NAME'.two names for tables with names longer than ten characters. 2=NC (NONE) 3=UR (CHG). INTO table . . . . Insertion method . . ON ORDER ORDERED') HAND'. . see the CREATE TABLE statement in the DB2 UDB for AS/400 SQL Reference book. Inserting Information into a Table After you create a table. Specify INSERT Statement Type choices. . . DATE'. . F4 for list Y=Yes. . N=No 1=Input VALUES 2=Subselect F3=Exit F4=Prompt F5=Refresh F21=Display statement F12=Cancel F20=Display full names Type the table name and collection name in the input fields as shown. 18 DB2 UDB for AS/400 SQL Programming V4R4 . The Specify INSERT Statement display will be shown. Or you can use the SQL INSERT statement. . F4 for list Name. Example: Inserting Information into a Table (INVENTORY_LIST) To work with interactive SQL. type INSERT and press F4 (Prompt). . you can insert. QUANTITY_ON_HAND) Chapter 2. Getting Started with SQL 19 . We will let the other columns have their default value inserted. Specify INSERT Statement Type values to insert. The sequence numbers on this display indicate the order that the columns and values will be listed in the INSERT statement. press Enter.INVENTORY_LIST (ITEM_NUMBER. The values for the columns that were not specified will have a default value inserted. ITEM_NAME. Press Enter to show the display where values for the selected columns can be typed. the value specified as the default value on the CREATE TABLE statement. red'_______________________________________ 10. UNIT_COST. You can type the INSERT statement on the Enter SQL Statements display as: INSERT INTO SAMPLECOLL. press Enter.Specify INSERT Statement Type sequence numbers (1-999) to make selections. providing information about the column definition. A row containing these values will be added to the table.00________________________________________________ 25___________________________________________________ F3=Exit F12=Cancel 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. For ORDER_QUANTITY it will be 20. For LAST_ORDER_DATE it will be the null value since no default was provided and the column allows the null value. This will show a different view of the insert values display. Seq 1__ 2__ 3__ 4__ ___ ___ Column ITEM_NUMBER ITEM_NAME UNIT_COST QUANTITY_ON_HAND LAST_ORDER_DATE ORDER_QUANTITY Type CHARACTER VARCHAR DECIMAL SMALLINT DATE SMALLINT Length Scale 6 20 8 2 4 4 Bottom F3=Exit F5=Refresh F20=Display entire name F12=Cancel F19=Display system column names F21=Display statement | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | In this example. Column ITEM_NUMBER ITEM_NAME UNIT_COST QUANTITY_ON_HAND Value '153047'_____________________________________________ 'Pencils. press F11 (Display type). we only want to insert into four of the columns. Type the values to be inserted for all of the columns and press Enter. In SQL. 25) To add the next row to the table. This will copy the previous INSERT statement to the typing area.00 8.SUPPLIERS table. For example. specify only the column names for which you want to insert a value.00 20.00 3. this is done with the SELECT statement.50 225. legal Envelopes. red Lined tablets UNIT_COST 10.00 1. to insert the third row. This statement is composed of three main clauses: 20 DB2 UDB for AS/400 SQL Programming V4R4 .00 2.50 17.00 9.00 | The sample collection now contains two tables with several rows of data in each. press F9 (Retrieve) on the Enter SQL Statements display. 10. ITEM_NUMBER 153047 229740 544931 303476 559343 291124 775298 073956 Paper clips Envelopes.00 1. Continue using the INSERT statement to add the following rows to the table.| | | | | | | | | | | | | | VALUES('153047'.00. SUPPLIER_NUMBER 1234 1234 1234 9988 9988 2424 2424 5546 3366 3366 ITEM_NUMBER 153047 229740 303476 153047 559343 153047 303476 775298 303476 073956 SUPPLIER_COST 10. 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. Getting Information from a Single Table Now that we have inserted all the information into our tables. 'Pencils.00 1.00 2. red'.00 6 25 ITEM_NAME Pencils. The SELECT statement is the most complex of all SQL statements. 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.50 5.00 3. secretary Pens. black 225. standard Chairs. we need to be able to look at it again. Values not shown in the chart below should not be inserted so that the default will be used.00 3. In the INSERT statement column list.00 100 500 QUANTITY_ON_HAND 25 120 Add the following rows to the SAMPLECOLL. .+.00 25 20 ******** End of data ******** F3=Exit F12=Cancel F19=Left F20=Right F21=Split Display Data 71 The column headings that were defined using the LABEL ON statement are shown.+. red 10. secretary 225. which specifies the table or tables containing the columns with the desired data. . N=No Y=Yes. . .. . SAMPLECOLL. . .. . legal 3..+. .. . . . . ..20 303476 Paper clips 2.. standard . . Press Enter and the statement will run to select all of the data for all of the columns in the table. and in the DB2 UDB for AS/400 SQL Reference book... ..+. . .. . black 20. . .. . Shift to column . .. which affect the final form of returned data. .1. Press F4 for a list.. .. The SELECT clause. Getting Started with SQL 21 . To see the values we inserted into the INVENTORY_LIST table. . .+. .. N=No Type choices. N=No Y=Yes. .. . . . 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 Type the table name in the FROM tables field on the display.. .7. . The following output will be shown: Data width . FOR UPDATE OF columns ....00 25 20 229740 Lined tablets 1. GROUP BY columns . . . . type * for the SELECT columns field on the display.. ...... . . .. . In addition to the three main clauses. ITEM ITEM UNIT QUANTITY LAST NUMBER NUMBER NAME COST ON ORDER ORDERED HAND DATE 153047 Pencils. Specify additional options ..20 775298 Chairs. . . . The ITEM_NAME for the third entry has the default value that was specified in the CREATE TABLE statement.00 . To select all columns from the table.+. there are several other clauses described in “Using Basic SQL Statements and Clauses” on page 31. UNION with another SELECT . The FROM clause. . . . . . DISTINCT rows in result table .. type SELECT and press F4 (prompt). 3. ORDER BY columns .. . which specifies those columns containing the desired data.INVENTORY_LIST____________________ *____________________________________________ _____________________________________________ _____________________________________________ _____________________________________________ _____________________________________________ _____________________________________________ Bottom N N N Y=Yes. . . The WHERE clause.2. . WHERE conditions . . . HAVING conditions . . .00 6 20 073956 Pens.00 100 20 559343 Envelopes...+. . . which supplies conditions that determine which rows of data are retrieved. The QUANTITY_ON_HAND column has a null value for Chapter 2.. . .. . The following display will be shown: Specify SELECT Statement Type SELECT statement information. . . . . .. . .50 120 20 544931 ***UNKNOWN*** 5.. . .00 .00 500 20 291124 Envelopes.. FROM tables .5. . .1. SELECT columns . .3..6.. press Enter. .4. .. 2... : Position to line . Specify additional options . . DISTINCT rows in result table . press Enter.. . WHERE conditions . . . UNIT_COST. . . . . . .. .. type SELECT and press F4 (Prompt)...00____________________________ _____________________________________________ _____________________________________________ _____________________________________________ _____________________________________________ Bottom N N N Y=Yes... . . UNION with another SELECT ..INVENTORY_LIST____________________ ITEM_NUMBER. . N=No Type choices. . . . When Enter is pressed. . . . UNIT_COST.. GROUP BY columns . Specify SELECT Statement Type SELECT statement information.3. .00 Chairs.. 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 Although only one line is initially shown for each prompt on the Specify SELECT Statement display.00 Pens. SAMPLECOLL. and only have the values for the columns ITEM_NUMBER. . . .. or a longer. ITEM_NAME____________ UNIT_COST > 10. HAVING conditions .. This could be used if more columns were to be entered in the SELECT columns list. . FROM tables . . This statement could be entered on the Enter SQL Statements display as: SELECT * FROM SAMPLECOLL. . . Shift to column . . . . and ITEM_NAME returned.. the WHERE clause is used. . .. . . N=No Y=Yes. . the columns you want to see must be specified. more complex WHERE condition were needed. .+... . ITEM UNIT ITEM NUMBER COST NAME 775298 225. . . Similarly.. . To restrict the number of output rows returned. . . Furthermore. . .. N=No Y=Yes. . Fill in the display as shown above.1. . .the rows where no value was inserted. To see only the items that cost more than 10 dollars. The following output will be seen: Data width . . the only data values returned are 22 DB2 UDB for AS/400 SQL Programming V4R4 . . ORDER BY columns . FOR UPDATE OF columns . . . The Specify SELECT Statement display will be shown. . .. SELECT columns . . . . . . . . . ..INVENTORY_LIST To limit the number of columns returned by the SELECT statement.. : Position to line . black ******** End of data ******** F3=Exit F12=Cancel F19=Left F20=Right F21=Split Display Data 41 The only rows returned are those whose data values compare with the condition specified in the WHERE clause. . . F6 (Insert line) can be used to add more lines to any of the input areas in the top part of the display. . the SELECT statement is run.2. . secretary 073956 20. .+..+.4. .. Press F4 for a list. . . . 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.. . . .+. . . the ORDER_QUANTITY column contains the default value for all rows. Running this example returns the following output: Chapter 2. ITEM_NAME FROM SAMPLECOLL. The item name is not in the SUPPLIERS table. Data values of columns other than those explicitly identified are not returned. In this SELECT statement. the column name must be qualified by the table name to specify which column is really being referenced. a join operation is specified by placing the names of those tables you want to join together into the same FROM clause of a SELECT statement.INVENTORY_LIST WHERE UNIT_COST > 10. ITEM_NUMBER.ITEM_NUMBER = Y. This operation is called a join operation. ITEM_NAME FROM SAMPLECOLL. Whenever the same column name exists in two or more tables being joined. The names X and Y are then used to qualify the ITEM_NUMBER column name.INVENTORY_LIST WHERE SAMPLECOLL. This statement could have been entered on the Enter SQL Statements display as: SELECT ITEM_NUMBER.ITEM_NUMBER Another way to enter the same statement is to use a correlation name. SAMPLECOLL. SAMPLECOLL. the following SELECT statement can be used.ITEM_NUMBER = SAMPLECOLL.SUPPLIERS is given a correlation name of X and SAMPLECOLL. For more information on correlation names. It is in the INVENTORY_LIST table. both table names need to be typed on the FROM tables input line. Suppose you want to see a list of all the suppliers and the item numbers and item names for their supplied items. the column name ITEM_NUMBER is defined in both tables so the column name needs to be qualified by the table name.SUPPLIERS.SUPPLIERS. Y. It can be specified following each table name in the FROM list. The previous statement could be rewritten as: SELECT SUPPLIER_NUMBER. If the columns had different names.INVENTORY_LIST.ITEM_NUMBER. there would be no confusion so qualification would not be needed. SELECT SUPPLIER_NUMBER. To perform this join. A correlation name provides another name for a table name to use in a statement.ITEM_NUMBER In this example. Enter it by typing it directly on the Enter SQL Statements display or by prompting. SAMPLECOLL. UNIT_COST.from the columns you explicitly specified in the SELECT clause. (For a more detailed description of the join operation.ITEM_NUMBER. we can see all three of the columns as if they were from a single table. If using prompting. see the DB2 UDB for AS/400 SQL Reference book. A correlation name must be used when the table names are the same. see “Joining Data from More Than One Table” on page 75).INVENTORY_LIST. SAMPLECOLL.INVENTORY_LIST is given a correlation name of Y. ITEM_NAME FROM SAMPLECOLL.INVENTORY_LIST Y WHERE X.SUPPLIERS X. Getting Started with SQL 23 .00 Getting Information from More Than One Table SQL allows you to get information from columns contained in more than one table. Using the common column. In SQL. . . .. ITEM_NAME FROM SAMPLECOLL.INVENTORY_LIST Y WHERE X. Y.2.Data width . . secretary 3366 073956 Pens..ITEM_NUMBER = Y. The following is an example of using ORDER BY to guarantee the order of the rows. . the SUPPLIER_NUMBER column name is used as the column heading..ITEM_NUMBER Running the previous statement would produce the following output.. : Position to line ..+ SUPPLIER_NUMBER ITEM ITEM NUMBER NAME 1234 153047 Pencils. . black ******** End of data ******** F3=Exit F12=Cancel F19=Left F20=Right F21=Split Display Data 45 The data values in the result table represent a composite of the data values contained in the two tables INVENTORY_LIST and SUPPLIERS....ITEM_NUMBER ORDER BY SUPPLIER_NUMBER.. . Shift to column .. red 2424 153047 Pencils.. .. ...4. red 1234 229740 Lined tablets 1234 303476 Paper clips 2424 303476 Paper clips 3366 303476 Paper clips 9988 559343 Envelopes. . . Y...+. .. Any item numbers that do not appear in the SUPPLIER table are not shown in this result table.+. .+. This result table contains the supplier number from the SUPPLIER table and the item number and item name from the INVENTORY_LIST table... . The statement will first order the result table by the SUPPLIER_NUMBER column.ITEM_NUMBER. SELECT SUPPLIER_NUMBER. SAMPLECOLL.+... 24 DB2 UDB for AS/400 SQL Programming V4R4 .3.SUPPLIERS X. . red 9988 153047 Pencils. The results are not guaranteed to be in any order unless the ORDER BY clause is specified for the SELECT statement. legal 5546 775298 Chairs. . Rows with the same value for SUPPLIER_NUMBER will be ordered by their ITEM_NUMBER.... Since we did not change any column headings for the SUPPLIER table.1... .... if you use the WHERE clause. black 3366 303476 Paper clips 5546 775298 Chairs.. . red 2424 303476 Paper clips 3366 073956 Pens. For more information see.. . . “The UPDATE Statement” on page 33.2.. use the WHERE clause with the UPDATE statement. Shift to column . .. The Specify UPDATE Statement display will be shown. see “Example: Changing Information in a Table”. : Position to line . . Example: Changing Information in a Table Suppose we want to use interactive SQL and are placing an order for more paper clips today. the system changes only the rows satisfying the conditions that you specify. . For an example of changing information in a table using interactive SQL.. .. Getting Started with SQL 25 . legal ******** End of data ******** F3=Exit F12=Cancel F19=Left F20=Right F21=Split Display Data 45 Changing Information in a Table | | | You can use the SQL UPDATE statement to change the data values in some or all of the columns of a table.. If you do not specify the WHERE clause.1.+. type UPDATE and press F4 (Prompt).. .... However.+. Chapter 2....3. red 1234 229740 Lined tablets 1234 303476 Paper clips 2424 153047 Pencils. . .. all of the rows in the specified table are changed. ... red 9988 559343 Envelopes.+. For more information. see “The WHERE Clause” on page 38. You may also use Operations Navigator to accomplish this task.. | | | | | | | | | | | If you want to limit the number of rows being changed during a single statement execution.. secretary 9988 153047 Pencils..Data width .+ SUPPLIER_NUMBER ITEM ITEM NUMBER NAME 1234 153047 Pencils.4... To update the LAST_ORDER_DATE and ORDER_QUANTITY for item number 303476.. . . ..+. Correlation . . . F4 for list Name Type information. The display will be shown again with the list of columns in the table. . . Correlation . If a WHERE condition is not specified. . Specify UPDATE Statement Type choices. . . press Enter to see the display on which the WHERE condition can be specified.| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Specify UPDATE Statement Type choices. INVENTORY_LIST______ SAMPLECOLL__ ____________________ Name. F4 for list Name F3=Exit F4=Prompt F5=Refresh F21=Display statement F12=Cancel F20=Display full names After typing the table name and collection name. . . . Collection . . all the rows in the table will be updated using the values from the previous display. press Enter. . . INVENTORY_LIST______ SAMPLECOLL__ ____________________ Name. press Enter. . . . . F4 for list Name. After typing the values to be updated for the table. . . . . Column ITEM_NUMBER ITEM_NAME UNIT_COST QUANTITY_ON_HAND LAST_ORDER_DATE ORDER_QUANTITY F3=Exit F4=Prompt F11=Display type Value _____________________________________________________ _____________________________________________________ _____________________________________________________ _____________________________________________________ CURRENT DATE_________________________________________ 50___________________________________________________ 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 today’s date. . F4 for list Name. . press Enter. . . 26 DB2 UDB for AS/400 SQL Programming V4R4 . Collection . press Enter. Table . . Table . . . . . +.00 . .00 . This date is always the date the update is run.. . black 20.. .. The NUMBER_ORDERED shows its updated value....00 25 20 ******** End of data ******** Bottom F3=Exit F12=Cancel F19=Left F20=Right F21=Split Display Data Only the entry for Paper clips was changed.. Press F4 for a list...2.. WITH isolation level .| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Specify UPDATE Statement Type WHERE conditions.+. .. Shift to column .. . . ORDER_QUANTITY = 50 WHERE ITEM_NUMBER = '303476' Running a SELECT statement to get all the rows from the table (SELECT * FROM SAMPLECOLL. press Enter.. 4=CS. red 10.. . . .20 775298 Chairs...00 6 20 073956 Pens..+. press Enter to perform the update on the table.. 2=NC (NONE) 3=UR (CHG).50 120 20 544931 ***UNKNOWN*** 5.. The LAST_ORDER_DATE was changed to be the current date.INVENTORY_LIST SET LAST_ORDER_DATE = CURRENT DATE.. This statement could have been typed on the Enter SQL Statements display as: UPDATE SAMPLECOLL. secretary 225.. returns the following result: Data width . standard ..4.6.00 25 20 229740 Lined tablets 1.5..7.3.1. 5=RS (ALL) 6=RR 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. .. 1 Bottom 1=Current level.20 303476 Paper clips 2. Getting Started with SQL 27 . ..+..00 500 20 291124 Envelopes. legal 3.. . press Enter..+. ITEM ITEM UNIT QUANTITY LAST NUMBER NUMBER NAME COST ON ORDER ORDERED HAND DATE 153047 Pencils... .. .+...... Chapter 2. . ITEM_NUMBER = '303476'________________________________________________ ______________________________________________________________________ Type choices. : 71 Position to line ..00 100 05/30/94 50 559343 Envelopes..INVENTORY_LIST).+... ... . A message will indicate that the function is complete. 28 DB2 UDB for AS/400 SQL Programming V4R4 . see “The DELETE Statement” on page 34.. Shift to column . using the SQL DELETE statement. ... See Chapter 6. Data Integrity for more information on using WITH CHECK OPTION.1...50 120 20 303476 Paper clips 2... You can create a view using Operations Navigator. at the same time..+. For more information. For an example of deleting information in a table using interactive SQL..5. Running another SELECT statement after the delete has completed will return the following result table: Data width ..00 25 20 ******** End of data ******** F3=Exit F12=Cancel F19=Left F20=Right F21=Split Display Data 71 Bottom The rows with a null value for QUANTITY_ON_HAND were deleted........ .. You may also want to give users access to only part of the data in a table. Or you can use the SQL CREATE VIEW statement. However. .. You can use the WHERE clause with the DELETE statement to identify rows to be deleted during a single statement execution. .00 25 20 229740 Lined tablets 1. defining a view on a table is like creating a new table containing just the columns and rows you want.. red 10. rows that do not match the selection criteria may still be inserted through a view if the SQL WITH CHECK OPTION is not used.. .. Views provide a way to subset the table so that you deal with only the data you need. it cannot access rows or columns of the table that are not included in the view. you can delete entire rows from a table when they no longer contain needed information. secretary 225.00 6 20 073956 Pens. .+...... see “Example: Deleting Information from a Table (INVENTORY_LIST)”..00 500 20 775298 Chairs.INVENTORY_LIST WHERE QUANTITY_ON_HAND IS NULL To check a column for the null value.. Creating and Using a View | | | | You may find that no single table contains all the information you need. . Or. black 20. the IS NULL comparison is used.+.. ..6. ..4.. . you could enter the following statement on the Enter SQL Statements display: DELETE FROM SAMPLECOLL.7.. Example: Deleting Information from a Table (INVENTORY_LIST) If we want to remove all the rows in our table that have the null value for the QUANTITY_ON_HAND column.3. . . Using the CREATE VIEW statement.2.00 100 05/30/94 50 559343 Envelopes... When your application uses a view. .... : Position to line . ITEM ITEM UNIT QUANTITY LAST NUMBER NUMBER NAME COST ON ORDER ORDERED HAND DATE 153047 Pencils. .Deleting Information from a Table | | | | | | | You can delete data from a table by using Operations Navigator. . A view reduces complexity and. legal 3.+.+.+.. restricts access...+. See “Creating and Using Views” on page 95 for additional information. Because a view is derived from a table that exists in storage. the columns in the view have the same name as the columns in the table because no column list follows the view name. see the following: v Example: “Example: Creating a view on a single table” or v Example: “Example: Creating a view combining data from more than one table” on page 30 In order to create a view you must have the proper authority to the tables or physical files on which the view is based.14 DAYS In the example above. The view has no data of its own and therefore requires no storage for the data. QUANTITY_ON_HAND FROM SAMPLECOLL. The view will contain only the rows for items that were ordered in the last two weeks. The table has six columns. LAST_ORDER_DATE.RECENT_ORDERS Chapter 2. For INSERT. Example: Creating a view on a single table The following example shows how to create a view on a single table. and QUANTITY_ON_HAND. The order of the columns in the SELECT clause is the order in which they will appear in the view. Getting Started with SQL 29 . columns in the table that are not in the view must have a default value.RECENT_ORDERS AS SELECT ITEM_NUMBER. If you do not specify column names in the view definition. The view is built on the INVENTORY_LIST table. when you update the view data. The CREATE VIEW statement looks like this: CREATE VIEW SAMPLECOLL. See the CREATE VIEW statement in the SQL Reference for a list of authorities needed. Therefore. you are really updating data in the table.INVENTORY_LIST WHERE LAST_ORDER_DATE > CURRENT DATE . LAST_ORDER_DATE. but the view uses only three of the columns: ITEM_NUMBER. The following display is the result of running the SQL statement: SELECT * FROM SAMPLECOLL. You can use the view as though it were a table. even though the view is totally dependent on one or more tables for data. views are automatically kept up-to-date as the tables they depend on are updated.| | | | | For examples of creating a view using interactive SQL. 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. You can make changes to a table through a view even if the view has a different number of columns or rows than the table. the column names will be the same as those for the table on which the view is based. ...SUPPLIERS B WHERE A. .00 8. .4. . ... A.. : Position to line .00 17.. SUPPLIER_NUMBER ITEM UNIT SUPPLIER_COST NUMBER COST 9988 153047 10. .. .Display Data Position to line . These are joined with the ITEM_NUMBER column and the SUPPLIER_COST column of the SUPPLIERS table.. . ... . and a column with the cost of the item.. SAMPLECOLL. . ... : Shift to column .1.INVENTORY_LIST A..50 3366 073956 20.. UNIT_COST.. 30 DB2 UDB for AS/400 SQL Programming V4R4 .2. All other dates in our table still have the null value so they are not returned. . ..1.... .00 2424 153047 10..00 ******** End of data ******** F3=Exit F12=Cancel F19=Left F20=Right F21=Split Display Data 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... . . SUPPLIER_COST FROM SAMPLECOLL.+.00 3366 303476 2...... .5.....LOWER_COST Data width .LOWER_COST AS SELECT SUPPLIER_NUMBER.. .+. The view will only contain those item numbers for suppliers that can supply an item at lower cost than the current unit cost. Example: Creating a view combining data from more than one table You can create a view that combines data from two or more tables by naming more than one table in the FROM clause. . . The CREATE VIEW statement looks like this: CREATE VIEW SAMPLECOLL.+. . UNIT_COST. the INVENTORY_LIST table contains a column of item numbers called ITEM_NUMBER. .00 1.ITEM_NUMBER.. ..00 1234 229740 1.+.ITEM_NUMBER = B.. . .+. Shift to column . In the following example. ITEM LAST QUANTITY NUMBER ORDER ON DATE HAND 303476 05/30/94 100 ******** End of data ******** F3=Exit F12=Cancel F19=Left Data width .. ...2. . A WHERE clause is used to limit the number of rows returned.+.50 1... 26 F20=Right F21=Split Bottom The only row selected by the view is the row that we updated to have the current date. .ITEM_NUMBER AND UNIT_COST > SUPPLIER_COST The following table is the result of running the SQL statement: SELECT * FROM SAMPLECOLL.+..00 9.3. .+.. .. or many rows to a table.Chapter 3. Notes: 1. UPDATE. delete. “Inserting Rows into a Table Using a Select-Statement” on page 69 explains how to use the select-statement within an INSERT statement to add zero. and database physical and logical files. FETCH statements can be used in an application program to access data as well. Character strings specified in an SQL statement (such as those used with WHERE or VALUES clauses) are case sensitive. WHERE ADMRDEPT='a00' WHERE ADMRDEPT='A00' (does not return a result) (returns a valid department number) Comparisons may not be case sensitive if a shared-weight sort sequence is being used where uppercase and lowercase characters are treated as the same character. “Using the Blocked Insert Statement” on page 70 explains how to use the blocked form of the INSERT statement to add multiple rows to a table. The rules for the continuation of lines are the same as those of the host language (the language the program is written in). The SQL statements described in this section can be run on SQL tables and views. 1997. Note: Because views are built on tables and actually contain no data. Basic Concepts and Techniques This chapter explains some of the concepts used in SQL statements. See “Creating and Using Views” on page 95 for more information on inserting data by using a view. This statement is covered in Chapter 4. 1999 31 . The SQL statements used are SELECT. The INSERT Statement You can use the INSERT statement to add new rows to a table or view in one of the following ways: v Specifying values in the INSERT statement for columns of the single row to be added. and INSERT. You can write SQL statements on one line or on many lines. It discusses many of the common statements and clauses in SQL. v Specifying the blocked form of the INSERT statement to add multiple rows. and insert data into tables and views. Using Basic SQL Statements and Clauses This section shows the basic SQL statements and clauses that retrieve. 2. Examples using these SQL statements are supplied to help you develop SQL applications. working with views can be confusing. views. v Including a select-statement in the INSERT statement to tell SQL what data for the new row is contained in another table or view. and files can be either in an SQL collection or in a library. Detailed syntax and parameter descriptions for SQL statements are given in the DB2 UDB for AS/400 SQL Reference book. © Copyright IBM Corp. uppercase characters must be entered in uppercase and lowercase characters must be entered in lowercase. DELETE. DB2 UDB for AS/400 Sample Tables. The examples in this chapter refer to the tables shown in Appendix A. update. The tables. that is. one. COMMIT(*CS). the default value is placed in the column. v For varying length character or graphic columns or LOB columns. If you specify COMMIT(*ALL).. time. but is defined to allow the null value (NOT NULL was not specified in the column definition). the default is a zero length string. an error might occur. SQL places the null value in the column. unique key.’’).. When your program attempts to insert a row that duplicates another row already in the table. the default date/time value is extracted from the system when the block is written. and timestamp columns. the default value corresponds to DLVALUE(’’. v For distinct-type columns. If DEFAULT was specified for the column definition without an explicit default value. depending on the option used when the index was created. You must provide a value in the VALUES clause for each column named in an INSERT statement’s column list. or unique index. If SQL finds an error while running the INSERT statement. v You can verify that you are giving the values in the proper order based on the column names. or timestamp. no rows are inserted. ) VALUES (value-for-column1. the default value is 0. The default value is used. ) The INTO clause names the columns for which you specify values. it stops inserting data. the row is not inserted. v For fixed length character or graphic columns. the keyword DEFAULT may be used as a value on the VALUES clause. Rows already inserted by this statement.. Instead. It is a good idea to name all columns into which you are inserting values because: v Your INSERT statement is more descriptive. time. the default is blanks. COMMIT(*CHG). When inserting a block of records. the row can be inserted without error. in the case of INSERT | | | | | 32 DB2 UDB for AS/400 SQL Programming V4R4 . If a column has a default value. you must supply a value for each column defined with the NOT NULL attribute if that column does not have a default value. unique key. or COMMIT(*RR). The INSERT statement for adding a row to a table or view may look like this: INSERT INTO table-name (column1. If the column is defined to allow null values or to have a default. v For date.. value-for-column2. . column2. v If the table has a primary key. v For numeric columns. Multiple null values may or may not be considered duplicate values. SQL places the default value for that data type in the column. v If the table does not have a primary key. The column name list can be omitted if all columns in the table have a value provided in the VALUES clause. or unique index. you do not need to name it in the column name list or specify a value for it. . v You have better data independence. SQL returns an SQLCODE of −803. v For DataLink columns. The order in which the columns are defined in the table does not affect your INSERT statement.For every row you insert. This means that the column will be assigned the same default value for each row in the block.’URL’. the default value is the default value of the corresponding source type. The VALUES clause specifies a value for each column named in the INTO clause. If the column does not have a default value defined for it. If the column is defined to have a default value. the default value is the current date. Chapter 3.. . A special register. A host variable. USER. The column must be defined as capable of containing a null value when the table was created. Replace the column’s current value with the value that results from an expression. suppose an employee was relocated. Replace the column’s current value with a special register value. use the UPDATE statement. This allows the database manager to reuse any rows in the table that were marked as deleted. To update several items of the employee’s data in the CORPDATA. any rows already inserted are not deleted. Replace the column’s current value with the contents of a host variable. Replace the column’s current value with the value provided in the SET clause. column-2 = value-2.with a select-statement or blocked insert. 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 UPDATE statement looks like this: UPDATE table-name SET column-1 = value-1. An expression. The value you specify can be: A column name. A null value. With the UPDATE statement. The SET clause names the columns you want updated and provides the values you want them changed to. Replace the column’s current value with the null value. A constant. the SQLERRD(3) field of the SQLCA has a value of 1. If the row is inserted without error. using the keyword NULL.EMPLOYEE table to reflect the move. Replace the column’s current value with the contents of another column in the same row. you can specify: UPDATE CORPDATA.EMPLOYEE SET JOB = :PGM-CODE.. WHERE search-condition . Basic Concepts and Techniques 33 . The result of the UPDATE statement is one or more changed column values in zero or more rows of a table (depending on how many rows satisfy the search condition specified in the WHERE clause). For example. you can change the value of one or more columns in each row that satisfies the search condition of the WHERE clause. are deleted.. Note: For blocked INSERT or for INSERT with select-statement.. The order in which rows are inserted does not guarantee the order in which they will be retrieved. or an error occurs. The expression can contain any of the values in this list. PHONENO = :PGM-PHONE WHERE EMPNO = :PGM-SERIAL Use the SET clause to specify a new value for each column you want to update. for example. If you specify COMMIT(*NONE). A table created by SQL is created with the Reuse Deleted Records parameter of *YES. more than one row can be inserted. The UPDATE Statement To change the data in a table. The number of rows inserted is reflected in SQLERRD(3). no rows in the table are changed (rows already changed by this statement. an SQLCODE of +100 is returned. if any. or COMMIT(*RR). COL5 = AMT . any rows already changed are not restored to previous values.. If the database manager finds an error while running your UPDATE statement. The result of the DELETE statement is the removal of zero or more rows of a table (depending on how many rows satisfy the search condition specified in the WHERE clause). The DELETE statement looks like this: DELETE FROM table-name WHERE search-condition . COMMIT(*CHG). The number of rows updated is reflected in SQLERRD(3). SQL removes all the rows of the table. The DELETE Statement To remove rows from a table. use a WHERE clause that selects only the rows you want to update. Note: UPDATE with a WHERE clause may have updated more than one row. you remove the entire row. DELETE does not remove specific columns from the row. Replace the column’s current value with the value that the subquery returns.EMPLOYEE table with a WORKDEPT value of D11 as follows: DELETE FROM CORPDATA. You want to delete each row in the CORPDATA.EMPLOYEE WHERE WORKDEPT = 'D11' The WHERE clause tells SQL which rows you want to delete from the table. If COMMIT(*NONE) is specified. it stops updating and returns a negative SQLCODE. COL2 = NULL. v To update several rows.6. Replace the column’s current value with the default value of the column. If you specify COMMIT(*ALL). use the DELETE statement. COL6 = COL7 WHERE EMPNO = :PGM-SERIAL To identify the rows to be updated. COMMIT(*CS). When you DELETE a row. You can 34 DB2 UDB for AS/400 SQL Programming V4R4 . are restored to their previous values).00. use a WHERE clause that selects only one row. use the WHERE clause: v To update a single row. The following is an example of a statement that uses many different values: UPDATE WORKTABLE SET COL1 = 'ASC'. If the database manager cannot find any rows that satisfy the search condition. or an error occurs. You can omit the WHERE clause. The column must have a default value defined for it or allow the NULL value. If you omit the WHERE clause from a DELETE statement. COL3 = :FIELD3. COL4 = CURRENT TIME. For example. If you do.. SQL deletes all the rows that satisfy the search condition from the base table. The DEFAULT keyword. SQL updates each row in the table or view with the values you supply.A scalar subselect. suppose department D11 was moved to another place. are restored to their previous values). The other clauses are optional. because a DELETE statement without a WHERE clause deletes all the rows from the table or view. The format and syntax shown here are very basic. if any. If you specify COMMIT(*ALL). Furthermore. You can use the “The WHERE Clause” on page 38. One way to do this is to use the SELECT INTO statement in a program to retrieve a specific row (for example. no rows in the table are deleted (rows already deleted by this statement. it stops deleting data and returns a negative SQLCODE. The SELECT INTO Statement | | | | | | | You can use a variety of statements and clauses to query your data. and “The ORDER BY Clause” on page 43 to tailor your query to gather data in a specific manner. COMMIT(*CS). Chapter 3. The name of each host variable used to contain retrieved data 3. SELECT INTO statements can be more varied than the examples presented in this chapter. “The GROUP BY Clause” on page 40. and FROM clauses must be specified. The name of each column you want 2. The name of each column used to group your data 6. A search condition to uniquely identify the row that contains the information you want 5. COMMIT(*CHG). INTO. If COMMIT(*NONE) is specified. “The HAVING Clause” on page 42. but it is best to include one. If SQL finds an error while running your DELETE statement. The order of the results so a specific row among duplicates can be returned. issue the DROP statement (described in the DB2 UDB for AS/400 SQL Reference book). or COMMIT(*RR). To delete a table definition as well as the table contents. a variety of clauses are used to gather data in a specific way. an SQLCODE of +100 is returned. Note: DELETE with WHERE clause may have deleted more than one row. A SELECT INTO statement looks like this: SELECT column names INTO host variables FROM table or view name WHERE search condition GROUP BY column names HAVING search condition ORDER BY column-name The SELECT. A SELECT INTO statement can include the following: 1. any rows already deleted are not restored to their previous values. The number of rows deleted is reflected in SQLERRD(3).omit the WHERE clause. The name of the table or view that contains the data 4. Basic Concepts and Techniques 35 . the row for an employee). in this example. A search condition that uniquely identifies a group that contains the information you want 7. If SQL cannot find any rows that satisfy the search condition. These restrictions are described in “Creating and Using Views” on page 95. If you use the ORDER BY clause. Finding more than one row is an error. and so on. You can retrieve data from a view in exactly the same way you retrieve data from a table. If you want more than one row to be the result of a select-statement. If SQL is unable to find a row that satisfies the search condition. However. Using cursors is described in “Chapter 4. an SQLCODE of +100 is returned. If SQL finds more host variables than results.The INTO clause names the host variables (variables in your program used to contain retrieved column values). insert. use a DECLARE CURSOR statement to select the rows. would be exactly one row (or no rows). Data retrieval errors If SQL finds that a retrieved character or graphic column is too long to be placed in a host variable. You want to retrieve the department name and manager number from the CORPDATA. there are several restrictions when you attempt to update. :PGM-MGRNO FROM CORPDATA. your program can set PGM-DEPT to the value C01 and issue: SELECT DEPTNAME. To do this. For example. or delete data in a view. +326 is returned. a negative SQLCODE is returned. the first row in the result table is returned. the second value is put into the second host variable. If SQL finds errors while running your select-statement. For example. You can control which row will be returned in this error condition by specifying the ORDER BY clause.DEPARTMENT WHERE DEPTNO = :PGM-DEPT When the statement is run. each row in the CORPDATA. MGRNO INTO :PGM-DEPTNAME.DEPARTMENT table for department C01. assume that each department listed in the CORPDATA.EMPLOYEE table has a unique EMPNO (employee number) column. Using a Cursor” on page 55. The value of the first column specified in the SELECT clause is put into the first host variable named in the INTO clause. The FROM clause names the table (or view) that contains the data you are interested in. followed by a FETCH statement to move the column values into host variables one or many rows at a time. The result of a SELECT INTO statement for this table if the WHERE clause contains an equal comparison on the EMPNO column. The result table for a SELECT INTO should contain just one row. the result is one row: PGM-DEPTNAME INFORMATION CENTER PGM-MGRNO 000030 These values are assigned to the host variables PGM-DEPTNAME and PGM-MGRNO.DEPARTMENT table has a unique department number. SQL does the following: 36 DB2 UDB for AS/400 SQL Programming V4R4 . but one row is still returned. It is not ordered as if it were a null (higher than all other values). – SQL returns all valid data for that row. v +304 . the result column is normally ordered as if it were a null value (higher than all other values). overflow. or timestamp is not a valid value. or timestamp is not valid. or division by zero). v Sets the indicator variable. For data mapping errors.Numeric conversion error (for example. the SQLCA reports only the last error detected. v +191 . This is because the expression was evaluated before the assignment to the host variable is attempted. the data is considered equal to a null value if the query is completed as a sort.MIXED data is not properly formed. Basic Concepts and Techniques 37 . underflow. 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. Data mapping errors include: v +138 .Syntax for a string representation of a date. v +183 .String representation of a date. v Sets SQLWARN0 and SQLWARN1 in the SQLCA to the value 'W'. 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.Characters cannot be converted. the result column is ordered as if it were a null value. and that same expression is used in the ORDER BY clause.Character in the CAST argument is not valid. The indicator variable corresponding to each result column having an error is set to −2. v +420 . the result record is ordered based on the value of the expression. If SQL finds a data mapping error while running a statement.Argument of the substringing function is not valid.v Truncates the data while assigning the value to the host variable. time. v +181 . If an existing index is used. v +802 . 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. the data is not considered equal to a null. The resulting date or timestamp is not within the valid range of dates or timestamps. v +331 . SQL returns the corresponding negative SQLCODE in the SQLCA. time. If the ORDER BY clause is implemented by using a sort. if provided. – SQL returns a positive SQLCODE.Invalid result from a date/time expression. to the length of the value before truncation. v If an indicator variable is not provided.Data conversion or data mapping error. v +180 . If the full-select contains DISTINCT in the select list and a column in the select list contains numeric data that is not valid. If the ORDER BY clause is Chapter 3. LASTNAME. – The expression is a decimal column and a numeric value that is not valid is detected. When you look at the source code statement.. update. The number of rows you process with an SQL statement then depends on the number of rows that satisfy the WHERE clause search condition. or *JUL. . WHERE WORKDEPT = 'C01' 38 DB2 UDB for AS/400 SQL Programming V4R4 . . If a column is added to a table or view you access and you use “SELECT * ..implemented by using an existing index. to specify that you are interested in the rows where the department number is C01. For example. WORKDEPT = 'C01' is a predicate.. You can specify that only one column be retrieved. you specify the name of each column you want to retrieve. 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. . . If you want to retrieve all columns (in the same order as they appear in the row). or delete. and the equal sign (=) is a comparison operator. WORKDEPT and 'C01' are expressions. For example: SELECT EMPNO. There are two reasons for this: 1. The extra column causes you to get a warning (not an error) in the SQLCA (SQLWARN4 will contain a “W”). Note that character values are enclosed in apostrophes ('). In the following example. A predicate specifies a test that you want SQL to apply to a specified row or rows of a table. The value of each column you name is retrieved in the order specified in the SELECT clause. you would say: . A search condition consists of one or more predicates. 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. WORKDEPT .” and you create the program again from source. numeric values are not. and a date conversion error occurs because the date is not within the valid range for dates.. *DMY. use an asterisk (*) instead of naming the columns: SELECT * . This applies to all constant values wherever they are coded within an SQL statement. When using the select-statement in an application program. *YMD. the INTO clause does not have a matching host variable named for the new column. 2. list the column names to give your program more data independence. The WHERE Clause The WHERE clause specifies a search condition that identifies the row or rows you want to retrieve. The SELECT Clause With the SELECT clause (the first part of a select-statement). or as many as 8000 columns. – The expression is a character column and a character could not be converted.. X = Y or X <> Y) can be performed on character data.. a literal value) A column A host variable A value returned from a function A special register Another expression For example: . when evaluated by SQL. the sort sequence that is in effect when the query is run is applied to those predicates. Using Expressions in the WHERE Clause An expression in a WHERE clause names or specifies something you want to compare to something else. v An expression identifies two values that are added (+). For example: . or a numeric value. Multiplication. divided (/). The operands of an expression can be: A constant (that is.. the search condition consists of one predicate: WORKDEPT = 'C01'. WHERE EMPNO = '000200' EMPNO names a column that is defined as a 6-byte character value. Addition and subtraction Operators on the same precedence level are applied from left to right. Equality comparisons (that is..In this case. Prefix operators 2. For example: . v A constant specifies a literal value for the expression. division. You also cannot perform arithmetic operations on character data (even though EMPNO is a character string that appears to be a number). WHERE 40000 < SALARY SALARY names a column that is defined as an 9-digit packed decimal value (DECIMAL(9. You can add and subtract date/time values. the expression is evaluated in the following order: 1.2)). or concatenated (CONCAT or ||) to result in a value. subtracted (−).. multiplied (*). v A host variable identifies a variable in an application program. WHERE EMPNO = :EMP Chapter 3. WHERE INTEGER(PRENDATE .. Each expression. Basic Concepts and Techniques 39 . Other types of comparisons can also be evaluated for character data. If the search condition contains character or UCS-2 graphic column predicates.. and concatenation 4.. date/time/timestamp. have exponentiation (**). The expressions you specify can be: v A column name names a column. It is compared to the numeric constant 40000.PRSTDATE) > 100 When the order of evaluation is not specified by parentheses. you cannot compare character strings to numbers. Exponentiation 3. See “Using Sort Sequence in SQL” on page 50 for more information on sort sequence and selection.. However. is a character string. For example: . TRUE if the predicate is FALSE. 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) The NOT Keyword You can precede a predicate with the NOT keyword to specify that you want the opposite of the predicate’s value (that is. For example... to indicate that you are interested in all employees except those working in department C01. More complex search conditions and predicates are described in “Performing Complex Search Conditions” on page 72. For example: . if the value of a row is null. SQL divides the selected rows into groups such that the rows of each group have matching values in one or more columns or expressions. WHERE NOT WORKDEPT = 'C01' which is equivalent to: . the function is applied to each group. When you specify a GROUP BY clause. WHERE DUE_DATE IS NULL A search condition need not be limited to two column names or constants separated by arithmetic or comparison operators.. you need to know how SQL evaluates search conditions and predicates. No matter how complex the search condition. or greater than the value specified in the search condition. To fully understand the WHERE clause. WHERE LASTNAME = USER v The NULL value specifies the condition of having an unknown value. There is also an unknown truth value.. it supplies a TRUE or FALSE value when evaluated against a row. You can specify one or more columns or 40 DB2 UDB for AS/400 SQL Programming V4R4 . thereby returning as many rows as there are groups.. and compares the values of expressions. Next. WHERE WORKDEPT <> 'C01' The GROUP BY Clause Without a GROUP BY clause. . This topic is discussed in the DB2 UDB for AS/400 SQL Reference book. That is. You can develop a complex search condition that specifies several predicates separated by AND and OR. | | | | | The GROUP BY clause allows you to find the characteristics of groups of rows rather than individual rows. equal to.. or vice versa). SQL processes each group to produce a single-row result for the group. the application of SQL column functions returns one row. NOT applies only to the predicate it precedes. this null value is not returned as a result of a search because it is not less than. When GROUP BY is used.v A special register identifies a special value generated by the database manager. not to all predicates in the WHERE clause.. which is effectively false. you could say: .. RV2W552-3 Chapter 3. Grouping puts each selected row in a group..| | | expressions in the GROUP BY clause to group the rows.. The items you specify in the SELECT statement are properties of each group of rows. suppose you want a list of the number of people working on each major project described in the CORPDATA. a single-row result is produced for the data in the rows with null values. you could issue: The SQL statement: Results in: fetch WORK-DEPT AVG-SALARY 1 2 .. 42833 41250 . For example.) 2. For example.. You could issue: The SQL statement: Results in: fetch SUM-PR 1 2 3 . A00 B01 .. and each set consists of rows describing members of a specific department. ( “The ORDER BY Clause” on page 43 describes how to do this. To find the average salary of people in each department. Basic Concepts and Techniques 41 .. which SQL then processes to derive characteristics of the group. 3. Ordering the rows puts all the rows in the results table in ascending or descending collating sequence. | | | | When you use GROUP BY. the sort sequence in effect when the query is run is applied to the grouping.PROJECT table.. 6 5 10 .. See “Using Sort Sequence in SQL” on page 50 for more information on sort sequence and selection. Grouping the rows does not mean ordering them. the CORPDATA. one for each department. MAJ-PROJ AD3100 AD3110 MA2100 . Notes: 1.. If the grouping occurs over character or UCS-2 graphic columns. you list the columns or expressions you want SQL to use to group the rows. If there are null values in the column you specify in the GROUP BY clause.. RV2W551-1 The result is several rows... not properties of individual rows in a table or view.EMPLOYEE table has several sets of rows. . The HAVING clause says that you want only those groups that satisfy the condition in that clause. SQL examines and process all rows in the CORPDATA... In addition.. SEX F M M F . The HAVING clause tests a property of the group. To do this.. suppose you wanted to retrieve the average salary of women in each department. use the HAVING clause. the test is on MIN(EDLEVEL).. which is a group property: 42 DB2 UDB for AS/400 SQL Programming V4R4 . AVG-WAGES 52750 37875 41250 30156 . A00 A00 B01 C01 . RV2W553-1 Because you did not include a WHERE clause in this example. you could issue a select-statement to find the average salary for men and women in each department.The result is a list of the company’s current major projects and the number of people working on each project. 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. The HAVING Clause You can use the HAVING clause to specify a search condition for the groups selected based on a GROUP BY clause. the search condition you specify in the HAVING clause must test properties of each group rather than properties of individual rows in the group.. For example.EMPLOYEE table. | | | | You can also specify that you want the rows grouped by more than one column or expression. To specify that you want this data only when all the female employees in the selected department have an education level equal to or greater than 16 (a college graduate).EMPLOYEE table. Therefore. The HAVING clause follows the GROUP BY clause and can contain the same kind of search condition you can specify in a WHERE clause.. For example. To do this. In this case. using the CORPDATA. you could issue: The SQL statement: Results in: fetch DEPT 1 2 3 4 . you can specify column functions in a HAVING clause. you would use the AVG column function and group the resulting rows by WORKDEPT and specify a WHERE clause of SEX = 'F'. you cannot include a GROUP BY or HAVING clause in the SELECT statement within a DECLARE CURSOR statement. The ORDER BY Clause | | | | | You can specify that you want selected rows retrieved in a particular order. It is processed during the initial phase of the query processing. (The DECLARE CURSOR statement is described in “Chapter 4. you could use this select-statement: Chapter 3. and you can use NOT for any predicate of a search condition. with the ORDER BY clause. 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. For example. to retrieve the names and department numbers of female employees listed in the alphanumeric order of their department numbers. sorted by ascending or descending collating sequence of a column’s value. Note: If you intend to update a column or delete a row. See “Using Sort Sequence in SQL” on page 50 for more information on sort sequence and selection.The SQL statement: Results in: fetch DEPT 1 2 3 A00 C01 D11 AVG-WAGES 52750 30156 24476 MIN-EDUC 18 16 17 RV2W554-3 You can use multiple predicates in a HAVING clause by connecting them with AND and OR.) 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. You can use an ORDER BY clause as you would a GROUP BY clause: specify the columns or expressions you want SQL to use when retrieving the rows in a collated sequence. The HAVING selection is performed in post processing of the result table. Basic Concepts and Techniques 43 . Using a Cursor” on page 55. or something other than a column name.. you can either specify the exact same expression in the ORDER BY clause.The SQL statement: Results in: fetch PGM-NAME3 1 2 3 4 5 6 7 8 9 10 11 12 13 HAAS KWAN QUINTANA NICHOLLS PIANKA SCOUTTEN LUTZ PULASKI JOHNSON PEREZ HENDERSON SCHNEIDER SETRIGHT DEPT A00 C01 C01 C01 D11 D11 D11 D21 D21 D21 E11 E11 E11 RV2W555-3 Notes: 1. In the above select-statement. For example. as specified by the select-statement. An ascending collating sequence is the default. All columns named in the ORDER BY clause must also be named in the SELECT list. Use a number to order the rows of the results table when the sequencing value is not a named column. 2. SQL first returns the row with the lowest department 44 DB2 UDB for AS/400 SQL Programming V4R4 . You can also specify whether you want SQL to collate the rows in ascending (ASC) or descending (DESC) sequence.. ORDER BY 3 specifies that you want the results ordered by the third column of the results table. to retrieve the full name of employees listed in alphabetic order. This name can be specified in the ORDER BY clause. you can use a number. v The name must not be qualified. The AS clause names the result column. ORDER BY FULLNAME | | | | This select-statement could optionally be written as: SELECT LASTNAME CONCAT FIRSTNAME ORDER BY LASTNAME CONCAT FIRSTNAME Instead of naming the columns to order the results. Null values are ordered as the highest value. To order by a name specified in the AS clause: v The name must be unique in the select-list. you could use this select-statement: SELECT LASTNAME CONCAT FIRSTNAME AS FULLNAME . For example. you can specify an AS clause in the select-list. | | | | To order by a column function. To order by an expression. or you can specify an AS clause in the select-list. Basic Concepts and Techniques 45 . In the example above. To select the values for all rows that contain a null value for the manager number. see the DB2 UDB for AS/400 SQL Reference book. contains a null value. ORDER BY WORKDEPT. equal to. you might want the rows ordered first by department number. To do this. Normally.. DEPTNAME. Using Null Values A null value indicates the absence of a column value in a row. ORDER BY WORKDEPT DESC As with GROUP BY. ordered by employee name. To order the rows in descending collating sequence based on the department number. specify: .DEPARTMENT WHERE MGRNO IS NULL The result would be: DEPTNO DEPTNAME D01 DEVELOPMENT CENTER ADMRDEPT A00 To get the rows that do not have a null value for the manager number. followed by rows with higher department numbers. a WHERE clause can specify a column that. you could change the WHERE clause like this: WHERE MGRNO IS NOT NULL For more information on the use of null values. for some rows. See “Using Sort Sequence in SQL” on page 50 for more information on sort sequence and its affect on ordering. ADMRDEPT FROM CORPDATA. and within each department. and as a mathematical argument. a comparison predicate using a column that contains null values does not select a row that has a null value for the column. you could specify: SELECT DEPTNO. A null value is the same as “unknown”.. nor greater than the value specified in the condition. This is because a null value is neither less than.. Null values can be used as a condition in the WHERE and HAVING clauses. A null value is not the same as zero or all blanks.. For example. specify: . ordering for these columns is based on the sort sequence in effect when the query is run. you can specify a secondary ordering sequence (or several levels of ordering sequences) as well as a primary one. LASTNAME If character columns or UCS-2 graphic columns are used in the ORDER BY clause. the special registers and their contents are shown in the following table: Special Registers CURRENT DATE CURRENT_DATE Contents The current date. Chapter 3.number (alphabetically and numerically). For locally run SQL statements. Using Special Registers You can specify certain “special registers” in SQL statements. The run-time authorization identifier of the server job on the remote system. The current path value at the remote system. procedure names. CURRENT TIME. not the local system.Special Registers CURRENT TIME CURRENT_TIME CURRENT TIMESTAMP CURRENT_TIMESTAMP CURRENT TIMEZONE CURRENT_TIMEZONE Contents The current time. The run-time authorization identifier (user profile) of the job. all values are based on a single clock reading.CURRENT TIMEZONE = UTC It is taken from the system value QUTCOFFSET. CURTIME. or the CURDATE. If a single statement contains more than one reference to any of CURRENT DATE. A duration of time that links the remote system time to UTC. the special registers and their contents are shown in the following table: Special Registers CURRENT DATE CURRENT_DATE CURRENT TIME CURRENT_TIME CURRENT TIMESTAMP CURRENT_TIMESTAMP CURRENT TIMEZONE CURRENT_TIMEZONE CURRENT SERVER CURRENT_SERVER USER CURRENT PATH CURRENT_PATH CURRENT FUNCTION PATH Contents The current date and time at the remote system. or NOW scalar functions. The SQL path used to resolve unqualified data type names. and function names. CURRENT SERVER CURRENT_SERVER USER CURRENT PATH CURRENT_PATH CURRENT FUNCTION PATH The name of the relational database as contained in the relational database directory table in the relational database directory. For more information on distributed tables. The current date and time in timestamp format. A duration of time that links local time to Universal Coordinated Time (UTC) using the formula: local time . When a query over a distributed table references a special register. see DB2 Multisystem for AS/400 book. the contents of the special register on the system that requests the query are used. The name of the relational database as contained in the relational database directory table in the relational database directory. or CURRENT TIMESTAMP special registers. For remotely run SQL statements. 46 DB2 UDB for AS/400 SQL Programming V4R4 . the character string ’1950-01-01’ is interpreted as a date. see Chapter 2 of the DB2 UDB for AS/400 SQL Reference book . The value of each is based on a time-of-day clock reading obtained during the running of the statement. Multiple references to CURRENT DATE. Date. and timestamp are data types represented in an internal form not seen by the SQL user. or the VALUES clause of an INSERT statement. time. time. and Timestamp Date. For a detailed description of date and time arithmetic. CURRENT TIME.CURRENT TIMEZONE FROM DATETIME Date/Time Arithmetic Addition and subtraction are the only arithmetic operators applicable to date. and timestamp values. or CURRENT TIMESTAMP within the same SQL statement use the same value. or TIMESTAMP scalar functions. and timestamp can be represented by character string values and assigned to character string variables. or CURRENT TIMESTAMP special registers. time. The following statement returns the age (in years) of each employee in the EMPLOYEE table when the statement is run: SELECT YEAR(CURRENT DATE . a time from a time. Time. For more information on character string formats of date. WHERE HIREDATE < '1950-01-01' if HIREDATE is a date column. or CURRENT TIMESTAMP. or timestamp by a duration. The database manager recognizes the following as date. see Chapter 2 of the DB2 UDB for AS/400 SQL Reference book. time. CURRENT TIME. time. and timestamp values: v A value returned by the DATE. time. v A character string when it is an operand of an arithmetic expression or a comparison and the other operand is a date. For example. or timestamp column in either the SET clause of an UPDATE statement. and timestamp values. if you have a table named DATETIME. you can use the following statement: SELECT STARTT . For example. time.Using Date. in the predicate: .EMPLOYEE The CURRENT TIMEZONE special register allows a local time to be converted to Universal Coordinated Time (UTC).. v A value returned by the CURRENT DATE. or timestamp in an expression by specifying one of three special registers: CURRENT DATE. TIME. Specifying Current Date and Time Values You can specify a current date. time. and you want to convert STARTT to UTC.. or timestamp. CURRENT TIME. or subtract a date from a date. containing a time column type with a name of STARTT. time. Basic Concepts and Techniques 47 .BIRTHDATE) FROM CORPDATA. You can increment and decrement a date. v A character string variable or constant used to set a date. Chapter 3. or a timestamp from a timestamp. views. Unlike overrides. an alias can be created for the second member so that SQL can easily refer to it. column name. 48 DB2 UDB for AS/400 SQL Programming V4R4 .DEPARTMENT. The following DROP statement will drop table MYLIB. CREATE ALIAS MYLIB. or SQL package name.MYMBR2_ALIAS VALUES('ABC'. These labels can be seen in the SQL catalog in the LABEL column.Creating and using ALIAS names | | | | When you refer to an existing table or view to an AS/400 physical file that consists of multiple members. You can create an alias for v A table or view v A member of a table A table alias defines a name for the file.MYMBR2_ALIAS FOR MYLIB. You can use the SQL CREATE ALIAS statement to do this. The label for tables. you can create a more descriptive label for the table name.MYALIAS Using LABEL ON Sometimes the table name.MYFILE with members MBR1 and MBR2. By using the LABEL ON statement. alias name.DEPARTMENT IS 'Department Structure Table' LABEL ON COLUMN CORPDATA. specify the ALIAS keyword on the drop statement: DROP ALIAS MYLIB. including the specific member name.MYFILE (MBR2) | | | | | When alias MYLIB. view name.' After these statements are run. column name. 6) Alias names can also be specified on DDL statements. SQL packages. Assume that alias MYLIB. view name. You can use this alias name in an SQL statement in the same way that you would use a table name. if there is a multiple member file MYLIB.MYMBR2_ALIAS is specified on the following insert statement. alias names are objects that exist until they are dropped.ADMRDEPT IS 'Reports to Dept. For example.MYALIAS If you really want to drop the alias name instead.MYFILE. the table named DEPARTMENT displays the text description as Department Structure Table and the column named ADMRDEPT displays the heading Reports to Dept.MYALIAS exists and is an alias for table MYLIB. DROP TABLE MYLIB.MYTABLE.MYTABLE. the values are inserted into member MBR2 in MYLIB. or SQL package name does not clearly define data that is shown on an interactive display of the table. Or you can use Operations Navigator. alias name. INSERT INTO MYLIB. you can avoid using file overrides by creating an alias. The LABEL ON statement looks like this: LABEL ON TABLE CORPDATA. ...+..6.3.........6.. *.+.4...EMPLOYEE....1. You can also include similar information about each column of a table or view...........2....+... user-defined type.2....* LABEL ON COLUMN CORPDATA. Each row in this table represents one employee of the company. *.... see the DB2 UDB for AS/400 SQL Reference book. package...4...3......EMPLOYEE IS 'Employee table..SALARY IS '' An example of a DBCS column heading with two levels specified..+... Your comment must not be more than 2000 bytes. *.+.....+.5.......5..+..' Chapter 3....6.. index......* LABEL ON COLUMN CORPDATA.+. who uses it. *.....EMPLOYEE...EMPLOYEE.+.+.SALARY IS 'Yearly Salary (in dollars)' This LABEL ON statement removes the column heading for SALARY..* LABEL ON COLUMN CORPDATA....+.+..+. or function.1. procedure.2. A comment is especially useful if your names do not clearly indicate the contents of the columns or objects.....+.......+.and column text cannot be more than 50 characters and the label for column headings cannot be more than 60 characters (blanks included)....1..4.6....+.EMPLOYEE.2.+.1.....1...+.. In that case..EMPNO IS 'Employee Number' This LABEL ON statement provides 3 levels of column headings for the SALARY column....EMPLOYEE..SALARY IS '<AABBCCDD> <EEFFGG>' This LABEL ON statement provides column text for the EDLEVEL column..+...5.......2...5. *.....+....* LABEL ON COLUMN CORPDATA.+. you can supply information about it for future referral....* LABEL ON COLUMN CORPDATA..3.. parameter........+.......+.+...4.EDLEVEL TEXT IS 'Number of years of formal education' For more information about the LABEL ON statement........ use a comment to describe the specific contents of the column or objects. view... Basic Concepts and Techniques 49 ...3.3..+..+....4.. An example of using COMMENT ON follows: COMMENT ON TABLE CORPDATA.. Using COMMENT ON | | | | | After you create an SQL object such as a table......+. The following are examples of LABEL ON statements: This LABEL ON statement provides column heading 1 and column heading 2...6.+.5.. and anything unusual or special about it..+.. such as the purpose of the object.+.. 'MGR'.25 17506.80 16808. The sort sequence is used for all character and UCS-2 graphic comparisons performed in SQL statements. There are sort sequence tables for both single byte and double byte character data. the CREATE INDEX statement has the sort sequence (in effect at the time the statement was run) applied to the character columns referred to in the index.55 0 650. Conversion between the two tables is performed when necessary to implement a query. your comments are stored in the REMARKS column of SYSTABLES.00 20659.Getting Comments | | | | | | | | | | After running a COMMENT ON statement for a table.75 18352.75 18006. (If the indicated row had already contained a comment.45 0 846.60 18001.) The following example gets the comments added by the COMMENT ON statement in the previous example: SELECT REMARKS FROM CORPDATA. Notice that the values in the JOB column are in mixed case. Sort Sequence Used with ORDER BY and Record Selection To see how to use a sort sequence.25 1152. and 'mgr'. The STAFF Table ID 10 20 30 40 50 60 70 80 90 100 NAME Sanders Pernal Merenghi OBrien Hanes Quigley Rothman James Koonitz Plotz DEPT 20 20 38 38 15 38 15 20 42 42 JOB Mgr Sales MGR Sales Mgr SALES Sales Clerk sales mgr YEARS 7 8 5 6 10 0 7 0 6 6 SALARY 18357.80 COMM 0 612. You can see the values 'Mgr'. see Chapter 1 in DB2 UDB for AS/400 SQL Reference book. Each single byte sort sequence table has an associated double byte sort sequence table. Table 2. For more information on sort sequences. the old comment is replaced by the new one. In addition.70 0 In the following examples. run the examples in this section against the STAFF table shown in Table 2.20 1386. 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 50 DB2 UDB for AS/400 SQL Programming V4R4 .30 16502.50 18171.83 13504.SYSTABLES WHERE NAME = 'EMPLOYEE' Using Sort Sequence in SQL A sort sequence defines how characters in a character set relate to each other when they are compared or ordered. and vice versa. Comments for the other objects are stored in the REMARKS column of the appropriate catalog table.00 128. 25 Table 4 shows how sorting is done for a unique-weight sort sequence.55 1152.80 17506.60 18352. ID 100 90 80 10 50 30 20 40 70 60 NAME Plotz Koonitz James Sanders Hanes Merenghi Pernal OBrien Rothman Quigley DEPT 42 42 20 20 15 38 20 38 15 38 JOB mgr sales Clerk Mgr Mgr MGR Sales Sales Sales SALES YEARS 6 6 0 7 10 5 8 6 7 0 SALARY 18352.45 846. all lowercase letters sort before the uppercase letters.83 16808.50 20659. and the values 'mgr'. ″SELECT * FROM STAFF ORDER BY JOB″ Using the *HEX Sort Sequence. the rows are sorted.75 13504.70 128. STRSQL.00 16502. After the sort sequence is applied to the values in the JOB column. Basic Concepts and Techniques 51 . After the sort sequence is applied to the values in the JOB column. 'Mgr'.Note: ENU is chosen as a language identifier by specifying either SRTSEQ(*LANGIDUNQ).80 18357.00 650. the rows are sorted. In this case.20 0 0 0 612.25 18006.00 16502. or SRTSEQ(*LANGIDSHR) and LANGID(ENU).00 650. 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. Table 3.83 16808.70 612.30 COMM 0 1386. or by using the SET OPTION statement.25 Table 5 on page 52 shows how sorting is done for a shared-weight sort sequence. For the Chapter 3.45 846. or RUNSQLSTM commands. Table 4.60 18357.75 18001.20 0 0 0 0 1386.75 18171. ″SELECT * FROM STAFF ORDER BY JOB″ Using the Unique-Weight Sort Sequence for the ENU Language Identifier. Notice that after the sort.80 18001. ID 80 100 10 50 30 90 20 40 70 60 NAME James Plotz Sanders Hanes Merenghi Koonitz Pernal OBrien Rothman Quigley DEPT 20 42 20 15 38 42 20 38 15 38 JOB Clerk mgr Mgr Mgr MGR sales Sales Sales Sales SALES YEARS 0 6 7 10 5 6 8 6 7 0 SALARY 13504. and 'MGR' are adjacent to each other.75 18171.50 20659. on the CRTSQLxxx.25 18006. lowercase letters are before the same uppercase letters.30 COMM 128.80 17506.55 1152. 25 18006. Notice that in Table 8 all the values 'mgr'.″ ID 30 NAME Merenghi DEPT 38 JOB MGR YEARS 5 SALARY 17506. Therefore. Table 8. 'Mgr' and 'MGR' are selected.30 16502. the lowercase and uppercase letters are treated as unique.75 20659. the rows that match the record selection criteria for the column 'JOB' are selected by treating uppercase letters the same as lowercase letters. In Table 7. ID 80 10 30 50 100 20 40 60 70 90 NAME James Sanders Merenghi Hanes Plotz Pernal OBrien Quigley Rothman Koonitz DEPT 20 20 38 15 42 20 38 38 15 42 JOB Clerk Mgr MGR Mgr mgr Sales Sales SALES Sales sales YEARS 0 7 5 10 6 8 6 0 7 6 SALARY 13504. ″SELECT * FROM STAFF WHERE JOB=’MGR’ Using the *HEX Sort Sequence.80 18171. 'mgr' and 'Mgr' are mixed together. Table 6. In Table 8. Table 5. ″SELECT * FROM STAFF ORDER BY JOB″ Using the Shared-Weight Sort Sequence for the ENU Language Identifier.20 0 0 0 0 612. notice that all the values 'MGR'.25 1152. ″SELECT * FROM STAFF WHERE JOB = ’MGR’ ″ Using the Shared-Weight Sort Sequence for the ENU Language Identifier.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 shows how record selection is done with a *HEX sort sequence. Only the uppercase 'MGR' is selected. Table 7. the lower case 'mgr' is not selected.50 COMM 0 52 DB2 UDB for AS/400 SQL Programming V4R4 .00 1386.55 650. ID 30 NAME Merenghi DEPT 38 JOB MGR YEARS 5 SALARY 17506.75 COMM 0 Table 7 shows how record selection is done with a unique-weight sort sequence. ID 10 NAME Sanders DEPT 20 JOB Mgr YEARS 7 SALARY 18357. the rows that match the record selection criteria for the column 'JOB' are selected exactly as specified in the select statement. each lowercase letter is treated the same as the corresponding uppercase letter. The lowercase 'mgr' is not treated the same as uppercase 'MGR'.80 18352.50 17506.83 18001.60 18357.00 16808. In Table 6.75 COMM 128.sort comparison. ″SELECT * FROM STAFF WHERE JOB = ’MGR’ ″ Using Unique-Weight Sort Sequence for the ENU Language Identifier. In Table 5.45 846.75 COMM 0 Table 8 shows how record selection is done with a shared-weight sort sequence. 75 COMM 0 Sort Sequence and the CREATE INDEX Statement Indexes are created using the sort sequence that was in effect when the CREATE INDEX statement was run.75 20659.80 COMM 0 0 0 Any queries run against view V1 are run against the result table shown in Table 9. View V1.50 17506. At that time. used in the following examples. that sort sequence is used for any character comparisons in the subselect of the CREATE VIEW. ″SELECT * FROM V1 WHERE JOB = ’MGR’″ Using the Unique-Weight Sort Sequence for Language Identifier ENU ID 30 NAME Merenghi DEPT 38 JOB MGR YEARS 5 SALARY 17506. ″SELECT * FROM STAFF WHERE JOB = ’MGR’ ″ Using the Shared-Weight Sort Sequence for the ENU Language Identifier. an intermediate result table is produced from the view subselect.80 18352. (continued) ID 30 50 100 NAME Merenghi Hanes Plotz DEPT 38 15 42 JOB MGR Mgr mgr YEARS 5 10 6 SALARY 17506.80 COMM 0 0 0 Sort Sequence and Views Views are created with the sort sequence that was in effect when the CREATE VIEW statement was run. The system gets the weighted value by converting the key value based on the sort sequence of the index. The sort sequence in effect when the query is being run is then applied to all the character and UCS-2 graphic comparisons (including those comparisons involving implicit conversions to character or UCS-2 graphic) specified in the query. An entry is added to the index every time an insert is made into the table over which the index is defined. The query shown below is run with a sort sequence of SRTSEQ(*LANGIDUNQ) and LANGID(ENU). The following SQL statements and tables show how views and sort sequences work. Chapter 3. ″SELECT * FROM V1″ ID 10 30 50 NAME Sanders Merenghi Hanes DEPT 20 38 15 JOB Mgr MGR Mgr YEARS 7 5 10 SALARY 18357. Table 9. The CREATE VIEW statement would be as follows: CREATE VIEW V1 AS SELECT * FROM STAFF WHERE JOB = 'MGR' AND ID < 100 Table 9 shows the result table from the view. Index entries contain the weighted value for character key and UCS-2 graphic key columns. Table 10.Table 8. Basic Concepts and Techniques 53 . When the view is referred to in a FROM clause. was created with a shared-weight sort sequence of SRTSEQ(*LANGIDSHR) and LANGID(ENU).75 20659. The sort sequence used at the time a check constraint is defined is the same sort sequence the system uses to validate adherence to the constraint at the time of an INSERT or UPDATE. If the table on which a unique constraint is added was defined with a sort sequence. For more information on sort sequence and constraints. the sort sequence between the parent and dependent table must match. Sort Sequence and Constraints Unique constraints are implemented with indexes. see the DB2 UDB for AS/400 Database Programming book. This improves the performance of the query.When selection is made using that sort sequence and that index. 54 DB2 UDB for AS/400 SQL Programming V4R4 . the character or UCS-2 graphic keys do not need to be converted prior to comparison. If defining a referential constraint. the index will be created with that same sort sequence. If host variables are specified (with the INTO clause on the FETCH © Copyright IBM Corp. WHERE CURRENT OF statement to delete the current row of a cursor. v A DELETE . When a FETCH is issued.. When you reach the end-of-data. For a serial cursor. SQL moves the current row’s contents into your program’s host variables. each row of the result table can be fetched only once per OPEN of the cursor. The type of cursor determines the positioning methods which can be used with the cursor. The cursor is moved through the result table based on the position option specified on the FETCH statement. although each must have a unique name. Serial cursor A serial cursor is one defined without the SCROLL keyword. A cursor provides a way to access a result table. You can never back up. That row is then the current row. SQL uses a cursor to work with the rows in the result table and to make them available to your program. You cannot access any rows in the result table after you reach the end-of-data. It is used within an SQL program to maintain a position in the result table. v A FETCH statement to retrieve rows from the cursor’s result table or to position the cursor on another row. it is positioned before the first row in the result table. the cursor is positioned to the row in the result table that is specified by the position option. WHERE CURRENT OF statement to update the current row of a cursor. Types of cursors SQL supports serial and scrollable cursors. v An UPDATE . When the cursor is opened. Statements related to using a cursor include the following: v A DECLARE CURSOR statement to define and name the cursor and specify the rows to be retrieved with the embedded select statement. When a FETCH is issued.. When the cursor is opened. The cursor must be opened before any rows can be retrieved. If host variables are specified (with the INTO clause on the FETCH statement). That row is then the current row. To use the cursor again. the resulting rows comprise the result table. you must first close the cursor and then re-issue the OPEN statement. Your program can have several cursors. 1997. v OPEN and CLOSE statements to open and close the cursor for use within the program. This sequence is repeated each time a FETCH statement is issued until the end-of-data (SQLCODE = 100) is reached. close the cursor.Chapter 4. the rows of the result table can be fetched many times. Scrollable cursor For a scrollable cursor. it is positioned before the first row in the result table. 1999 55 . Using a Cursor When SQL runs a select statement.. the cursor is moved to the next row in the result table.. updating the job for all members of department D11 and deleting the records of employees from the other departments. Positions the cursor before the first row. “Step 2: Open the Cursor” on page 59.EMPLOYEE FOR UPDATE OF JOB END-EXEC. SQL moves the current row’s contents into your program’s host variables. The following scroll options are used to position the cursor when issuing a FETCH statement. the cursor is positioned three rows after the current row.EMPLOYEE table. For the serial cursor example. A Serial Cursor Example Serial Cursor SQL Statement EXEC SQL DECLARE THISEMP CURSOR FOR SELECT EMPNO. 56 DB2 UDB for AS/400 SQL Programming V4R4 . Positions the cursor on the previous row. WORKDEPT. For example. Example of Using a Cursor Suppose your program examines data about people in department D11. EXEC SQL WHENEVER NOT FOUND GO TO CLOSE-THISEMP END-EXEC. The cursor does not need to be closed when an end-of-data or beginning-of-data condition occurs.statement). Table 11. Positions the cursor after the last row. This is the default if no position is specified. This sequence is repeated each time a FETCH statement is issued. Evaluates a host variable or integer n in relationship to the cursor’s current position. Host variables cannot be specified for the BEFORE and AFTER position options. JOB FROM CORPDATA. the program processes all of the rows from the table. Positions the cursor on the last row. These positions are relative to the current cursor location in the result table. Positions the cursor on the first row. “Step 3: Specify What to Do When End-of-Data Is Reached” on page 59. if n is -1. The following examples show the SQL statements you would include in a program to define and use a serial and a scrollable cursor. If n is +3. EXEC SQL OPEN THISEMP END-EXEC. LASTNAME. Described in Section “Step 1: Define the Cursor” on page 58. The position options enable the program to continue fetching rows from the table. These cursors can be used to obtain information about the department from the CORPDATA. Does not change the cursor position. the cursor is positioned on the previous row of the result table. NEXT PRIOR FIRST LAST BEFORE AFTER CURRENT RELATIVE n Positions the cursor on the next row. update the JOB value: EXEC SQL UPDATE CORPDATA. :NAME2. CLOSE-THISEMP. for other employees. SALARY FROM CORPDATA. “Step 3: Specify What to Do When End-of-Data Is Reached” on page 59. EXEC SQL DECLARE THISEMP DYNAMIC SCROLL CURSOR FOR SELECT EMPNO. Branch back to fetch and process the next row. ..EMPLOYEE WHERE CURRENT OF THISEMP END-EXEC. Chapter 4. . Described in Section “Step 4: Retrieve a Row Using a Cursor” on page 60.EMPLOYEE SET JOB = :NEW-CODE WHERE CURRENT OF THISEMP END-EXEC..Table 11. EXEC SQL WHENEVER NOT FOUND GO TO CLOSE-THISEMP END-EXEC. A Serial Cursor Example (continued) Serial Cursor SQL Statement EXEC SQL FETCH THISEMP INTO :EMP-NUM.. :DEPT. “Step 5a: Update the Current Row” on page 61. “Step 6: Close the Cursor” on page 62.. EXEC SQL CLOSE THISEMP END-EXEC. for all employees in department D11.. “Step 2: Open the Cursor” on page 59.EMPLOYEE WHERE WORKDEPT = ’D11’ END-EXEC. . then print the row. Table 12. For the scrollable cursor example. the program uses the RELATIVE position option to obtain a representative sample of salaries from department D11. Scrollable Cursor Example Scrollable Cursor SQL Statement Described in Section “Step 1: Define the Cursor” on page 58. :JOB-CODE END-EXEC. LASTNAME. “Step 5b: Delete the Current Row” on page 61.. delete the row: EXEC SQL DELETE FROM CORPDATA. Using a Cursor 57 . EXEC SQL OPEN THISEMP END-EXEC. FOR UPDATE OF column-2 .. FROM table-name .. 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). EXEC SQL CLOSE THISEMP END-EXEC. If you do not 58 DB2 UDB for AS/400 SQL Programming V4R4 . If you do not specify the names of columns.. For a scrollable cursor.add the current salary to program summation salary .Table 12........ However.. and you specify either the ORDER BY clause or FOR READ ONLY clause. you can code several other types of clauses in a select-statement within a DECLARE CURSOR statement for a serial and a scrollable cursor. For a serial cursor. Step 1: Define the Cursor To define a result table to be accessed with a cursor.calculate the average salary CLOSE-THISEMP. Described in Section “Step 4: Retrieve a Row Using a Cursor” on page 60. . :JOB-CODE END-EXEC... :NAME2.branch back to fetch and process the next row.. use the DECLARE CURSOR statement... the statement looks like this (the FOR UPDATE OF clause is optional): EXEC SQL DECLARE cursor-name CURSOR FOR SELECT column-1. column-2 . END-EXEC.. WHERE column-1 = expression . The select-statements shown here are rather simple. . The DECLARE CURSOR statement names a cursor and specifies a select-statement. END-EXEC. column-2 .. It names each column you intend to update... a negative SQLCODE is returned if an update is attempted.. FROM table-name . conceptually. make up the result table. Scrollable Cursor Example (continued) Scrollable Cursor SQL Statement ...initialize program summation salary variable EXEC SQL FETCH RELATIVE 3 FROM THISEMP INTO :EMP-NUM.. The select-statement defines a set of rows that. . the statement looks like this (the WHERE clause is optional): EXEC SQL DECLARE cursor-name DYNAMIC SCROLL CURSOR FOR SELECT column-1. include the FOR UPDATE OF clause. “Step 6: Close the Cursor” on page 62. . or many rows. test the SQLCODE field for a value of 100 or test the SQLSTATE field for a value of '02000' (that is. 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. Using a Cursor 59 . Chapter 4. the DECLARE CURSOR statement should include FOR UPDATE OF JOB . the FOR READ ONLY clause. called a result table 3.specify the FOR UPDATE OF clause. using the current value of any host variables specified in the select-statement. When your program issues the OPEN statement. Step 3: Specify What to Do When End-of-Data Is Reached To find out when the end of the result table is reached. v The select-list includes a DataLink column and a FOR UPDATE OF clause is not specified. SQL processes the select-statement within the DECLARE CURSOR statement to identify a set of rows. The OPEN statement looks like this: EXEC SQL OPEN cursor-name END-EXEC. v The first FROM clause identifies a read-only view. depending on the extent to which the search condition is satisfied. or the ORDER BY clause. v The outer subselect contains a GROUP BY clause. you do not need to name the column in the SELECT statement.EMPLOYEE table. issue the OPEN statement. v The first SELECT clause contains a column function. v The select-statement contains an ORDER BY clause. A result table can contain zero. 3.. Step 2: Open the Cursor To begin processing the rows of the result table. If you want to update the JOB column (one of the columns in each row of the CORPDATA. v The first SELECT clause specifies the keyword DISTINCT. and the FOR UPDATE OF clause and DYNAMIC SCROLL are not specified. In this case. v The select-statement includes a FOR READ ONLY clause. You can update a column of the identified table even though it is not part of the result table. assume that each row of the result table includes the EMPNO.. | | v The SCROLL keyword is specified without DYNAMIC. you can use UPDATE . and the result table is not read-only. WHERE CURRENT OF to update the row. v The select-statement contains a UNION or UNION ALL operator. and WORKDEPT columns from the CORPDATA. LASTNAME.. even though JOB is omitted from the SELECT statement. you can update any of the columns of the specified table. For example. When the cursor retrieves a row (using FETCH) that contains a column value you want to update. one.EMPLOYEE table). 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 outer subselect contains a HAVING clause. :host variable-2] . This sequence is repeated each time the FETCH statement is issued. The scrollable cursor FETCH statement looks like this: 60 DB2 UDB for AS/400 SQL Programming V4R4 . although the DELETE statement does. and should be prepared to handle this situation when it occurs. The SELECT statement within the DECLARE CURSOR statement identifies rows that contain the column values your program wants.. This condition occurs when the FETCH statement has retrieved the last row in the result table and your program issues a subsequent FETCH. The WHENEVER statement looks like this: EXEC SQL WHENEVER NOT FOUND GO TO symbolic-address END-EXEC. The UPDATE statement does not change the position of the current row within the result table.. where a CLOSE statement is issued. An alternative to this technique is to code the WHENEVER statement. For example: . every subsequent FETCH statement returns the end-of-data condition. use the FETCH statement. When your program issues the FETCH statement. the result table can still process more data. SQL moves the current row’s contents into your program’s host variables. SQL uses the current cursor position as a starting point to locate the requested row in the result table. SQL does not retrieve any data for your application program until the FETCH statement is issued.end-of-data). IF SQLCODE =100 GO TO DATA-NOT-FOUND. You do not need to CLOSE the cursor when the end-of-data is reached. END-EXEC. You can position the cursor anywhere in the result table using a combination of the position options. However. When you are using a scrollable cursor and the end-of-data is reached. This changes that row to the current row. the cursor points to the current row) until the next FETCH statement for the cursor is issued. Step 4: Retrieve a Row Using a Cursor To move the contents of a selected row into your program’s host variables. The CLOSE statement is the only operation that can be performed on the cursor. You cannot position the cursor on rows that are already processed. The serial cursor FETCH statement looks like this: EXEC SQL FETCH cursor-name INTO :host variable-1[. If an INTO clause was specified.. Using WHENEVER NOT FOUND can result in a branch to another part of your program. When you are using a serial cursor and the end-of-data is reached. Your program should anticipate an end-of-data condition whenever a cursor is used to fetch a row.. or IF SQLSTATE ='02000' GO TO DATA-NOT-FOUND. SQL maintains the position of the current row (that is. . Chapter 4. END-EXEC. Step 5a: Update the Current Row When your program has positioned the cursor on a row. the WHERE CURRENT OF clause specifies a cursor that points to the row you want to delete. if an ORDER BY clause was also specified After you update a row.. WHERE CURRENT OF statements when you want to obtain a copy of the row. the DELETE statement: v Deletes only one row—the current row v Uses the WHERE CURRENT OF clause to identify a cursor that points to the row to be deleted After you delete a row. Step 5b: Delete the Current Row When your program has retrieved the current row.. To do this. “The DELETE Statement” on page 34 shows you how to use the DELETE statement to delete all rows that meet a specific search condition. the UPDATE statement: v Updates only one row—the current row v Identifies a cursor that points to the row to be updated v Requires that the columns updated be named previously in the FOR UPDATE OF clause of the DECLARE CURSOR statement.. When used with a cursor. the current row of the cursor does not change) until you issue a FETCH statement for the next row.EXEC SQL FETCH RELATIVE integer FROM cursor-name INTO :host variable-1[. The DELETE .. you cannot update or delete another row using that cursor until you issue a FETCH statement to position the cursor.. WHERE CURRENT OF statement looks like this: EXEC SQL UPDATE table-name SET column-1 = value [. you can delete the row by using the DELETE statement. Using a Cursor 61 . The WHERE CURRENT OF clause specifies a cursor that points to the row you want to update. WHERE CURRENT OF cursor-name END-EXEC. you issue a DELETE statement designed for use with a cursor. When used with a cursor. you can update its data by using the UPDATE statement with the WHERE CURRENT OF clause. WHERE CURRENT OF statement looks like this: EXEC SQL DELETE FROM table-name WHERE CURRENT OF cursor-name END-EXEC. then delete it. :host variable-2] . column-2 = value] ... examine it. The UPDATE .. You can also use the FETCH and DELETE .. the cursor’s position remains on that row (that is. v The connection to the application server was released and a successful COMMIT occurred.Step 6: Close the Cursor If you processed the rows of a result table for a serial cursor. v The first SQL program in the call stack ends and neither CLOSQLCSR(*ENDJOB) or CLOSQLCSR(*ENDACTGRP) was specified when the program was precompiled. Both methods can be coded in all of the languages supported by the SQL precompilers. 62 DB2 UDB for AS/400 SQL Programming V4R4 . Only the FETCH statement changes to specify the number of rows to retrieve and the storage where the rows are placed. The program controls the blocking of rows by the number of rows requested on the FETCH statement (OVRDBF has no effect). Once the data is retrieved. with the exception of the host structure array in REXX. you should explicitly close any open cursors as soon as they are no longer needed. v An *RUW CONNECT occurred. Refer to Chapter 12. Coding SQL Statements in C and C++ Applications. EXEC SQL CLOSE cursor-name END-EXEC. the cursor is positioned on the last row retrieved. The indicator array should contain one indicator for each host variable that is null capable. Both forms of the multiple-row FETCH statement allow the application to code a separate indicator array. The maximum number of rows that can be requested on a single fetch call is 32767. through Chapter 17. If you processed the rows of a result table and you do not want to use the cursor again. Using the Multiple-Row FETCH Statement The multiple-row FETCH statement can be used to retrieve multiple rows from a table or view with a single FETCH. Coding SQL Statements in REXX Applications. open. issue a CLOSE statement to close the cursor prior to re-opening it. for more information on the programming languages. v The activation group ends and CLOSQLCSR(*ENDACTGRP) was specified on the precompile. and close a cursor for a multiple-row FETCH remain the same. and you want to use the cursor again. v A ROLLBACK without HOLD statement is issued. Because an open cursor still holds locks on referred-to-tables or views. 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 The job ends. you can let the system close the cursor. v The connection to the application server is ended using the DISCONNECT statement. The multiple-row FETCH statement can be used with both serial and scrollable cursors. The operations used to define. There are two ways to define the storage where fetched rows are placed: a host structure array or a row storage area with an associated descriptor. Consider the following COBOL example: EXEC SQL INCLUDE SQLCA END-EXEC. Multiple-Row FETCH Using a Host Structure Array To use the multiple-row FETCH with the host structure array.. JOB FROM CORPDATA. The host structure array consists of an array of structures. v SQLERRD4 contains the length of each row retrieved. Cursors which do have immediate sensitivity to updates should continue fetching until an SQLCODE +100 is received to detect an end-of-data condition.. ... . then an error or end-of-data condition occurred. 01 TABLE-2.After each multiple-row FETCH. Each structure corresponds to one row of the result table. 02 DEPT OCCURS 10 TIMES.EMPLOYEE WHERE WORKDEPT = "D11" END-EXEC. 05 WORKDEPT PIC X(3). The first structure in the array corresponds to the first row. . WORKDEPT. EXEC SQL OPEN D11 Chapter 4. To maximize performance. 02 IND-ARRAY OCCURS 10 TIMES. EXEC SQL DECLARE D11 CURSOR FOR SELECT EMPNO. the application must define a host structure array that can be used by SQL. 05 EMPNO PIC X(6).. v SQLERRD5 contains an indication that the last row in the table was fetched. information is returned to the program through the SQLCA. Using a Cursor 63 . If SQLERRD3 is less than the number of rows requested. Each language has its own conventions and rules for defining a host structure array. 49 LASTNAME-TEXT PIC X(15). the SQLERRD provides the following information: v SQLERRD3 contains the number of rows retrieved on the multiple-row FETCH statement. 05 LASTNAME.. 05 INDS PIC S9(4) BINARY OCCURS 4 TIMES. 01 TABLE-1. LASTNAME. SQL determines the attributes of elementary items in the host structure array based on the declaration of the host structure array. 05 JOB PIC X(8). It can be used to detect the end-of-data condition in the table being fetched when the cursor does not have immediate sensitivity to updates. the attributes of the items that make up the host structure array should match the attributes of the columns being retrieved. In addition to the SQLCODE and SQLSTATE fields. Host structure arrays can be defined by using variable declarations or by using compiler directives to retrieve External File Descriptions (such as the COBOL COPY directive). and so on. the second structure in the array corresponds to the second row. 49 LASTNAME-LEN PIC S9(4) BINARY. Multiple-Row FETCH Using a Row Storage Area The application must define a row storage area and an associated description area before the application can use a multiple-row FETCH with a row storage area. The indicator array has an entry for each column in the result table. EXEC SQL CLOSE D11 END-EXEC. 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 of the rows in the result table. the length of each row v SQLERRD5 contains +100. Following the FETCH. . EXEC SQL WHENEVER NOT FOUND GO TO ALL-DONE END-EXEC. PERFORM FETCH-PARA UNTIL SQLCODE NOT EQUAL TO ZERO. the cursor position remains on the last row retrieved. FETCH-PARA.END-EXEC. IND_ARRAY. 64 DB2 UDB for AS/400 SQL Programming V4R4 ... . contains zeros for every column in every row because no NULL values were returned. EXEC SQL FETCH D11 FOR 10 ROWS INTO :DEPT :IND-ARRAY END-EXEC. The row storage area contains the results of the multiple-row FETCH. The indicator array. When the multiple-row FETCH statement has successfully completed. the number of rows fetched v SQLERRD4 contains 34. The result table contains eight rows. Both arrays have a dimension of ten. In this example. The DECLARE CURSOR and OPEN statements do not have any special syntax when they are used with a multiple-row FETCH statement. The host structure array DEPT and the associated indicator array IND-ARRAY are defined in the application. the host structure array contains the data for all eight rows. a cursor was defined for the CORPDATA. The SQLCA that is returned to the application contains the following information: v SQLCODE contains 0 v SQLSTATE contains '00000' v SQLERRD3 contains 8.. A row storage area can be a character variable with enough bytes to hold all of the rows requested on the multiple-row FETCH. The row storage area is a host variable defined in the application program. ALL-DONE.. indicating the last row in the result table is in the block See Appendix B of the DB2 UDB for AS/400 SQL Reference book for a description of the SQLCA. The attributes of type and length of the DEPT host structure array elementary items match the columns that are being retrieved.EMPLOYEE table to select all rows where the WORKDEPT column equals 'D11'. See Appendix C of the DB2 UDB for AS/400 SQL Reference book for a description of the SQLDA. To maximize performance.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. Using a Cursor 65 . The information provided in the descriptor determines the data mapping from the database to the row storage area. the attribute information in the descriptor should match the attributes of the columns retrieved. Consider the following PL/I example: Chapter 4. */ SQLLEN(3) = 3... LASTNAME.. DEC J BIN(31) FIXED....*/ /* NOT NULLABLE */ SQLLEN(4) = 8..EMPLOYEE WHERE WORKDEPT = 'D11'..7. DCL DEPTPTR PTR. JOB FROM CORPDATA...*...... .* EXEC SQL INCLUDE SQLCA. /*REQUESTS 10 ROWS ON THE FETCH */ Figure 2.. 3 WORKDEPT CHAR(3)... DCL 1 DEPT(10) BASED(DEPTPTR). ...+.. 3 JOB CHAR(8)...+. SQLTYPE(4) = 452.. SQLDABC = 366.6..*/ /* NOT NULLABLE */ SQLLEN(1) = 6.1. SQLTYPE(1) = 452. /* FIXED LENGTH CHARACTER ....+...+. DCL I BIN(31) FIXED..+. DCL ROWAREA CHAR(2000).3. Example of Multiple-Row FETCH Using a Row Storage Area (Part 1 of 2) 66 DB2 UDB for AS/400 SQL Programming V4R4 . ALLOCATE SQLDA SET(SQLDAPTR).. EXEC SQL OPEN D11...+. .. /* FIXED LENGTH CHARACTER . EXEC SQL DECLARE D11 CURSOR FOR SELECT EMPNO... /* FIXED LENGTH CHARACTER .4. /*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..2... EXEC SQL INCLUDE SQLDA..... SQLTYPE(3) = 452. WORKDEPT...5.. SQLTYPE(2) = 456... .. /* SET UP THE DESCRIPTOR FOR THE MULTIPLE-ROW FETCH */ /* 4 COLUMNS ARE BEING FETCHED */ SQLD = 4. 3 EMPNO CHAR(6). /*VARYING LENGTH CHARACTER */ /* NOT NULLABLE */ SQLLEN(2) = 15. SQLN = 4. 3 LASTNAME CHAR(15) VARYING.+... EXEC SQL WHENEVER NOT FOUND GOTO FINISHED. the ROWAREA contains eight rows. 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. EXEC SQL FETCH D11 FOR :J ROWS USING DESCRIPTOR :SQLDA INTO :ROWAREA. indicating the last row in the result table was fetched In this example. The DECLARE CURSOR and OPEN statements do not have special syntax when they are used with a multiple-row FETCH statement. /*PROCESS EACH ROW RETURNED IN THE ROW STORAGE /*AREA BASED ON THE COUNT OF RECORDS RETURNED /*IN SQLERRD3. The data from the result table is placed in the host variable. After the FETCH statement is completed. The sample EMPLOYEE table in Appendix A. a pointer variable is assigned to the address of ROWAREA. the number of rows returned v SQLERRD4 contains 34. Using a Cursor 67 . the application has taken advantage of the fact that SQLERRD5 contains an indication of the end of the file being reached. END. ROWAREA. DO I = 1 TO SQLERRD(3). In this case. a cursor has been defined for the CORPDATA. EXEC SQL WHENEVER SQLERROR GOTO FINISHED. /* ADDRESS THE ROWS RETURNED DEPTPTR = ADDR(ROWAREA). the application does not need to call SQL again to attempt to retrieve more rows. is defined as a character array. /* PROCESS END OF FILE */ END. The row area. Example of Multiple-Row FETCH Using a Row Storage Area (Part 2 of 2) In this example. FINISHED: */ */ */ */ Figure 2. The SQLCA that is returned to the application contains the following: v SQLCODE contains 0 v SQLSTATE contains '00000' v SQLERRD3 contains 8. for the length of the row fetched v SQLERRD5 contains +100. IF EMPNO(I) = '000170' THEN DO. no indicator area is provided. In this example. If the Chapter 4. Following the FETCH. the cursor position remains on the eighth record in the block. : END.EMPLOYEE table to select all rows where the WORKDEPT column equal 'D11'. As a result. IF SQLERRD(5) = 100 THEN DO. 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. DB2 UDB for AS/400 Sample Tables shows the result table contains eight rows. All record locks are still released. You can open the cursor again. On a COMMIT statement. you should call SQL in case any records were added. the cursor position is maintained. They are automatically closed on a ROLLBACK (the WITH HOLD clause specified on the DECLARE CURSOR statement is ignored). the cursor position is restored to just after the last row retrieved from the previous unit of work. Dynamic SQL Applications for information on the use of the ALWBLK parameter and other performance related options on the CRTSQLxxx commands. all locks are released and all cursors are closed. Note: Specification of the ALWBLK(*ALLREAD) parameter of the CRTSQLxxx commands can change the restoration of the cursor position for read-only cursors. If you want to continue processing from the current cursor position after a COMMIT or ROLLBACK. 68 DB2 UDB for AS/400 SQL Programming V4R4 .cursor has immediate sensitivity to inserts. Unit of Work and Open Cursors When your program completes a unit of work. After issuing a COMMIT or ROLLBACK statement without HOLD. Cursors have immediate sensitivity when the commitment control level is something other than *RR. any open cursors are left open and keep their cursor position so processing can resume. On a ROLLBACK statement. it should commit or rollback the changes you made. Cursors that are declared with the WITH HOLD clause are not automatically closed on COMMIT. you must specify COMMIT HOLD or ROLLBACK HOLD. When HOLD is specified. all open cursors are automatically closed by SQL. See Chapter 10. but you will begin processing at the first row of the result table. Unless you specified HOLD on the COMMIT or ROLLBACK statement. and techniques used to retrieve data. The second method can be used with all languages except REXX. STARTDATE. suppose you want a table that shows each employee’s time commitments to projects. and then use the following INSERT statement to fill the table: INSERT INTO CORPDATA. With the exception of FOR READ ONLY. The table you select the rows from can be the same table you are inserting into.EMP_ACT The select-statement embedded in the INSERT statement is no different from the select-statement you use to retrieve data. One use for this kind of INSERT statement is to move data into a table you created for summary data. EMSTDATE. or more rows selected from the table or view you specify into another table. The first section Inserting Rows into a Table Using a Select-Statement discusses how to insert more than one row at a time using a select statement.Chapter 5. SQL inserts all the rows that meet the search conditions into the table you specify. ENDDATE) SELECT EMPNO. Advanced Coding Techniques This chapter covers the more advanced SQL coding techniques. EMENDATE FROM CORPDATA. For example. you can use all the keywords. © Copyright IBM Corp. 1997. PROJNUMBER. If they are the same table. or the OPTIMIZE clause. The topics included in this chapter are: v inserting rows v updating rows v preventing duplicate rows v searching v joining v v v v v using using using using using UNION subqueries views indexes the system catalog Advanced Insert Techniques The next two sections cover two advanced techniques on how to insert rows into a table. and TTIME. ENDDATE. SQL will create a temporary result table containing the selected rows and then insert from the temporary table into the target table. Inserting rows from one table into another table does not affect any existing rows in either the source table or the target table. You could create a table called EMPTIME with the columns EMPNUMBER. STARTDATE. PROJNO.EMPTIME (EMPNUMBER. Inserting Rows into a Table Using a Select-Statement You can use a select-statement within an INSERT statement to insert zero. column functions. PROJNUMBER. one. 1999 69 . The second section Using the Blocked Insert Statement discusses how to insert multiple rows that are in a host structure array. FOR UPDATE OF. v You can join two or more tables with a select-statement in an INSERT statement. LASTNAME. because the rows exist as physically stored rows in a table. COMMIT (*ALL). The following example lists each column with its corresponding value: 70 DB2 UDB for AS/400 SQL Programming V4R4 . The blocked INSERT statement is supported in all of the languages except REXX. or COMMIT(*RR). v The data in the columns you are selecting must be compatible with the columns you are inserting into when using the INSERT with select-statement. SQL stops the operation. DELETE. If you specify COMMIT(*NONE). ISTRUCT is a host structure array that is declared in the program. any rows inserted prior to the error remain in the table. an SQLCODE of 100 is returned to alert you that no rows were inserted. v In the event the select-statement embedded in the INSERT returns no rows. If you successfully insert rows. MIDINIT. If indicator variables are used with a blocked INSERT. For example. For information on host structure arrays for a particular language. refer to the chapter on that language. Advanced Update Techniques The SET clause of an UPDATE statement can be used in many ways to determine the actual values to be set in each row being updated. the SQLERRD(3) field of the SQLCA has an integer representing the number of rows SQL actually inserted. the table can be operated on with UPDATE. COMMIT(*CS). The five elements correspond to EMPNO.Notes on Multiple-Row Insertion You should consider the following when inserting multiple rows into a table: v The number of columns implicitly or explicitly listed in the INSERT statement must equal the number of columns listed in the select-statement. If you specify COMMIT (*CHG).MIDINIT.EMPLOYEE (EMPNO. and INSERT statements. DSTRUCT has a dimension of at least ten to accommodate inserting ten rows. Using the Blocked Insert Statement A blocked INSERT can be used to insert multiple rows into a table with a single statement.EMPLOYEE table: INSERT INTO CORPDATA. v If SQL finds an error while running the INSERT statement. and WORKDEPT. Loaded in this manner. to add ten employees to the CORPDATA. 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.FIRSTNME.LASTNAME. FIRSTNME. nothing is inserted into the table and a negative SQLCODE is returned. The data inserted into the table must be in a host structure array.WORKDEPT) 10 ROWS VALUES(:DSTRUCT:ISTRUCT) DSTRUCT is a host structure array with five elements that is declared in the program. they must also be in a host structure array. ISTRUCT has a dimension of at least ten small integer fields for the indicators. is a unique key column. In the following example.RESPEMP = EMPLOYEE. You can specify that you do not want any duplicates by using the DISTINCT keyword. The scalar-subselect allows you to update one or more columns by setting them to one or more values selected from another table. Now the project table needs to be updated to reflect the new department number of this employee (employee number is ’000030’). PHONENO = '7213'. several rows might qualify to be in the result table.CLASS_CODE = MYCOPY. The changes are made to the work copy and merged into the master table every night. an employee moves to a different department but continues working on the same projects. the duplicate row is ignored (it is not put Chapter 5. CLASS_CODE. Some of the rows in the result table might be duplicates.EMPNO) WHERE RESPEMP='000030' This same technique could be used to update a list of columns with multiple values returned from a single select.CLASS_CODE) This update will update all of the rows in CL_SCHED with the values from MYCOPY. 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. '7213'. PHONENO. UPDATE CL_SCHED SET ROW = (SELECT * FROM MYCOPY WHERE CL_SCHED. The two tables have exactly the same columns and one column. It is also possible to update an entire row in one table with values from a row in another table. Preventing Duplicate Rows When SQL evaluates a select-statement. The employee table has already been updated to contain the new department number. Advanced Coding Techniques 71 .UPDATE EMPLOYEE SET WORKDEPT = 'D11'. If a selected row duplicates another row in the result table. DISTINCT means you want to select only the unique rows. 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. 'DESIGNER') WHERE EMPNO = '000270' Another way to select a value (or multiple values) for an update is to use a scalar-subselect. JOB) = ('D11'. followed by the list of column names: SELECT DISTINCT JOB. UPDATE PROJECT SET DEPTNO = (SELECT WORKDEPT FROM EMPLOYEE WHERE PROJECT. depending on the number of rows that satisfy the select-statement’s search condition... SEX . For example.into the result table). The following example shows how to do this: DECLARE XMP2 CURSOR FOR SELECT DISTINCT JOB FROM CORPDATA. FETCH XMP2 INTO :JOB The result is two rows (in this example. 'Mgr'. the sort sequence is applied to the operands before evaluation of the predicates for BETWEEN. AND . v BETWEEN . Null values are treated as duplicate rows for DISTINCT. fewer values are returned. Performing Complex Search Conditions The following section explains more advanced things you can do with search conditions. Keywords for Use in Search Conditions A search condition can contain any of the keywords BETWEEN. However. because SQL retrieves the JOB column’s value for each row that satisfies the search condition. only one of these values would be returned. IS NULL. you could use this: . Remember to precede each host variable with a colon. and LIKE. EXISTS. and LIKE clauses.. you could just as easily code host variables instead.. Note: Constants are shown in the following examples to keep the examples simple. If you include DISTINCT in a SELECT clause and you also include a shared-weight sort sequence. See “Using Sort Sequence in SQL” on page 50 for more information on the using sort sequence with selection... For example. Because it is probable that several people in a department have the same job code. suppose you want a list of employee job codes. For character and UCS-2 graphic column predicates... If 'MGR'. you might find duplicate rows in your result. is used to specify a search condition that is satisfied by any value that falls on or between two other values.. IN. you can use DISTINCT to ensure that the result table has only unique values. to find all employees who were hired in 1987. You do not need to know which employee has what job code. WHERE HIREDATE BETWEEN '1987-01-01' AND '1987-12-31' 72 DB2 UDB for AS/400 SQL Programming V4R4 . The sort sequence causes values that contain the same characters to be weighted the same. IN. fetch 1 JOB Designer RV2W557-2 If you do not include DISTINCT in a SELECT clause. and 'mgr' were all in the same table. JOB-DEPT is set to D11).EMPLOYEE WHERE WORKDEPT = :JOB-DEPT .. but explicit. then SQL allows 0 or more character(s) to precede the matching value in the column. Use the underline character or percent sign either when you do not know or do not care about all the characters of the column’s value. v When fixed-length host variables are used in place of string constants in a search pattern. SQL searches for a character string similar to the one you specify. Note: If you are operating on MIXED data... See the DB2 UDB for AS/400 SQL Reference book for more information on the LIKE predicate and MIXED data. you could specify: . to find out which employees live in Minneapolis.. a percent sign refers to any number of SBCS or DBCS characters. you should ensure the value specified in the host variable Chapter 5. to find the names of all employees in departments A00. SQL returns any row with the string MINNEAPOLIS in the ADDRESS column. In another example. If the percent sign starts the search string. For example. and E21. you could specify: .. you should be sure that MINNEAPOLIS was not part of a street address or part of another city name. the search string must begin in the first position of the column. The combination ’@%’ is taken as the actual percent character. This allows you to: – Assign previously used string constants to host variables without any change. that is. No such restriction applies to the percent sign. the following distinction applies: an SBCS underline character refers to one SBCS character.. no matter where the string occurs. to list the towns whose names begin with 'SAN'. search condition that produces the same result is: . For example. use the ESCAPE clause to specify an escape character. The degree of similarity is determined by two special characters used in the string that you include in the search condition: _ % An underline character stands for any single character. WHERE BUSINESS_NAME LIKE '%@%%' ESCAPE '@' The first and last percent characters are interpreted as usual. WHERE WORKDEPT IN ('A00'. – Obtain the same selection criteria and results as if a string constant was used. 'E21') v LIKE says you are interested in rows in which a column value is similar to the value you supply... to see all businesses that have a percent in their name. WHERE TOWN LIKE 'SAN%' If you want to search for a character string that contains either the underscore or percent character... C01. Special Considerations for LIKE v When host variables are used in place of string constants in a search pattern. When you use LIKE. 'C01'.. you could specify: . For example. you could specify: . you should consider using varying length host variables. A more complex. Otherwise. WHERE ADDRESS LIKE '%MINNEAPOLIS%' In this case. Advanced Coding Techniques 73 .The BETWEEN keyword is inclusive. A percent sign stands for an unknown string of 0 or more characters. WHERE HIREDATE >= '1987-01-01' AND HIREDATE <= '1987-12-31' v IN says you are interested in rows in which the value of the specified expression is among the values you listed. WHERE WORKDEPT = 'C01' OR WORKDEPT = 'D11' v NOT says that. WHERE WORKDEPT = 'E11' AND NOT JOB = 'ANALYST' When SQL evaluates search conditions that contain these connectors. This is because the last six characters in the host variable were not assigned a specific value so blanks were used. All characters in a host variable that are not assigned a value are initialized with a blank. for a row to qualify. to find all employees in department E11 except those with a job code equal to analyst.matches the pattern previously used by the string constants.. these are some of the values that could be returned: 'ABCD ' 'ABCDE' 'ABCxxx' 'ABC ' For example. WHERE WORKDEPT = 'D21' AND HIREDATE > '1987-12-31' v OR says that. and then the OR clauses. 1987. If you wanted to do a search on a fixed-length host variable where the last 7 characters could be anything. A WHERE clause can have as many predicates as you want. For example... it does so in a specific order. For example.. you could specify 4: . if you did a search using the search pattern ’ABC%’ contained in a host variable with a fixed length of 10. and IS NOT NULL. For example. you can use the NOT keyword to specify that the desired search condition is the negated value of the specified search condition. 4. you would search for ’ABC%%%%%%%’. v AND says that. you could specify: . for a row to qualify. the row can satisfy the condition set by either or both predicates of the search condition. SQL first evaluates the NOT clauses. You can join any two predicates with the connectors AND and OR. to find out which employees in department D21 were hired after December 31. to find out which employees are in either department C01 or D11. 74 DB2 UDB for AS/400 SQL Programming V4R4 . a row must not meet the criteria set by the search condition or predicate that follows the NOT. LIKE. next evaluates the AND clauses. if you did a search using the string pattern ’ABC%’. 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. These are some values that could be returned: 'ABCDEFGHIJ' 'ABCXXXXXXX' 'ABCDE' 'ABCDD' Multiple Search Conditions within a WHERE Clause You saw how to qualify a request using one search condition. the row must satisfy both predicates of the search condition. You could also use IN to specify this request: WHERE WORKDEPT IN ('C01'. to qualify. IN.. You can qualify your request further by coding a search condition that includes several predicates.. 'D11'). The search condition you specify can contain any of the comparison operators or the keywords BETWEEN. For example. IS NULL. In addition. you would specify: . Four different types of joins are supported by DB2 UDB for AS/400: inner join. exception join. v An “Exception Join” on page 77 returns only the rows from the left table that do not have a match in the right table.. WHERE EDLEVEL > 12 AND (WORKDEPT = 'E11' OR WORKDEPT = 'E21') The parentheses determine the meaning of the search condition.. SQL examines both tables specified for the join to retrieve data from all the rows that meet the search condition for the join. and using the WHERE clause. The search conditions enclosed in parentheses are evaluated first. regardless of the EDLEVEL value Joining Data from More Than One Table Sometimes the information you want to see is not in a single table. 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. You can retrieve and join column values from two or more tables into a single row. Columns in the result table that come from the right table have the null value.. Inner Join With an inner join. v A “Left Outer Join” on page 76 returns values for all of the rows from the first table (the table on the left) and the values from the second table for the rows that match. to select all employees in departments E11 and E21 who have education levels greater than 12. For example. The selected rows are rows that have: WORKDEPT = E11 and EDLEVEL > 12. left outer join.. Advanced Coding Techniques 75 . WHERE EDLEVEL > 12 AND WORKDEPT = 'E11' OR WORKDEPT = 'E21' Your result is different.You can change the order of evaluation by using parentheses. In this example. v An “Inner Join” returns only the rows from each table that have matching values in the join columns. and EDLEVEL value greater than 12 If you did not use parentheses: . Any rows that do not have a match between the tables will not appear in the result table. To form a row of the result table. There are two ways of specifying an inner join: using the JOIN syntax. v A “Cross Join” on page 78 returns a row in the result table for each combination of rows from the tables being joined (a Cartesian Product). Any rows that do not have a match in the second table will return the null value for all columns from the second table. or WORKDEPT = E21. you could specify: . Chapter 5. and cross join. you might want to retrieve some column values from one table and some column values from another table. you want all rows that have a: WORKDEPT value of E11 or E21. PROJNO FROM CORPDATA. Left Outer Join A left outer join will return all the rows that an inner join returns plus one row for each of the other rows in the first table that did not have a match in the second table. To find this information. SELECT EMPNO. both of the tables you are joining are listed in the FROM clause. you need to join the two tables.EMPLOYEE.EMPLOYEE INNER JOIN CORPDATA. This query returns the following output: EMPNO 000020 000060 000100 000250 LASTNAME THOMPSON STERN SPENSER SMITH PROJNO PL2100 MA2110 OP2010 AD3112 Inner Join Using the WHERE Clause Using the WHERE clause to perform this same join is written with both the join condition and the additional selection condition in the WHERE clause. it does not need to be the equal operator.PROJECT ON EMPNO = RESPEMP WHERE LASTNAME > 'S' In this example. In other words.Suppose you want to retrieve the employee numbers. separated by commas. The condition can be any comparison operator. CORPDATA. this additional condition is provided in the WHERE clause. names. The join condition is specified after the ON keyword and determines how the two tables are to be compared to each other to produce the join result.EMPLOYEE table and the PROJNO column from the CORPDATA. Suppose you want to find all employees and the projects they are currently responsible for. Multiple join conditions can be specified in the ON clause separated by the AND keyword. the join is done on the two tables using the EMPNO and RESPEMP columns from the tables. Inner Join Using JOIN Syntax To use the inner join syntax. Any additional conditions that do not relate to the actual join are specified in either the WHERE clause or as part of the actual join in the ON clause.PROJECT WHERE EMPNO = RESPEMP AND LASTNAME > 'S' This query returns the same output as the previous example. you want the EMPNO and LASTNAME columns from the CORPDATA. LASTNAME. Since only employees that have last names starting with at least ’S’ are to be returned.PROJECT table. You want to see those employees that are not currently in charge of 76 DB2 UDB for AS/400 SQL Programming V4R4 . Only employees with last names starting with ’S’ or later should be considered. PROJNO FROM CORPDATA. LASTNAME. along with the join condition that applies to the tables. and project numbers for all employees that are responsible for a project. SELECT EMPNO. The tables to be joined are listed in the FROM clause. return those employees that are not responsible for any projects. LASTNAME.a project as well. PROJNO FROM CORPDATA. along with their assigned project numbers.PROJECT ON EMPNO = RESPEMP WHERE LASTNAME > 'S' The result of this query contains some employees that do not have a project number. LASTNAME. The previous query could be rewritten in the following way: Chapter 5.EMPLOYEE EXCEPTION JOIN CORPDATA. but have the null value returned for their project number. Using the same tables as before. The following query will return a list of all employees whose names are greater than ’S’.PROJECT ON EMPNO = RESPEMP WHERE LASTNAME > 'S' This join returns the output: EMPNO 000170 000180 000190 000280 000300 000310 LASTNAME YOSHIMURA SCOUTTEN WALKER SCHNEIDER SMITH SETRIGHT PROJNO - An exception join can also be written as a subquery using the NOT EXISTS predicate. PROJNO FROM CORPDATA.EMPLOYEE LEFT OUTER JOIN CORPDATA. SELECT EMPNO. Exception Join An exception join returns only the records from the first table that do NOT have a match in the second table. They are listed in the query. SELECT EMPNO. EMPNO 000020 000060 000100 000170 000180 000190 000250 000280 000300 000310 LASTNAME THOMPSON STERN SPENSER YOSHIMURA SCOUTTEN WALKER SMITH SCHNEIDER SMITH SETRIGHT PROJNO PL2100 MA2110 OP2010 AD3112 - Notes 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. Advanced Coding Techniques 77 . The number of rows in the result table is the product of the number of rows in each table. If you wanted to return all the employees. 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. 78 DB2 UDB for AS/400 SQL Programming V4R4 .PROJECT WHERE EMPNO = RESPEMP) The only difference in this query is that it cannot return values from the PROJECT table. and the project they are responsible for. Table A T1COL1 A1 A2 A3 T1COL2 AA1 AA2 AA3 Table 14. if any. Table B T2COL1 B1 B2 T2COL2 BB1 BB2 The following two select statements produce identical results. their department name. If the tables involved are large. this join can take a very long time. Table 13. B The result table for either of these select statements looks like this: T1COL1 A1 A1 A2 A2 A3 A3 T1COL2 AA1 AA1 AA2 AA2 AA3 AA3 T2COL1 B1 B2 B1 B2 B1 B2 T2COL2 BB1 BB2 BB1 BB2 BB1 BB2 Using multiple join types in one statement There are times when more than two tables need to be joined to produce the desired result.EMPLOYEE WHERE LASTNAME > 'S' AND NOT EXISTS (SELECT * FROM CORPDATA. 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 EMPLOYEE table. Suppose the following tables exist. SELECT * FROM A CROSS JOIN B SELECT * FROM A.SELECT EMPNO. LASTNAME FROM CORPDATA. following the nested table expression to name the derived table. v The sort sequence is applied to all character and UCS-2 graphic columns being joined. They can be used in place of a view to avoid creating the view when general use of the view is not required. suppose you want a result table that shows the manager number. v If you do not list the column names you want. but instead use SELECT *. PROJNO FROM CORPDATA.DEPARTMENT table. The outer select then uses T2 to qualify columns that are selected from the derived table. The manager number is in the DEPARTMENT table. Nested table expressions are specified within parentheses in the FROM clause. and maximum salary for each department. Column names that are unique do not need to be qualified. For example. the department number is in both the DEPARTMENT and EMPLOYEE tables. and the salaries are in the EMPLOYEE table. in this case MAXSAL and Chapter 5. The following example shows the query and the results. and so on. and PROJECT table would all need to be joined to get the information. you must qualify each common name with the name of the table (or a correlation name). | | | | | | | | | | | | | | | Using Table Expressions You can use table expressions to specify an intermediate result table. SELECT EMPNO. v You must be authorized to select rows from each table or view specified in the FROM clause. Table expressions consist of nested table expressions and common table expressions. You add a correlation name.DEPARTMENT ON WORKDEPT = DEPTNO LEFT OUTER JOIN CORPDATA. DEPTNAME. department number. SQL returns rows that consist of all the columns of the first table. Advanced Coding Techniques 79 . You can use a table expression in the from clause to select the maximum salary for each department. followed by all the columns of the second table. T2.PROJECT ON EMPNO = RESPEMP WHERE LASTNAME > 'S' EMPNO 000020 000060 000100 000170 000180 000190 000250 000280 000300 000310 LASTNAME THOMPSON STERN SPENSER YOSHIMURA SCOUTTEN WALKER SMITH SCHNEIDER SMITH SETRIGHT DEPTNAME PLANNING MANUFACTURING SYSTEMS SOFTWARE SUPPORT MANUFACTURING SYSTEMS MANUFACTURING SYSTEMS MANUFACTURING SYSTEMS ADMINISTRATION SYSTEMS OPERATIONS OPERATIONS OPERATIONS PROJNO PL2100 MA2110 OP2010 AD3112 - Notes on Joins When you join two or more tables: v If there are common column names.EMPLOYEE INNER JOIN CORPDATA. LASTNAME. The first character of the department number has some meaning and you want to get the minimum and maximum for those departments that start with the letter ’D’ and those that start with the letter ’E’. in this case.33 MIN ( AVGSAL ) 20. 80 DB2 UDB for AS/400 SQL Programming V4R4 . MAXSAL FROM CORPDATA.998.677. T1. you must name the derived table. For example. suppose you want a table that shows the minimum and maximum of the average salary of a certain set of departments.250. it processes each subselect to form an interim result table. MAX(AVGSAL). then it combines the interim result table of each subselect and deletes duplicate rows to form a combined result table.DEPTNO = E. The AS clause is used to do that. (SELECT MAX(SALARY) AS MAXSAL.00 26. Again.WORKDEPT GROUP BY E.00 32. AVG(SALARY) AS AVGSAL FROM CORPDATA.153. MIN(AVGSAL) FROM DT WHERE DEPTNO LIKE 'E%' UNION SELECT 'D'.DEPTNO.150.WORKDEPT) SELECT 'E'.EMPLOYEE E1 GROUP BY WORKDEPT) T2 WHERE T1. MAX(AVGSAL).| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | WORKDEPT. You can then specify a SELECT statement using a WHERE clause to restrict the selection to only the departments that begin with a certain letter.175.00 29.DEPARTMENT D . CORPDATA.00 38. When SQL encounters the UNION keyword. They can be used when the same result table needs to be shared in a full-select.00 24.WORKDEPT ORDER BY DEPTNO The result of the query is: MGRNO DEPTNO 000010 A00 000020 B01 000030 C01 000060 D11 000070 D21 000050 E01 000090 E11 000100 E21 MAXSAL 52. Note that the MAX(SALARY) column selected in the nested table expression must be named in order to be referenced in the outer select.DEPARTMENT T1.00 40.00 25. you can combine two or more subselects to form a single select-statement.DEPTNO = T2.750.00 Common table expressions can be specified prior to the full-select in a SELECT statement. WORKDEPT FROM CORPDATA.175.250.170.750. WITH DT AS (SELECT E. Specify a UNION to get the results for the letter ’E’ and the results for the letter ’D’.00 36. Specify the minimum and maximum of column AVGSAL from the derived table DT. or a CREATE VIEW statement. MIN(AVGSAL) FROM DT WHERE DEPTNO LIKE 'D%' The result of the query is: E D MAX ( AVGSAL ) 40. SELECT MGRNO.77 Using the UNION Keyword to Combine Subselects Using the UNION keyword. an INSERT statement.EMPLOYEE E WHERE D.250.00 41. the name is DT. You can use a common table expression to select the average salary for each department.WORKDEPT AS DEPTNO. Common table expressions are preceeded with the keyword WITH. You can use any of the clauses and techniques you have learned so far when coding select-statements. Advanced Coding Techniques 81 . imagine that SQL goes through the following process: Chapter 5.. To better understand what results from these SQL statements..EMP_ACT WHERE PROJNO = 'MA2112' OR PROJNO = 'MA2113' OR PROJNO = 'AD3111' ORDER BY EMPNO END-EXEC. . You can use UNION to eliminate duplicates when merging lists of values obtained from several tables. EXEC SQL FETCH XMP6 INTO :EMP-NUMBER END-EXEC. MA2113.You use UNION to merge lists of values from two or more tables. and AD3111 The combined list is derived from two tables and contains no duplicates. To do this.EMPLOYEE WHERE WORKDEPT = :WORK-DEPT UNION SELECT EMPNO FROM CORPDATA... . you can obtain a combined list of employee numbers that includes: v People in department D11 v People whose assignments include projects MA2112. EXEC SQL DECLARE XMP6 CURSOR FOR SELECT EMPNO FROM CORPDATA. including ORDER BY. specify: MOVE 'D11' TO WORK-DEPT. For example. The ORDER BY clause specifies that the combined result table is to be in collated sequence. The number refers to the position of the expression in the list of expressions you include in your subselects.EMP ACT) 000230 000230 000230 .Step 1: SQL processes the first SELECT statement: Which results in an interim result table: (from CORPDATA.. SELECT A + B AS X . EMPNO.. Step 3: SQL combines the two interim result tables: Which results in a combined result table with values in ascending sequence: fetch EMP-NUMBER 1 2 3 4 5 . A result column is named if the corresponding columns in each of the unioned select-statements have the same name. the results are sequenced on the basis of the first selected column.. RV3W186-0 When you use UNION: v Any ORDER BY clause must appear after the last subselect that is part of the union.... v A name may be specified on the ORDER BY clause if the result columns are named...... 82 DB2 UDB for AS/400 SQL Programming V4R4 . SELECT A + B . 000060 000150 000160 000170 000180 . ORDER BY 1 You cannot use UNION when creating a view.....EMPLOYEE) 000060 000150 000160 000170 . An AS clause can be used to assign a name to columns in the select list. UNION SELECT X .. ORDER BY X If the result columns are unnamed. UNION SELECT X . Step 2: SQL processes the second SELECT statement: Which results in another interim result table: (from CORPDATA. use numbers to order the result. In this example. . Chapter 5.EMP_ACT gives the same result as: SELECT PROJNO FROM CORPDATA.. RV3W187-0 v The UNION ALL operation is associative.PROJECT UNION ALL SELECT PROJNO FROM CORPDATA. see chapter 4 of the DB2 UDB for AS/400 SQL Reference book. Y. When SQL returns your results. The sort sequence is used for the distinct processing that implicitly occurs during UNION processing. 000060 000150 000150 000150 000160 000160 000170 000170 .EMP_ACT) v When you include the UNION ALL in the same SQL statement as a UNION operator. Step 3. Advanced Coding Techniques 83 . the result of the operation depends on the order of evaluation.PROJECT UNION ALL (SELECT PROJNO FROM CORPDATA. Note: Sort sequence is applied after the fields across the UNION pieces are made compatible.. however..PROJECT) UNION ALL SELECT PROJNO FROM CORPDATA.To identify which subselect each row is from. for example: (SELECT PROJNO FROM CORPDATA. 'B2' When a row is presented to your program. For example. SQL uses the set of column names specified in the first subselect when interactive SQL displays or prints the results. specify UNION ALL instead of just UNION. Specifying UNION ALL If you want to keep duplicates in the result of a UNION. or in the SQLDA resulting from processing an SQL DESCRIBE statement. If the column names in the union are different. For information on compatibility of the length and data type for columns in a UNION. you can include a constant at the end of the select list of each subselect in the union. B. 'A1' . you can specify: SELECT A... SQL combines two interim result tables: Resulting in a result table that includes duplicates: fetch EMP-NUMBER 1 2 3 4 5 6 7 8 . the last column contains the constant for the subselect that is the source of that row. it includes a value (either A1 or B2) to indicate the table that is the source of the row’s values.PROJECT UNION ALL SELECT PROJNO FROM CORPDATA. UNION SELECT X. names.EMPLOYEE WHERE EMPNO .. suppose you want a list of the employee numbers. followed. LASTNAME. The SELECT statement surrounding the subquery is called the outer-level SELECT. JOB FROM CORPDATA. you specified a search condition by using a literal value. names..EMPLOYEE WHERE EMPNO IN (SELECT EMPNO FROM CORPDATA. an expression.Where there are no parentheses. you know that you are searching for a specific value. say project number MA2100. The inner SELECT statement is called a subquery. Where parentheses are included. from left to right. and job codes of all employees working on a particular project. You do not know which employees are working on project MA2100 without issuing another SELECT statement against the CORPDATA. by the other parts of the statement. In those search conditions. With SQL. but sometimes you cannot supply that value until you have retrieved other data from a table.EMP_ACT table. evaluation is from left to right. Using Subqueries In the WHERE and HAVING clauses you have seen so far.EMPLOYEE table does not include project number data. Using a subquery. For example. or the registers.EMP_ACT WHERE PROJNO = 'MA2100') To better understand what will result from this SQL statement. you could issue just one SQL statement to retrieve the employee numbers. and job codes for employees who work on project MA2100: DECLARE XMP CURSOR FOR SELECT EMPNO. a column name. The first part of the statement is easy to write: DECLARE XMP CURSOR FOR SELECT EMPNO. the parenthesized subselect is evaluated first. LASTNAME. JOB FROM CORPDATA. imagine that SQL goes through the following process: 84 DB2 UDB for AS/400 SQL Programming V4R4 . you can nest one SELECT statement within another to solve this problem. But you cannot go further because the CORPDATA. For example. the operand is EMPNO and operator is IN. In fact. The search condition can be part of a WHERE or HAVING clause. it is evaluated only once. and can be linked Chapter 5.EMPLOYEE. The search condition is in the form operand operator (subquery). the previous subquery has the same content for every row of the table CORPDATA. In the example.EMP ACT) 000010 000110 Step 2: The interim results table then serves as a list in the search condition of the outer-level SELECT. More information on correlated subqueries can be found in “Correlated Subqueries” on page 88. Essentially. can be preceded by the keyword NOT.Step 1: SQL evaluates the subquery to obtain a list of EMPNO values: Which results in an interim results table: (from CORPDATA. The mechanism that allows this is called correlation. The final result table looks like this: fetch 1 2 EMPNO 000010 000110 LASTNAME HAAS LUCCHESSI JOB PRES 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). like any other search condition. Advanced Coding Techniques 85 . can be enclosed in parentheses. Subqueries like this are said to be uncorrelated. if the subquery is the same for every row or group. Subqueries and Search Conditions A subquery is always part of a search condition. what is said before that point applies equally to correlated and uncorrelated subqueries. and the subqueries are said to be correlated. Even so. Some subqueries vary in content from row to row or group to group. A search condition containing a subquery. The clause can include more than one search condition that contains a subquery. This is done through the result table that the subquery produces. this is what is executed. the subquery is evaluated whenever a new row or group of rows must be qualified. Conceptually. the result of the compare is unknown. suppose you use the greater-than comparison operator with ALL: . SQL allows nesting down to a nesting level of 32. In this example. For example. or SOME. the result is (as it should be) the company-wide average educational level. no values were selected). and SOME in the following ways: v Use ALL to indicate that the value you supplied must compare in the indicated way to ALL the values the subquery returns. Consider. For example. names. then. greater than the highest value) returned by the subquery. If the subquery returns an empty set (that is. LASTNAME. a subquery could return no value at all.EMPLOYEE) SQL first evaluates the subquery and then substitutes the result in the WHERE clause of the SELECT statement. for example.EMPLOYEE WHERE EDLEVEL > (SELECT AVG(EDLEVEL) FROM CORPDATA. and salaries for employees whose education level is higher than the average education level throughout the company. Quantified Comparisons (ALL. If you do. Then the subquery would return no value. In this case.to other search conditions through the keywords AND and OR. the subquery can return at most one value. the subquery can return zero. the value in the expression must be greater than all the values (that is. ANY. If it does. You can use ALL. The value can be the result of a column function or an arithmetic expression. but few queries require a nesting level greater than 1. and SOME) You can use a subquery after a comparison operator followed by the keyword ALL. For example. the first query shown in this section. the condition is satisfied. Besides returning a single value. DECLARE XMP CURSOR FOR SELECT EMPNO. WHERE expression > ALL (subquery) To satisfy this WHERE clause. the WHERE clause of some query could look something like this: WHERE X IN (subquery1) AND (Y > SOME (subquery2) OR Z = 100) Subqueries can also appear in the search conditions of other subqueries. and assume that there are not any employees currently working on project MA2100. SALARY FROM CORPDATA. suppose you want to find the employee numbers. including null values. the result produced by the query would be an empty table. ANY. How Subqueries Are Used There are four ways to include a subquery in either a WHERE or HAVING clause: Basic Comparisons You can use a subquery immediately after any of the comparison operators. For example. ANY. SQL then compares the value that results from the subquery with the value to the left of the comparison operator. a subquery within a subquery within an outer-level SELECT is nested at a nesting level of two. Such subqueries are said to be nested at some level of nesting. and the search condition would be unknown for every row. one. When used in this way. or many values.. 86 DB2 UDB for AS/400 SQL Programming V4R4 .. If what the subquery returns is empty.. the subquery itself would be correlated.LASTNAME FROM CORPDATA. greater than the lowest value) returned by the subquery. the value in the expression must be greater than at least one of the values (that is. In a more powerful example. the subquery must produce a one-column result table. This Chapter 5. WHERE expression > ANY (subquery) To satisfy this WHERE clause.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. either every row appears in the results. you could use: .. and would change from row to row. SQL evaluates the subquery and uses the result as part of the WHERE clause of the outer-level SELECT..PROJECT WHERE PRSTDATE > '1982-01-01'). Please note that this example does not show the full power of EXISTS. Using the IN Keyword You can use IN to say that the value in the expression must be among the values returned by the subquery... when you use the keyword EXISTS. That is.. As shown in the example.. The first example in this chapter illustrates this type of usage. You could also use the IN keyword with the NOT keyword in order to select rows when the value is not among the values returned by the subquery. SQL simply checks whether the subquery returns one or more rows. WHERE WORKDEPT NOT IN (SELECT . the condition is not satisfied. For example. you could use: . For example. Using IN is equivalent to using =ANY or =SOME. For example: DECLARE XMP CURSOR FOR SELECT EMPNO. Advanced Coding Techniques 87 . you can code SELECT *. the search condition holds if any project represented in the CORPDATA. you do not need to specify column names in the subquery of an EXISTS clause. or none appear. See “Correlated Subqueries” on page 88 for more information on correlated subqueries. unless you are familiar with formal logic. If it does. In contrast.) Using the EXISTS Keyword In the subqueries presented so far.) For all general types of usage for subqueries but one (using a subquery with the EXISTS keyword). 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. For applicable rules. As a consequence.. read the discussion of quantified predicates in the DB2 UDB for AS/400 SQL Reference . In the example. because the result is always the same for every row examined for the outer-level SELECT. Instead.PROJECT table has an estimated start date that is later than January 1.. Using ANY and SOME were previously described.EMPLOYEE WHERE EXISTS (SELECT * FROM CORPDATA. 1982. Note: The results when a subquery returns one or more null values may surprise you. suppose you use the greater-than comparison operator with ANY: . If it does not (if it returns no rows). WHERE NOT EXISTS (SELECT .. the condition is satisfied. the condition is not satisfied. When you do. you can use subqueries in the WHERE clause of the UPDATE or DELETE statement. 4. v You can use a subquery in the HAVING clause of a SELECT statement. Using Subqueries with UPDATE and DELETE In the examples shown so far. the result table of a subselect must contain the same number of values as the corresponding list of columns to be updated. no more than one row is allowed. When nesting SELECT statements. In any subquery. but for comparisons not involving the keywords ALL. When the outer statement is a SELECT statement (at any level of nesting): v The subquery can be based on the same table or view as the outer statement. as in any search condition. Correlated Subqueries In the subqueries previously discussed. or SOME. Notes on Using Subqueries | | | | 1. UPDATE. For the most part. you have seen subqueries within SELECT statements. although performance is slower for each additional subquery. the values compared must be compatible. FOR READ ONLY. 3. SQL evaluates the subquery once. ANY. 6. or on a different table or view. The data type of the column does not change after SQL applies a column function or arithmetic operator. or contain a single expression. 5. You can also use subqueries in the WHERE clause of the UPDATE or DELETE statements or in the SET clause of an UPDATE. For some usages. this is not very different from using subqueries with outer-level SELECTs. both of the following SELECT clauses would be allowed for all four usage types: SELECT AVG(SALARY) SELECT EMPNO The result table produced by a subquery can have zero or more rows. CREATE VIEW. and evaluates the outer-level SELECT based on the value of the search condition. When the statement is an UPDATE or DELETE statement. When a subquery is used in the SET clause of an UPDATE statement. SQL evaluates the subquery and uses it to qualify each group. you can use as many as you need to satisfy your requirements (1 to 31 subqueries). A subquery cannot include the ORDER BY. or INSERT statement. unless the subquery is being used with the EXISTS keyword. 7. For example. substitutes the result of the subquery in the right side of the search condition. A maximum of 128 tables can be specified in an SQL statement. the result table for a subquery must consist of a single column. even when the outer-level SELECT is part of a DECLARE CURSOR. You can also write a subquery that SQL may have to re-evaluate as it examines each 88 DB2 UDB for AS/400 SQL Programming V4R4 . 2. In all other cases. the number of rows must be zero or one. UNION. Using a column function or an arithmetic expression with a column name in a subquery does not make it incompatible. or OPTIMIZE clauses. The number of rows in this table can vary from zero to many. v You can use a subquery in the WHERE clause of the outer-level SELECT. UNION ALL.means that the SELECT clause in a subquery must name a single column. WORKDEPT) A correlated subquery looks like an uncorrelated one. To get this information.new row (WHERE clause) or group of rows (HAVING clause) in the outer-level SELECT. Before it is executed. Suppose. the occurrence of X. for the row considered. For some other row for which WORKDEPT has a different value. that value appears in the subquery in place of A00. for example.EMPLOYEE table. that the row is for CHRISTINE I HAAS. SQL must search the CORPDATA. For each employee in the table.EMPLOYEE X WHERE EDLEVEL > (SELECT AVG(EDLEVEL) FROM CORPDATA.EMPLOYEE. In the example. and the subquery for his row would deliver the average education level for department B01. the subquery produces the average education level of Christine’s department. LASTNAME. EDLEVEL FROM CORPDATA. for the row for MICHAEL L THOMPSON. In the subquery. The subquery executed for this row is: (SELECT AVG(EDLEVEL) FROM CORPDATA. which is the value of WORKDEPT for this row. the qualifier X is the correlation name defined in the FROM clause of the outer SELECT statement. Advanced Coding Techniques 89 .EMPLOYEE WHERE WORKDEPT = X. the single correlated reference is the occurrence of X.EMPLOYEE. For example. SQL needs to compare the employee’s education level to the average education level for the employee’s department. Here. you tell SQL to calculate the average education level for the department number in the current row. Her work department is A00. This is called a correlated subquery. except for the presence of one or more correlated references. consider what happens when the subquery is executed for a given row of CORPDATA. this value would be B01. For example: DECLARE XMP CURSOR FOR SELECT EMPNO. This is then compared in the outer statement to Christine’s own education level. Now. Example of a Correlated Subquery in a WHERE Clause Suppose that you want a list of all the employees whose education levels are higher than the average education levels in their respective departments. X is introduced as the correlation name of the table CORPDATA.WORKDEPT in the subselect’s FROM clause. The result table produced by the query would have the following values: Chapter 5.WORKDEPT is replaced with the value of the WORKDEPT column for that row.EMPLOYEE WHERE WORKDEPT = 'A00') Thus. WORKDEPT. In that clause. DECIMAL(AVG(SALARY).(from CORPDATA.1.WORKDEPT. The result table produced by the query would have the following values: 90 DB2 UDB for AS/400 SQL Programming V4R4 . For example: DECLARE XMP CURSOR FOR SELECT WORKDEPT.1.EMPLOYEE WHERE SUBSTR('A00'. For each department in the table. SQL calculates the average salary for the area of the department in the current group. SQL compares the department’s average salary to the average salary of the area. The subquery executed for this group is: (SELECT AVG(SALARY) FROM CORPDATA. Suppose.1) = SUBSTR(WORKDEPT. In the subquery.WORKDEPT is replaced with the value of the WORKDEPT column for that group.EMPLOYEE.EMPLOYEE) fetch EMPNO 1 2 3 4 000010 000030 000070 000090 LASTNAME HAAS KWAN PULASKI HENDERSON WORKDEPT A00 C01 D21 E11 EDLEVEL 18 20 16 16 RV2W560-3 Example of a Correlated Subquery in a HAVING Clause Suppose that you want a list of all the departments whose average salary is higher than the average salary of their area (all departments whose WORKDEPT begins with the same letter belong to the same area). the occurrence of X.1) = SUBSTR(WORKDEPT. that the first group selected has A00 for the value of WORKDEPT. SQL must search the CORPDATA.1. for the group considered. For some other group for which WORKDEPT is ’B01’.EMPLOYEE table.1. for example.EMPLOYEE X GROUP BY WORKDEPT HAVING AVG(SALARY) > (SELECT AVG(SALARY) FROM CORPDATA. the subquery produces the average salary for the area.1)) Thus. Before it is executed. To get this information.EMPLOYEE WHERE SUBSTR(X. This is then compared in the outer statement to the average salary for department 'A00'.2) FROM CORPDATA. the subquery would result in the average salary for the area where department B01 belongs.1)) Consider what happens when the subquery is executed for a given department of CORPDATA.8. The correlation name is defined in the FROM clause of some query. You can define a correlation name for each table name appearing in a FROM clause. In the preceding example. TABLEC. for example. Note that in this case. For example. The substituted value is then taken from this group. The following FROM clause. The reference is always of the form X. B. v If the subquery is in the HAVING clause. Before the subquery is executed. when all Chapter 5. There are no restrictions on variety. one correlated name in a reference could be defined in the outer-level SELECT. Leave one or more blanks between a table name and its correlation name.EMPLOYEE) fetch WORKDEPT 1 2 D21 E01 AVG SALARY 25153. a value from the referenced column is always substituted for the correlated reference. Using Correlated Subqueries in an UPDATE Statement When you use a correlated subquery in an UPDATE statement.33 40175. the correlation name refers to the rows you are interested in updating. or any of the subqueries that contain the one with the reference. Then the subquery is either in the WHERE clause of D. while another could be defined in a containing subquery. The substituted value is then taken from this row. for example. or the outer-level SELECT. If it is not. and no correlation name for the table TABLEC. its results are used by D to qualify a group of rows. X represents the table CORPDATA. and that A contains B and B contains C. and C identifies the column WORKDEPT in this table. Advanced Coding Techniques 91 . and place a comma after the correlation name if it is followed by another table name. For example. v If the subquery is in the WHERE clause. defines the correlation names TA and TB for the tables TABLEA and TABLEB.C. for instance.00 RV2W561-3 Correlated Names and References A correlated reference can appear only in a search condition in a subquery. This query could be the outer-level SELECT. This is the case for the example.(from CORPDATA.EMPLOYEE. TABLEB TB Any number of correlated references can appear in a subquery. Suppose. or in its HAVING clause. Simply include the correlation names after the table names. the column specified must be identified in the GROUP BY clause in D. and C. FROM TABLEA TA. where the defining query is the outer one and the subquery appears in the outer query’s WHERE clause. that a query contains subqueries A. Then a correlation name used in C could be defined in B. The value is determined as follows: Note: Use D to designate the query in which the correlation name is defined. where X is a correlation name and C is the name of a column in the table that X represents. A. its results are used by D to qualify a row. the specified column could have more than one value for the group. 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. of the outer-level SELECT.EMPLOYEE X.. v You can use correlated subqueries in HAVING clauses.EMP_ACT row is deleted.PROJECT table). UPDATE CORPDATA. 92 DB2 UDB for AS/400 SQL Programming V4R4 . SQL evaluates the correlated subquery once for each row in the table named in the DELETE statement to decide whether or not to delete the row. for each row in the CORPDATA.EMP_ACT table must also be deleted. the current row in the CORPDATA. v The correlated subquery and the outer-level statement can refer to the same table or to different tables.EMP_ACT table. v The outer-level SELECT that defines the correlation name can join two or more tables.EMP_ACT table.PROJECT .PROJECT table was deleted. the correlation name represents the row you delete.PROJNO) SQL determines. your department considers that project to be a priority project.. When you do..activities of a project must be completed before September 1983. Notes on Using Correlated Subqueries v The correlation name is separated from its associated table name with a space.EMP_ACT X WHERE NOT EXISTS (SELECT * FROM CORPDATA.PROJECT table. CORPDATA.PROJECT table qualifies and is updated. SQL evaluates the subquery.EMP_ACT WHERE PROJNO = X. and write a 1 (a flag to indicate PRIORITY) in the PRIORITY column (a column you added to CORPDATA.PROJECT for this purpose) for each priority project. The column you refer to in the HAVING clause must specify a property of each group (for example. whether a row with the same project number exists in the CORPDATA. Using Correlated Subqueries in a DELETE Statement When you use a correlated subquery in a DELETE statement.PROJECT X SET PRIORITY = 1 WHERE '1983-09-01' > (SELECT MAX(EMENDATE) FROM CORPDATA. it determines the maximum activity end date (EMENDATE) for all activities of the project (from the CORPDATA. once per group.PROJECT table. If the end date of each activity associated with the project is prior to September 1983. Rows related to the deleted project in the CORPDATA. precede the table name with a comma.PROJECT WHERE PROJNO = X. v In an INSERT statement. for example: FROM CORPDATA. WORKDEPT) either the columns you grouped the rows by or another column with one of the column functions. Suppose a row in the CORPDATA. To do this.PROJNO) As SQL examines each row in the CORPDATA. To specify another table name. You could use the SQL statement below to evaluate the projects in the CORPDATA. you can use: DELETE FROM CORPDATA. If not. the CORPDATA. default value. You can add. you can use the ALTER COLUMN clause of the ALTER TABLE statement. data may be lost due to truncation. Changing a Table Definition | | | | Changing the definition of a table allows you to add new columns. Adding a column | | You can add a column to a table using Operations Navigator. Changing a column | | | | | | | | | | | | | | You can change a column in a table using Operations Navigator. 32740. If you have a column that does not allow the null value and you want to change it to now allow the null value. change an existing column definition (change its length. the ALTER TABLE will not be performed and an SQLCODE of -190 will result. use the SET NOT NULL clause. use the SQL ALTER TABLE statement. and add and remove constraints. When you add a new column to a table. However. and so on).v You can nest correlated subqueries. or drop columns and add or remove constraints all with one ALTER TABLE statement. if a VARCHAR or VARGRAPHIC column is specified. ALTER COLUMN. When you convert to a data type with a longer length. Advanced Coding Techniques 93 . When you convert to a data type with a shorter length. Or use the ADD COLUMN clause of the SQL ALTER TABLE statement. Or. If NOT NULL is specified. That is. The sum of the byte counts of the columns must not be greater than 32766 or. data will be padded with the appropriate pad character. If you have a column that allows the null value and you want to prevent the use of null values. If any of the existing values in that column are the null value. An inquiry message prompts you to confirm the request. | | | | The altered table may consist of up to 8000 columns. the sum of record data byte counts of the columns must not be greater than 15 728 640. a single column can be referenced only once in the ADD COLUMN. Allowable Conversions Table 15. drop existing columns. and DROP COLUMN clauses. the column is initialized with its default value for all existing rows. a default value must also be specified. Or. When you change the data type of an existing column. “Allowable Conversions” shows the conversions with compatible attributes. change. If a LOB column is specified. Allowable Conversions FROM data type Decimal TO data type Numeric Chapter 5. use the DROP NOT NULL clause. You can change the definition of a table using Operations Navigator. the old and new attributes must be compatible. you cannot add a column and then alter that column in the same ALTER TABLE statement. For example. given the following table definition: CREATE TABLE EX1 (COL1 CHAR(10) DEFAULT 'COL1'. Allowable Conversions (continued) FROM data type Decimal Decimal Numeric Numeric Numeric Integer. and COL3 would still have an allocated length of 10. COL3 VARGRAPHIC(20) ALLOCATE(10) NOT NULL WITH DEFAULT) After running the following ALTER TABLE statement: ALTER TABLE EX1 ALTER COLUMN COL2 SET DATA TYPE VARCHAR(30) ALTER COLUMN COL3 DROP NOT NULL COL2 would still have an allocated length of 10 and CCSID 937. Smallint DBCS-open UCS-2 graphic Character UCS-2 graphic Character DBCS-open UCS-2 graphic DBCS-open DBCS graphic UCS-2 graphic UCS-2 graphic Character DBCS-open DBCS graphic source type distinct type | | | | | | | | | | distinct type source type When modifying an existing column. Smallint Float Float Character Character DBCS-open DBCS-open DBCS-either DBCS-either DBCS-either DBCS-only DBCS-only DBCS-only DBCS graphic UCS-2 graphic UCS-2 graphic UCS-2 graphic TO data type Integer. Smallint Float Decimal Numeric Float Numeric Integer. Smallint Integer. only the attributes that you specify will be changed. Smallint Float Decimal Integer. Smallint Integer. COL2 VARCHAR(20) ALLOCATE(10) CCSID 937. 94 DB2 UDB for AS/400 SQL Programming V4R4 .Table 15. All other attributes will remain unchanged. or a HAVING clause. or constraints are dependent on the column. Advanced Coding Techniques 95 . Drop constraints 2. If RESTRICT is specified.EMPLOYEE The previous view can also be defined by using the AS clause in the select list to name the columns in the view. the column will not be dropped and SQLCODE of -196 will be issued. Add constraints Within each of these steps. indexes. In the following example. Creating and Using Views A view can be used to access part of the data in one or more tables. If CASCADE is specified.HIREDATE) FROM CORPDATA. Dropping a column deletes that column from the table definition.EMP_MANAGERS AS SELECT LASTNAME. YEARS (CURRENT DATE . YEARSOFSERVICE) AS SELECT LASTNAME. any views. indexes. with one exception. a GROUP by clause.EMP_YEARSOFSERVICE AS SELECT LASTNAME. For example.EMP_YEARSOFSERVICE (LASTNAME. specify: CREATE VIEW CORPDATA. YEARS (CURRENT_DATE . and the AS clause was not used to name the columns. If any columns are being dropped. that operation is logically done before any column definitions are added or altered. For example: CREATE VIEW CORPDATA. a column list must be specified for the view. Or you can delete a column using the DROP COLUMN clause of the ALTER TABLE statement. the columns of the view are LASTNAME and YEARSOFSERVICE. you can specify a WHERE clause. Drop columns for which the RESTRICT option was specified 3. To define the rows in the view. Order of operations for ALTER TABLE statement | | | | | | | An ALTER TABLE statement is performed as a set of steps as follows: 1.Deleting a column | | You can delete a column using Operations Navigator. constants. and constraints dependent on that column will also be dropped. You can define the columns of the view in the SELECT clause and the tables the view is based on in the FROM clause. WORKDEPT FROM CORPDATA. functions. to create a view that selects only the last name and the department of all the managers. CREATE VIEW CORPDATA. and any views.HIREDATE) AS YEARSOFSERVICE FROM CORPDATA.EMPLOYEE WHERE JOB = 'MANAGER' If the select list contains elements other than columns such as expressions. Alter column definitions (this includes adding columns and dropping columns for which the CASCADE option was specified) 4. in case record length is increased as a result of the ALTER TABLE statement. the order in which you specify the clauses is the order in which they are performed. or special registers.EMPLOYEE Chapter 5. or DELETE. v You cannot use UNION. You can create an index when creating a table using Operations Navigator. STDDEV. but you cannot use statements such as INSERT. – The first SELECT clause contains any of the SQL column functions (SUM. 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. 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. insert. The following example creates an index over the column LASTNAME in the CORPDATA. – The view has a column resulting from an expression. MAX. AVG. v You cannot update a column of a view that results from an expression. The following restrictions must be considered when creating the view: v You cannot change. UNION ALL. UPDATE. Or use the SQL CREATE INDEX statement. – The first SELECT clause specifies the keyword DISTINCT. A view is read-only if it includes any of the following: – The first FROM clause identifies more than one table (join). indexes help the system retrieve data faster for better query performance.INX1 ON CORPDATA.EMPLOYEE table: CREATE INDEX CORPDATA. does not allow nulls. See “WITH CHECK OPTION on a View” on page 108 for more information. Adding Indexes | | | | | | You can use indexes to sort and select data. you can get data from the views by means of the SQL SELECT statement. or delete data in a read-only view. you can use it to select the data or possibly change the data in the base table. – The first FROM clause identifies a read-only view. or OPTIMIZE FOR n ROWS in the definition of a view. a constant. MIN. such that the base object of the outer-most subselect and a table of a subquery are the same table In the above cases. a function. COUNT. In addition. – The WITH CHECK OPTION was specified when the view was created and the row does not match the selection criteria. – The outer subselect contains a GROUP BY or HAVING clause. – A subquery. or VAR). See “Using Sort Sequence in SQL” on page 50 for more information on sort sequences. a function.Once you have created the view.EMPLOYEE (LASTNAME) 96 DB2 UDB for AS/400 SQL Programming V4R4 . Views are created with the sort sequence in effect at the time the CREATE VIEW statement is run. or a special register and the column was specified in the INSERT column list. a constant. The sort sequence applies to all character and UCS-2 graphic comparisons in the CREATE VIEW statement subselect. ORDER BY. or a special register. and is not in the view. FOR READ ONLY. FOR UPDATE OF. When an SQL object is created in a library. another binary tree is still created. However. and given a different name. Getting Catalog Information about a Table SYSTABLES contains a row for every table and view in the SQL collection. see the DB2 UDB for AS/400 SQL Reference book. The sort sequence applies to all SBCS character fields and UCS-2 graphic fields of the index. only the QSYS2 catalog is updated. Saving in one collection and restoring to another is not supported by the product. see “Effectively Using SQL Indexes” on page 446. There is also a system-wide catalog that is always in the QSYS2 library. the owner of the object. 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. the new index shares the existing indexes’ binary tree. If an index is created that has exactly the same attributes as an existing index. Attention: Operations that normally update the SQL catalog for a collection can no longer update the catalog if the collection is saved. restored. For more information about catalogs. another binary tree is created. or UPDATE catalog information. It tells you if the object is a table or view. the encoded vector index.DEPARTMENT table: SELECT * FROM CORPDATA. Indexes are created with the sort sequence in effect at the time the CREATE INDEX statement is run. because the indexes are maintained by the system. See “Using Sort Sequence in SQL” on page 50 for more information on sort sequences. you can display catalog information.| | | | | | | | | | | | | | You can create a number of indexes. Advanced Coding Techniques 97 . go to the DB2 for AS/400 webpages. As the following examples show. A new type of index. The following sample statement displays information for the CORPDATA. the object name.SYSTABLES WHERE NAME = 'DEPARTMENT' Chapter 5. DELETE. and so forth. Otherwise. except the new index has fewer columns. what SQL collection it is in. information is added to both the system catalog tables and the collection’s catalog tables. For more information about indexes and query performance. For more information about accelerating your queries with encoded vector indexes . allows for faster scans that can be more easily processed in parallel. If the attributes of the new index are exactly the same as another index. a large number of indexes can adversely affect performance. You cannot INSERT. You create encoded vector indexes by using the SQL CREATE INDEX statement. Using the Catalog in Database Design A catalog is automatically created when you create a collection. You must have SELECT privileges on the catalog views to run the following examples. When an SQL object is created in a collection. DEPARTMENT table: SELECT * FROM CORPDATA. specify a select-statement like this: SELECT NAME. TBNAME. COLTYPE. 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: NAME DEPTNO DEPTNAME MGRNO ADMRDEPT TBNAME DEPARTMENT DEPARTMENT DEPARTMENT DEPARTMENT COLTYPE CHAR VARCHAR CHAR CHAR LENGTH 3 29 6 3 DEFAULT N N Y N 98 DB2 UDB for AS/400 SQL Programming V4R4 . Some of the information is not visible because the width of the information is wider than the display screen. The following sample statement displays all the column names in the CORPDATA.SYSCOLUMNS WHERE TBNAME = 'DEPARTMENT' The result of the previous sample statement is a row of information for each column in the table. DEFAULT FROM CORPDATA. For more information about each column. LENGTH.SYSCOLUMNS WHERE TBNAME = 'DEPARTMENT' In addition to the column name for each column.Getting Catalog Information about a Column SYSCOLUMNS contains a row for each column of every table and view in the collection. 1999 99 . You can add check constraints using Operations Navigator when creating a table. Referential integrity. 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. it would not make sense to allow a new account to be added to table B unless an associated customer exists in table A. In this example. For example. the WITH CHECK OPTION clause on a CREATE VIEW constrains the inserting or updating of data through a view. This chapter describes the different ways the system automatically enforces these kinds of relationships. Additionally. Or use the SQL CREATE TABLE and ALTER TABLE statements to add or drop check constraints. -1. © Copyright IBM Corp. COL3 INT) Given this table. -1) would fail because the value to be inserted into COL2 does not meet the check constraint. that is. For comprehensive information about data integrity. 1. check constraints. the following statement creates a table with three columns and a check constraint over COL2 which limits the values allowed in that column to positive integers: CREATE TABLE T1 (COL1 INT. 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). the following statement: INSERT INTO T1 VALUES (-1. COL2 INT CHECK (COL2>0). 1997. see the DB2 UDB for AS/400 Database Programming book. 1) Once that row is inserted. and triggers are all ways of accomplishing data integrity. Adding and Using Check Constraints | | | | A check constraint assures the validity of data during inserts and updates by limiting the allowable values in a column or group of columns. Data Integrity Data integrity is the principle of ensuring data values between tables of a collection are kept in a state which makes sense to the business.Chapter 6. Referential Integrity | | Referential integrity is the condition of a set of tables in a database in which all references from one table to another are valid. The following statement would be successful: INSERT INTO T1 VALUES (1. if a bank has a list of customers in table A and a list of customer accounts in table B. -1 is not greater than 0. When a table contains data for which there is a master list. Each value of the foreign key must also exist in the parent key or be null. that data should actually appear in the master list.EMPLOYEE serves as a master list of employees. For detailed descriptions of these commands. you specify: v A primary or unique key 100 DB2 UDB for AS/400 SQL Programming V4R4 . to data in another table. v A primary key is a unique key that does not allow nulls.DEPARTMENT acts as a master list of all valid department numbers. the condition of the set of tables is called referential integrity. v A parent key is either a unique key or a primary key which is referenced in a referential constraint. v A parent table is a table that contains the parent key. v CORPDATA. If any column value used to build the foreign key is null.| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Consider the following example: (These sample tables are given in Appendix A. Stated another way. With a referential constraint. You can add referential constraints using Operations Navigator when creating a table. or the reference is not valid. no two rows in a table can have the same unique key value. referential integrity is the state of a database in which all values of all foreign keys are valid. v A descendent table is a table that is a dependent table or a descendent of a dependent table. see the DB2 UDB for AS/400 SQL Reference book. then the rule does not apply. Adding or dropping referential constraints | | | | | | | | | | “Constraints” on page 375 are rules that ensure that references from one table. use the SQL CREATE TABLE and ALTER TABLE statements to add or change referential constraints. When you define a referential constraint. Although a table can have several unique keys. v A dependent table is the table that contains the foreign key. v CORPDATA. The table that contains the master list is the parent table.EMP_ACT provides a master list of activities performed for projects. When the references from the dependent table to the parent table are valid. DB2 UDB for AS/400 Sample Tables: v CORPDATA. Enforcement of referential integrity prevents the violation of the rule which states that every non-null foreign key must have a matching parent key. Or. Other tables refer to the same entities described in these tables. non-null values of the foreign key are valid only if they also appear as values of a parent key. This definition of referential integrity requires an understanding of the following terms: v A unique key is a column or set of columns in a table which uniquely identify a row. SQL supports the referential integrity concept with the CREATE TABLE and ALTER TABLE statements. the parent table. and the table that refers to it is a dependent table. A table cannot have more than one primary key. You use referential constraints to ensure “Referential Integrity” on page 99. are valid. a dependent table. v A foreign key is a column or set of columns whose values must match those of a parent key. MGRNO CHAR(6).2). COMM DECIMAL(9. Optionally. WORKDEPT CHAR(3) CONSTRAINT WORKDEPT_EXISTS REFERENCES CORPDATA. MIDINIT CHAR(1) NOT NULL.2). BIRTHDATE DATE. The following SQL statements create the CORPDATA. This constraint ensures that every employee belongs to an existing department. If a name is not specified. DEPTNAME VARCHAR(29) NOT NULL. CONSTRAINT UNIQUE_LNAME_IN_DEPT UNIQUE (WORKDEPT.| | | | | | | | | v A foreign key v Delete and update rules that specify the action taken with respect to dependent rows when the parent row is deleted or updated. Data Integrity 101 .2). 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. SEX CHAR(1).DEPARTMENT (DEPTNO) ON DELETE SET NULL ON UPDATE RESTRICT. PHONENO CHAR(4). LASTNAME)) In this case. one is automatically generated. DELETE. BONUS DECIMAL(9. Every non-null value of ADMRDEPT must match a value of DEPTNO.EMPLOYEE tables with those constraint relationships defined. every row in the table for which the ADMRDEPT is n is also deleted. JOB CHAR(8). Once a referential constraint is defined. utilities. and the column of Chapter 6. The DELETE CASCADE rule indicates that if a row with a DEPTNO value n is deleted. and UPDATE operation performed through SQL or any other interface including Operations Navigator. you can specify a name for the constraint. LASTNAME VARCHAR(15) NOT NULL. HIREDATE DATE.DEPARTMENT and CORPDATA. A department must report to an existing department in the database. the system enforces the constraint on every INSERT. EDLEVEL SMALLINT NOT NULL.DEPARTMENT (DEPTNO CHAR(3) NOT NULL PRIMARY KEY. ADMRDEPT CHAR(3) NOT NULL CONSTRAINT REPORTS_TO_EXISTS REFERENCES CORPDATA. CL commands. WORKDEPT_EXISTS establishes the EMPLOYEE table as a dependent table. SALARY DECIMAL(9.EMPLOYEE (EMPNO CHAR(6) NOT NULL PRIMARY KEY. CREATE TABLE CORPDATA. or high-level language statements. FIRSTNAME VARCHAR(12) NOT NULL. Example: adding referential constraints The rule that every department number shown in the sample employee table must appear in the department table is a referential constraint.DEPARTMENT (DEPTNO) ON DELETE CASCADE) CREATE TABLE CORPDATA. DEPARTMENT DROP CONSTRAINT UNIQUE_LNAME_IN_DEPT Inserting into Tables with Referential Constraints There are some important things to remember when inserting data into tables with referential constraints. then the value of WORKDEPT in EMPLOYEE is set to null in every row in which the value was n. the entire foreign key is considered null. DROP TABLE and DROP COLLECTION statements also remove any constraints on the table or collection being dropped. The constraints REPORTS_TO_EXISTS and WORKDEPT_EXISTS defined on tables DEPARTMENT and EMPLOYEE respectively will be removed as well. While this constraint is unlikely. The DELETE SET NULL rule says that if a row is deleted from DEPARTMENT in which the value of DEPTNO is n.employee department assignments (WORKDEPT) as a foreign key. Thus. it illustrates how a constraint made up of several columns can be defined at the table level. as in the following example: ALTER TABLE CORPDATA. the INSERT succeeds (as long as there are no unique index violations). If the constraint being dropped is the parent key in some referential constraint relationship. Removing Referential Constraints | | | | The ALTER TABLE statement can be used to add or drop one constraint at a time for a table. Example of Inserting Data with Constraints Alter the sample application project table (PROJECT) to define two foreign keys: 102 DB2 UDB for AS/400 SQL Programming V4R4 . SQL does not allow: v Duplicate values for the parent key v If the parent key is a primary key. ALTER TABLE CORPDATA. every value of WORKDEPT must match a value of DEPTNO. v If any column in the foreign key is null. Example of Removing Constraints The following example removes the primary key over column DEPTNO in table DEPARTMENT. If you are inserting data into a parent table with a parent key. a null value for any column of the primary key If you are inserting data into a dependent table with foreign keys: v Each non-null value you insert into a foreign key column must be equal to some value in the corresponding parent key of the parent table. 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. If all foreign keys that contain the column are null.EMPLOYEE DROP PRIMARY KEY You can also remove a constraint by name. Constraint UNIQUE_LNAME_IN_DEPT in the EMPLOYEE table causes last names to be unique within a department. since the primary key being removed is the parent key in those constraint relationships. the constraint between this parent file and any dependent files is also removed. Changing the key violates referential constraints for dependent tables and leaves some rows without a parent. PROJNAME. The tables with the sample data as they appear in Appendix A. The following INSERT statement fails because there is no matching DEPTNO value (’A01’) in the DEPARTMENT table. Data Integrity 103 . 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.PROJECT (PROJNO. INSERT INTO CORPDATA.PROJECT (PROJNO. you cannot give any part of a primary key a null value. '000011') The following INSERT statement completes successfully because there is a matching DEPTNO value of ’E01’ in the DEPARTMENT table and a matching EMPNO value of ’000010’ in the EMPLOYEE table. Furthermore.) 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. PROJNAME. you cannot modify a primary key for which dependent rows exist.PROJECT ADD CONSTRAINT RESP_DEPT_EXISTS FOREIGN KEY (DEPTNO) REFERENCES CORPDATA. INSERT INTO CORPDATA. the UPDATE NO ACTION rule is used. 'E01'. '000010') Likewise. 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. 'D21'. ALTER TABLE CORPDATA. DEPTNO. 'BENEFITS ADMIN'. 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. v UPDATE NO ACTION Chapter 6. RESPEMP) VALUES ('AD3130'. (The null value is not allowed because DEPTNO in the project table is defined as NOT NULL.DEPARTMENT ON DELETE RESTRICT ALTER TABLE CORPDATA. If no update rule was defined for a referential constraint. INSERT INTO CORPDATA. 'BENEFITS ADMIN'. '000010') Updating Tables with Referential Constraints If you are updating a parent table. DEPTNO. DB2 UDB for AS/400 Sample Tables conform to these constraints. 'BILLING'. 'A01'. RESPEMP) VALUES ('AD3120'.v A foreign key on the department number (DEPTNO) which references the department table v A foreign key on the employee number (RESPEMP) which references the employee table. PROJNAME. the following INSERT statement would be unsuccessful since there is no EMPNO value of ’000011’ in the EMPLOYEE table. DEPTNO.PROJECT (PROJNO. RESPEMP) VALUES ('AD3120'.PROJECT ADD CONSTRAINT RESP_EMP_EXISTS FOREIGN KEY (RESPEMP) REFERENCES CORPDATA.EMPLOYEE ON DELETE RESTRICT Notice that the parent table columns are not specified in the REFERENCES clause. v UPDATE RESTRICT Specifies that the row in the parent table can be updated if no other row depends on it. 2. but before a constraint rule of NO ACTION (where checking is performed at the end of the statement). You can assign an employee to no department (the null value).DEPARTMENT SET DEPTNO = 'D99' WHERE DEPTNAME = 'DEVELOPMENT CENTER' 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. For example.DEPTNO having a value of ’D01’ (the row targeted by the WHERE statement). UPDATE CORPDATA. department numbers in the employee table depend on the department numbers in the department table. which is described by a dependent row in the project table. 104 DB2 UDB for AS/400 SQL Programming V4R4 . and after a constraint rule of RESTRICT (where checking is performed immediately). The triggers and rules would occur in the following order: 1. The check for dependent rows is performed at the end of the statement. If an UPDATE against a table with a referential constraint fails. the referential constraint between the PROJECT and DEPARTMENT tables would be broken. but before a NO ACTION rule. An after trigger would be fired after a constraint rule of RESTRICT. but not to a department that does not exist. If a dependent row exists in the relationship. the UPDATE fails. A before trigger fires before the UPDATE is performed and therefore before any checking of constraints. A before trigger would be fired before the UPDATE and before a constraint rule of RESTRICT or NO ACTION. If you are updating a dependent table. The check for dependent rows is performed immediately. For more information on the implications of commitment control and journaling when working with constraints. any non-null foreign key values that you change must match the primary key for each relationship in which the table is a dependent. the UPDATE fails. you cannot update a department number from the department table if it is still responsible for some project. The subtle difference between RESTRICT and NO ACTION rules is easiest seen when looking at the interaction of triggers and referential constraints. Examples of UPDATE Rules For example.PROJECT SET DEPTNO = 'D00' WHERE DEPTNO = 'D01'. If this UPDATE were allowed. The following UPDATE fails because the PROJECT table has rows which are dependent on DEPARTMENT. An after trigger is fired after the UPDATE is performed. see “Journaling” on page 368 and “Commitment Control” on page 369. If a dependent row exists in the relationship. all changes made during the update operation are undone.Specifies that the row in the parent table can be updated if no other row depends on it. Triggers can be defined to fire either before or after an operation (an UPDATE statement. in this case). v DELETE CASCADE Specifies that first the designated rows in the parent table are deleted. but no primary key. Only the dependent rows that are immediate descendents are affected.The statement attempts to change all department numbers of D01 to department number D00. If a dependent row exists in the relationship. DELETE deletes or updates rows according to the delete rules specified. If some other default value was specified on the create of the table. In that case. For example. The check for dependent rows is performed at the end of the statement. The same is true if a table has only foreign keys. the value of MGRNO for each employee who reported to the manager is set to blanks in the department table. If a referential constraint is violated. the DELETE fails. If a dependent row exists in the relationship. Deleting from Tables with Referential Constraints If a table has a primary key but no dependents. that value is used. v DELETE SET DEFAULT Specifies that each column of the foreign key in each dependent row is set to its default value. If no delete rule was defined. 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. you can delete an employee from the employee table even if the employee manages some department. the DELETE fails. For example. If a table has a primary key and dependent tables. All delete rules of all affected relationships must be satisfied in order for the delete operation to succeed. v DELETE SET NULL Specifies that each nullable column of the foreign key in each dependent row is set to its default value. For example. Only the dependent rows that are immediate descendants are affected. Chapter 6. The check for dependent rows is performed immediately. Since D00 is not a value of the primary key DEPTNO in DEPARTMENT. This is due to the REPORTS_TO_EXISTS constraint defined for the department table. DELETE operates as it does without referential constraints. v DELETE RESTRICT Specifies that the row in the parent table can be deleted if no other row depends on it. 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. the statement fails. Then. 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 NO ACTION Specifies that the row in the parent table can be deleted if no other row depends on it. 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. the dependent rows are deleted. the DELETE NO ACTION rule is used. 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. the DELETE fails. Data Integrity 105 . you can delete a department by deleting its row in the department table. The triggers and rules would occur in the following order: 1. Example of DELETE Cascade Rule Deleting a department from the department table sets WORKDEPT (in the employee table) to null for every employee assigned to that department. 2. DB2 UDB for AS/400 Sample Tables. but before a NO ACTION rule. It does not include those rows deleted according to the CASCADE rule. DEPTNO A00 B01 C01 D01 D11 D21 E01 E21 DEPTNAME SPIFFY COMPUTER SERVICE DIV. Contents of the table after the DELETE statement is complete. An after trigger is fired after the DELETE is performed. the number of rows deleted is returned in SQLERRD(3) in the SQLCA. PLANNING INFORMATION CENTER DEVELOPMENT CENTER MANUFACTURING SYSTEMS ADMINISTRATION SYSTEMS SUPPORT SERVICES SOFTWARE SUPPORT MGRNO 000010 000020 000030 ? 000060 000070 000050 000100 ADMRDEPT A00 A00 A00 A00 D01 D01 A00 E01 Note that there were no cascaded deletes in the DEPARTMENT table because no department reported to department ’E11’. This number includes only the number of rows deleted in the table specified in the DELETE statement. but before a constraint rule of NO ACTION (where checking is performed at the end of the statement). and after a constraint rule of RESTRICT (where checking is performed immediately). one row is deleted from table DEPARTMENT. 106 DB2 UDB for AS/400 SQL Programming V4R4 . Consider the following DELETE statement: DELETE FROM CORPDATA. The subtle difference between RESTRICT and NO ACTION rules is easiest seen when looking at the interaction of triggers and referential constraints. When running this statement with a program. The results would appear as follows: Table 16. A before trigger fires before the DELETE is performed and therefore before any checking of constraints. in this case). Triggers can be defined to fire either before or after an operation (a DELETE statement.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. A question mark (’?’) in the sample data below reflects the null value.DEPARTMENT WHERE DEPTNO = 'E11' Given the tables and the data as they appear in Appendix A. the entire DELETE fails. An after trigger would be fired after a constraint rule of RESTRICT. SQLERRD(5) in the SQLCA contains the number of rows that were affected by referential constraints in all tables. and table EMPLOYEE is updated to set the value of WORKDEPT to its default wherever the value was ’E11’. A before trigger would be fired before the DELETE and before a constraint rule of RESTRICT or NO ACTION. DEPARTMENT Table. the following restrictions apply: v No input or output operations are allowed on the dependent file. Data Integrity 107 . When this happens. Chapter 6. a violation occurs when potential mismatches exist between parent and foreign keys. Partial contents after the DELETE statement. restrictions are placed on the use of tables involved in the constraint. Table 17. v Only read and insert operations are allowed on the parent file. For referential constraints. Partial EMPLOYEE Table. EMPNO 000230 000240 000250 000260 000270 000280 000290 000300 000310 000320 000330 000340 FIRSTNME MI JAMES J LASTNAME WORKDEPT PHONENO JEFFERSON D21 MARINO SMITH JOHNSON PEREZ D21 D21 D21 D21 2094 3780 0961 8953 9001 0997 4502 2095 3332 9990 2103 5696 HIREDATE 1966-11-21 1979-12-05 1960-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 SALVATORE M DANIEL SYBIL MARIA ETHEL JOHN PHILIP MAUDE RAMLAL WING JASON R S P L R R X F V SCHNEIDER E11 PARKER SMITH SETRIGHT MEHTA LEE GOUNOT E11 E11 E11 E21 E21 E21 Table 18. For referential constraints. where potential violations of the constraint exist. a violation occurs when potential values exist in columns which are limited by the check constraint. the constraint is marked as check pending.Below are snapshots of the affected portion of the EMPLOYEE table before and after the DELETE statement is completed. When the system determines that the constraint may have been violated (such as after a restore operation). Partial EMPLOYEE Table. EMPNO 000230 000240 000250 000260 000270 000280 000290 000300 000310 000320 000330 000340 FIRSTNME MI JAMES J LASTNAME WORKDEPT PHONENO JEFFERSON D21 MARINO SMITH JOHNSON PEREZ D21 D21 D21 D21 2094 3780 0961 8953 9001 0997 4502 2095 3332 9990 2103 5696 HIREDATE 1966-11-21 1979-12-05 1960-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 SALVATORE M DANIEL SYBIL MARIA ETHEL JOHN PHILIP MAUDE RAMLAL WING JASON R S P L R R X F V SCHNEIDER ? PARKER SMITH SETRIGHT MEHTA LEE GOUNOT ? ? ? E21 E21 E21 Check Pending Referential constraints and check constraints can be in a state known as check pending. Partial contents before the DELETE statement. For check constraints. To get a constraint out of check pending. If a row does not conform to the definition of the view.When a check constraint is in check pending. If the view is created without a WITH CHECK OPTION clause. WITH CHECK OPTION on a View WITH CHECK OPTION is an optional clause on the CREATE VIEW statement that specifies the level of checking to be done when inserting or updating data through a view. or both) data for referential constraints or column data for check constraints. This means that the rows could not be selected again using the view. In addition. rows might be inserted or updated through the view that do not conform to the definition of the view. See the DB2 UDB for AS/400 SQL Reference book for additional discussion of WITH CHECK OPTION. you must: 1. For more information on working with tables in check pending. 3. The definition of the view must not include a subquery. see the DB2 UDB for AS/400 Database Programming book. insert and update operations that are performed on the view are not checked for conformance to the view definition. Because the definition of the view is not used. Disable the relationship with the Change Physical File Constraint (CHGPFCST) CL command. Some checking might still occur if the view is directly or indirectly dependent on another view that includes WITH CHECK OPTION. WITH CASCADED CHECK OPTION The WITH CASCADED CHECK OPTION specifies that every row that is inserted or updated through the view must conform to the definition of the view. WITH CHECK OPTION cannot be specified if the view is read-only. You can identify the rows that are in violation of the constraint with the Display Check Pending Constraint (DSPCPCST) CL command. v Inserts and updates are allowed and the constraint is enforced. the following restrictions apply: v Read operations are not allowed on the file. every row that is inserted or updated through the view must conform to the definition of that view. INSERT INTO V1 VALUES (5) 108 DB2 UDB for AS/400 SQL Programming V4R4 . the following INSERT statement is successful even though the value being inserted does not meet the search condition of the view. the search conditions of all dependent views are checked when a row is inserted or updated. 2. Correct the key (foreign. parent. that row cannot be retrieved using the view. consider the following updateable view: CREATE VIEW V1 AS SELECT COL1 FROM T1 WHERE COL1 > 10 Because no WITH CHECK OPTION is specified. Enable the constraint again with the CHGPFCST CL command. If the option is specified. The checking can either be CASCADED or LOCAL. For example. INSERT INTO V3 VALUES (200) WITH LOCAL CHECK OPTION WITH LOCAL CHECK OPTION is identical to WITH CASCADED CHECK OPTION except that you can update a row so that it no longer can be retrieved through the view. INSERT INTO V3 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. INSERT INTO V2 VALUES (5) If we again consider one more view created over V2: CREATE VIEW V3 AS SELECT COL1 FROM V2 WHERE COL1 < 100 The following INSERT is successful again because the search condition on V1 is not checked due to the WITH LOCAL CHECK OPTION on V2. consider the same updateable view used in the previous example: CREATE VIEW V1 AS SELECT COL1 FROM T1 WHERE COL1 > 10 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. For example.Create another view over V1. Data Integrity 109 . specifying the WITH CASCADED CHECK OPTION: CREATE VIEW V2 AS SELECT COL1 FROM V1 WITH CASCADED CHECK OPTION 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) Consider one more view created over V2: CREATE VIEW V3 AS SELECT COL1 FROM V2 WHERE COL1 < 100 The following INSERT statement fails only because V3 is dependent on V2. Chapter 6. This can only happen when the view is directly or indirectly dependent on a view that was defined with no WITH CHECK OPTION clause. and V2 has a WITH CASCADED CHECK OPTION. it does not matter that the statement does not conform to the definition of V3. INSERT INTO V3 VALUES (5) However. and the search conditions of V1 do not need to be checked since V1 does not specify a check option. versus the WITH CASCADED CHECK OPTION in the previous example. the following INSERT statement is successful because it conforms to the definition of V2. Because V3 does not have a WITH CASCADED CHECK OPTION. and must end with ’YZ’. but it doesn’t have to start with the letter A. V3. COL1 must start with ’AB’ and end with ’YZ’. V2. Because V4 has the WITH CASCADED CHECK OPTION specified. every search condition for V4. v If V4 is operated on. and V2 has a check option. This is because V5 does not specify a check option. and V1 must be checked. so its own search condition must not be met. – COL1 must end in the letter Z. v If V2 is operated on. and view V1 does not have a check option specified. 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%' Different search conditions are going to be checked depending on which view is being operated on with an INSERT or UPDATE. V3 does not have a check option specified. v WITH CASCADED CHECK OPTION specifies that the search conditions of all dependent views are checked when a row is inserted or updated. but it does not have to start with the letter A. However. operating on V5 would mean that COL1 must start with ’ABC’ and end with ’YZ’. every search condition for every view on which V4 is dependent must be checked. If V5 were created WITH LOCAL CHECK OPTION. However. v If V5 is operated on. That is. – COL1 must start with ’AB’. the search condition for V2 must be checked since V3 is defined on V2. so its own search condition does not need to be checked. – COL1 must start with ’AB’. v If V3 is operated on. and V4 had a cascaded check option. because V5 is defined on V4. The LOCAL CHECK OPTION adds the additional requirement that the third character must be a ’C’.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. This is because the check option is LOCAL. no conditions are checked because V1 does not have a WITH CHECK OPTION specified. – COL1 must end in the letter Z. but not necessarily ’ABC’. 110 DB2 UDB for AS/400 SQL Programming V4R4 . v If V1 is operated on. It is written in ILE C. In this discussion. or any logical file or view created over the physical file. Once a trigger program is associated with a physical file. Each change operation can call a trigger before or after the change operation occurs. and that it could be an SQL INSERT. UPDATE. or delete high level language statement in an application program. The trigger program can have SQL embedded in it. the program containing the set of trigger actions can be defined in any supported high level language. To use trigger support. Data Integrity 111 .DB2 UDB for AS/400 Trigger Support A trigger is a set of actions that are run automatically when a specified change operation is performed on a specified physical database file. update. In DB2 UDB for AS/400. or DELETE statement. See the DB2 UDB for AS/400 Database Programming book for a full discussion and more examples of trigger usage in DB2 UDB for AS/400. a table is a physical file. UPDATE. There is no SQL statement to associate a physical file with a trigger program. and keeping an audit trail. you must: v Identify the physical file v Identify the kind of operation v Identify the program that performs the desired actions. Chapter 6. a physical file can be associated with a maximum of six triggers v Before delete trigger v v v v Before insert trigger Before update trigger After delete trigger After insert trigger v After update trigger Trigger Sample A sample trigger program follows. or an SQL INSERT. with embedded SQL. validating input data. SQL is only involved in that the trigger program can contain embedded SQL statements. Triggers are useful for tasks such as enforcing business rules. you must create a trigger program and add it to a physical file using the ADDPFTRG CL command. Thus. the system trigger support calls the trigger program when a change operation is initiated against the physical file or table. To add a trigger to a file. or DELETE that causes the trigger to be fired. The change operation can be an insert. _Packed struct { short fstlen . decimal(9. short edclvl.04 percent and insert into */ /* the RAISE table.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. */ /* Used either Packed struct or filler to reach */ /* the byte boundary alignment. char bdate[10].#include "string. char phone[4]. */ /*******************************************************/ _Packed struct rec{ char empn[6]. _Packed struct { short lstlen. char dept[3]. char lstnam[15]. decimal(9. If the employee's commission is */ /* greater than the maximum commission.h" #include "stdio. char fstnam[12]. char *datapt.2) bonus1. char minit[1].2) salary1. */ /*********************************************************************/ Qdb_Trigger_Buffer_t *hstruct. char jobn[8]. } lstname. } oldbuf. newbuf. this trigger program will */ /* increase the employee's salary by 1. Sample Trigger Program (Part 1 of 5) 112 DB2 UDB for AS/400 SQL Programming V4R4 . */ /* */ /* Note : You must ensure that all the numeric fields */ /* are aligned at 4 byte boundary in C. char sex1[1]. } fstname. */ /* */ /* The EMPLOYEE record information is passed from the input parameter*/ /* to this trigger program.h" #include <recio.2) comm1. char hdate[10]. /*******************************************************/ /* Structure of the EMPLOYEE record which is used to */ /* store the old or the new record that is passed to */ /* this trigger program.h> #include <xxcvt.h" #include "stdlib. decimal(9. Figure 3. EXEC SQL INCLUDE SQLCA. Data Integrity 113 . /* new buffer memcpy(&newbuf. datapt = (char *) hstruct.2) new_salary. decimal(9. NULL. /* decimal(9. char **argv) { int i. decimal(9. /****************************************/ /* Make the exception handler active. */ */ Figure 3. /****************************************/ /* Ensure exception handler OK */ /****************************************/ if (fc. /* old buffer memcpy(&oldbuf..2) percentage = 1.2) salary. nbufoff = hstruct ->New_Record_Offset. /* int nul2off.04.MsgNo != CEE0000) { printf("Failed to register exception handler. exit(99). /* int nuloff. /* decimal(9. /* int nbufoff. old buffer offset old null byte map offset new buffer offset new null byte map offset work days during in one year cutoff to qualify for raised salary as percentage effective raise date */ */ */ */ */ */ */ */ /*******************************************************/ /* Start to monitor any exception.2) commission = 2000.main(int argc. /*******************************************************/ /* Move the data from the trigger buffer to the local */ /* structure for reference. /* short work_days = 253. */ /*******************************************************/ hstruct = (Qdb_Trigger_Buffer_t *)argv[1]. &fc)./* struct { char empno[6]. Sample Trigger Program (Part 2 of 5) Chapter 6. char name[30].. hstruct->New_Record_Len). hstruct->Old_Record_Len). int obufoff. */ /****************************************/ CEEHDLR(&hdlr.00.datapt+nbufoff. /* char raise_date[12] = "1982-06-01".\n"). obufoff = hstruct ->Old_Record_Offset. }. */ /*******************************************************/ _FEEDBACK fc. _HDLR_ENTRY hdlr = main_handler. } rpt1.datapt+obufoff. /* All done */ finished: return.empno. } err_exit: exit(1)."2") == 0) EXEC SQL SET TRANSACTION ISOLATION LEVEL READ COMMITTED. else { if(strcmp(hstruct->Commit_Lock_Level. :rpt1.04 percent and insert into the RAISE table. SALARY INTO :rpt1. } } /********************************************************/ /* If the employee's commission is greater than maximum */ /* commission."1") == 0) EXEC SQL SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED. } /* end of main line */ Figure 3."0") == 0) EXEC SQL SET TRANSACTION ISOLATION LEVEL NONE."3") == 0) EXEC SQL SET TRANSACTION ISOLATION LEVEL ALL. else{ if(strcmp(hstruct->Commit_Lock_Level. READ WRITE.EXEC SQL WHENEVER SQLERROR GO TO ERR_EXIT. :rpt1. EXEC SQL INSERT INTO TRGPERF/RAISE VALUES(:rpt1).new_salary = salary * percentage. */ /********************************************************/ if (newbuf. */ /*******************************************************/ if(strcmp(hstruct->Commit_Lock_Level.name.comm1 >= commission) { EXEC SQL SELECT EMPNO. if (sqlca. Sample Trigger Program (Part 3 of 5) 114 DB2 UDB for AS/400 SQL Programming V4R4 .sqlcode == 0) then { rpt1.empn . } goto finished. EMPNAME. then increase the employee's salary */ /* by 1. else if(strcmp(hstruct->Commit_Lock_Level.salary FROM TRGPERF/EMP_ACT WHERE EMP_ACT. /*******************************************************/ /* Set the transaction isolation level to the same as */ /* the application based on the input parameter in the */ /* trigger buffer.EMPNO=:newbuf. */ /****************************************/ char message_id[7] = "TRG9999". char message_key[4]. char message_q[10] = "_C_pep ". int message_len = 30. int pgm_stack_cnt = 1.h> #include <leawi.h> #pragma linkage (QMHSNDPM.. */ /* */ /******************************************************************/ #include <stdio./******************************************************************/ /* INCLUDE NAME : MSGHAND1 */ /* */ /* DESCRIPTION : Message handler to signal an exception to */ /* the application to inform that an */ /* error occured in the trigger program. int. Sample Trigger Program (Part 4 of 5) Chapter 6.h> #include <recio. _FEEDBACK *new) { /****************************************/ /* Initialize variables for call to */ /* QMHSNDPM. /* /* /* /* /* /* /* /* /* /* Figure 3. */ /* */ /* NOTE : This message handler is a user defined routine. OS) void QMHSNDPM(char *. int.. void *. Data Integrity 115 . */ /*********************************************************************/ void main_handler(_FEEDBACK *cond. . _POINTER *token. void *. void *.). char message_type[10] = "*ESCAPE ". char *. _INT4 *rc. char message_data[50] = "Trigger error " . */ /* User must create a message file and */ /* define a message ID to match the */ /* following data. 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. char *.h> #include <stdlib. char message_file[20] = "MSGF LIB1 ". void *. /****************************************/ /* Declare error code structure for */ /* QMHSNDPM. Sample Trigger Program (Part 5 of 5) 116 DB2 UDB for AS/400 SQL Programming V4R4 . */ /****************************************/ QMHSNDPM(message_id. message_type. /****************************************/ /* Send my own *ESCAPE message.message_id). */ /****************************************/ if (error_code. &message_key. &message_file. char message_id[7]. } } Figure 3. */ /****************************************/ *rc = CEE_HDLR_RESUME. &message_data.bytes_available != 0) { printf("Error in QMHOVPM : %s\n". /****************************************/ /* Check that the call to QMHSNDPM */ /* finished correctly. message_len. message_q. } error_code.struct error_code { int bytes_provided. pgm_stack_cnt. &error_code ). int bytes_available. */ /****************************************/ error_code. error_code.bytes_provided = 15. /****************************************/ /* Set the error handler to resume and */ /* mark the last escape message as */ /* handled. That is. 1999 117 . Stored Procedures DB2 SQL for AS/400 stored procedure support provides a way for an SQL application to define and then invoke a procedure through SQL statements. information on passing parameters to the stored procedure. Procedures in SQL provide the same benefits as procedures in a host language. An external procedure can be any supported high level language program (except System/36* programs and procedures) or a REXX procedure. To create an external procedure or an SQL procedure. Creating a Procedure A procedure (often called a stored procedure) is a program that can be called to perform operations that can include both host language statements and SQL statements. | | | | You may define stored procedures by using the CREATE PROCEDURE statement. Stored procedures can be used in both distributed and non-distributed DB2 SQL for AS/400 applications. One of the big advantages in using stored procedures is that for distributed applications. the execution of one CALL statement on the application requester. Or. The procedure does not need to contain SQL statements. The CREATE PROCEDURE statement adds procedure and parameter definitions to the catalog tables SYSROUTINES and SYSPARMS. An SQL procedure is defined entirely in SQL. you can use Operations Navigator.Chapter 7. a common piece of code need only be written and maintained once and can be called from several programs. or client. can perform any amount of work on the application server. These definitions are then accessible by any SQL CALL statement on the system. The following sections describe the SQL statements used to define and invoke the stored procedure. Consider the following example: © Copyright IBM Corp. and can contain SQL statements that include SQL control statements. 1997. and examples of stored procedure usage. Coding stored procedures requires that the user understand the following: v Stored procedure definition through the CREATE PROCEDURE statement v Stored procedure invocation through the CALL statement v Parameter passing conventions v Methods for returning a completion status to the program invoking the procedure. you can use the SQL CREATE PROCEDURE statement. You may define a procedure as either an SQL procedure or an external procedure. but it may contain SQL statements. Defining an External Procedure The CREATE PROCEDURE statement for an external procedure: v Names the procedure v Defines the parameters and their attributes v Gives other information about the procedure which will the system uses when it calls the procedure. EXEC SQL CREATE PROCEDURE P1 (INOUT PARM1 CHAR(10)) EXTERNAL NAME MYLIB. date. the array contains only one element since there is only parameter. In this example. It is important to note that it is not necessary to define a procedure in order to call it.PROC1 LANGUAGE C GENERAL WITH NULLS. The parameter is a character field of length ten. and timestamp parameters). v Indicates that the procedure P1 (program MYLIB. time.2)) 118 DB2 UDB for AS/400 SQL Programming V4R4 . For example. However. if no procedure definition is found. and therefore would like an additional argument passed to the procedure on the CALL statement. v Defines the name of the program which corresponds to the procedure. Parameters can be defined to be type IN. graphic. a NUL-terminator is passed on character. or INOUT. See “Using Embedded CALL Statement Where No Procedure Definition Exists” on page 125 for an example of a CALL statement without a corresponding procedure definition. certain restrictions and assumptions are made when the procedure is invoked on the CALL statement. The parameter type determines when the values for the parameters get passed to and from the procedure. This CREATE PROCEDURE statement: v Names the procedure P1 v Defines one parameter which is used both as an input parameter and an output parameter. which is PROC1 in MYLIB. for ILE C procedures. 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. the NULL indicator argument cannot be passed.PROC1 is the program which is called when the procedure is invoked on a CALL statement. either from a prior CREATE PROCEDURE or from a DECLARE PROCEDURE in this program. The language is important since it impacts the types of parameters that can be passed. This indicates that the parameter for the procedure can possibly contain the NULL value. Consider the following simple example that takes as input an employee number and a rate and updates the employee’s salary: EXEC SQL CREATE PROCEDURE UPDATE_SALARY_1 (IN EMPLOYEE_NUMBER CHAR(10).PROC1) is written in C. OUT. Defining an SQL Procedure The CREATE PROCEDURE statement for SQL procedures: v Names the procedure v Defines the parameters and their attributes v Provides other information about the procedure which will be used when the procedure is called v Defines the procedure body. The procedure body is the executable part of the procedure and is a single SQL statement. v Defines the CALL type to be GENERAL WITH NULLS. MYLIB. It also affects how the parameters are passed to the procedure (for example. IN RATE DECIMAL(6. v Defines parameter EMPLOYEE_NUMBER which is an input parameter and is a character data type of length 6 and parameter RATE which is an input parameter and is a decimal data type. BONUS = 500 WHERE EMPNO = EMPLOYEE_NUMBER.EMPLOYEE SET SALARY = SALARY * RATE WHERE EMPNO = EMPLOYEE_NUMBER. END CASE. Stored Procedures 119 . This CREATE PROCEDURE statement: v Names the procedure UPDATE_SALARY_1.LANGUAGE SQL MODIFIES SQL DATA UPDATE CORPDATA.05. IN RATING INT) LANGUAGE SQL MODIFIES SQL DATA CASE RATING WHEN 1 THEN UPDATE CORPDATA. logic can be added to the SQL procedure using SQL control statements. Chapter 7. WHEN 2 THEN UPDATE CORPDATA. Instead of a single UPDATE statement. BONUS = 1000 WHERE EMPNO = EMPLOYEE_NUMBER.03 BONUS = 0 WHERE EMPNO = EMPLOYEE_NUMBER.10. This CREATE PROCEDURE statement: v Names the procedure UPDATE_SALARY_2. SQL control statements consist of the following: v an assignment statement v a CALL statement v v v v v a CASE statement a compound statement a FOR statement an IF statement a LOOP statement v a REPEAT statement v a WHILE statement | | | | | | | | | | | | | | | | | | | | | | | | | The following example takes as input the employee number and a rating that was received on the last evaluation. When the procedure is called. 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).EMPLOYEE SET SALARY = SALARY * 1. v Indicates the procedure is an SQL procedure that modifies SQL data. ELSE UPDATE CORPDATA. v Defines the procedure body as a single UPDATE statement. the UPDATE statement is executed using the values passed for EMPLOYEE_NUMBER and RATE.EMPLOYEE SET SALARY = SALARY * 1.EMPLOYEE SET SALARY = SALARY * 1. and handlers can be declared. and parameter DEPT_BONUS_CNT which is an output parameter and is an integer data type. CLOSE C1. DECLARE EXIT HANDLER FOR SQLEXCEPTION SET DEPT_SALARY = NULL. DECLARE EMPLOYEE_BONUS DECIMAL(9. BONUS FROM CORPDATA. OUT DEPT_SALARY DECIMAL(15. EMPLOYEE_BONUS. IF EMPLOYEE_BONUS > 0 THEN SET BONUS_CNT = BONUS_CNT + 1. SQL variables. SET DEPT_SALARY = TOTAL_SALARY.2). END WHILE. cursors. input parameter RATING is checked and the appropriate update statement is executed. OPEN C1. DECLARE BONUS_CNT INT DEFAULT 0. The following example takes as input the department number. EXEC SQL CREATE PROCEDURE RETURN_DEPT_SALARY (IN DEPT_NUMBER CHAR(3). WHILE END_TABLE = 0 DO SET TOTAL_SALARY = TOTAL_SALARY + EMPLOYEE_SALARY + EMPLOYEE_BONUS. FETCH C1 INTO EMPLOYEE_SALARY. In addition. v Defines parameter DEPT_NUMBER which is an input parameter and is a character data type of length 3. END IF. DECLARE CONTINUE HANDLER FOR NOT FOUND SET END_TABLE = 1. DECLARE END_TABLE INT DEFAULT 0. END P1. v Indicates the procedure is an SQL procedure that modifies SQL data. Multiple statements can be added to a procedure body by adding a compound statement.2).EMPLOYEE WHERE WORKDEPT = DEPT_NUMBER. Within a compound statement. FETCH C1 INTO EMPLOYEE_SALARY. When the procedure is called.v Defines parameter EMPLOYEE_NUMBER which is an input parameter and is a character data type of length 6 and parameter RATING which is an input parameter and is an integer data type. v Defines the procedure body. v Indicates the procedure is an SQL procedure that reads SQL data v Defines the procedure body. – Declares SQL variables EMPLOYEE_SALARY and TOTAL_SALARY as decimal fields. This CREATE PROCEDURE statement: v Names the procedure RETURN_DEPT_SALARY. EMPLOYEE_BONUS.2). parameter DEPT_SALARY which is an output parameter and is a decimal data type. OUT DEPT_BONUS_CNT INT) LANGUAGE SQL READS SQL DATA P1: BEGIN DECLARE EMPLOYEE_SALARY DECIMAL(9. 120 DB2 UDB for AS/400 SQL Programming V4R4 . It returns the total salary of all the employees in that department and the number of employees in that department who get a bonus. – Declares SQL variables BONUS_CNT and END_TABLE which are integers and are initialized to 0. DECLARE C1 CURSOR FOR SELECT SALARY. any number of SQL statements can be specified. DECLARE TOTAL_SALARY DECIMAL(15. SET DEPT_BONUS_CNT = BONUS_CNT.2). MIDINIT.EMPLOYEE_BONUS. DECLARE UNDO HANDLER FOR SQLEXCEPTION SET CNT = NULL. For each row retrieved. If the handler for SQLEXCEPTION is not specified and an error occurs that is not handled in another handler.– Declares cursor C1 that selects the columns from the employee table. It ensures the EMPLOYEE_BONUS table exists. Since indicators are always passed to SQL procedures. Compound statements can be made atomic so if an error occurs that is not expected. the TOTAL_SALARY is incremented and. SQLCODE and SQLSTATE are reinitialized to 0. the transaction is committed. BONUS FROM CORPDATA. DECLARE CONTINUE HANDLER FOR 23505 SET CNT = CNT + 1. The following example takes as input the department number. and inserts the name of all employees in the department who get a bonus. when invoked sets variable END_TABLE to 1. DEPT_SALARY is set to NULL and the processing of the compound statement is terminated. the SQLSTATE class is not ’00’. – Returns DEPT_SALARY and DEPT_BONUS_CNT as output parameters. ’01’ or ’02’. EXEC SQL CREATE PROCEDURE CREATE_BONUS_TABLE (IN DEPT_NUMBER CHAR(3). This handler is invoked when the FETCH has no more rows to return. – Includes a WHILE statement which loops until the last record is fetched. – Declares an exit handler for SQLEXCEPTION. IF DEPT_NUMBER IS NOT NULL THEN CREATE TABLE DATALIB.2)) PRIMARY KEY (FULLNAME). IF BONUS > 0 THEN Chapter 7. This handler is invoked if any errors occur.EMPLOYEE_BONUS (FULLNAME VARCHAR(30). If this handler is invoked. the indicator value for DEPT_SALARY is −1 when the procedure returns. 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. Similar to indicators. If invoked. Stored Procedures 121 . FETCH. INOUT CNT INT) LANGUAGE SQL MODIFIES SQL DATA CS1: BEGIN ATOMIC DECLARE NAME VARCHAR(30) DEFAULT NULL.EMPLOYEE WHERE WORKDEPT = CREATE_BONUS_TABLE. SQLCODE and SQLSTATE are reinitialized to 0. the SQLCA is always returned from SQL procedures. – Declares a continue handler for NOT FOUND. the statements within the atomic statement are rolled back. LASTNAME. ie. – Includes an OPEN. FOR_1:FOR V1 AS C1 CURSOR FOR SELECT FIRSTNME. The procedure returns the total count of all employees who get a bonus. which. the transaction must be at a commit boundary. BONUS DECIMAL(10. if the employee’s bonus is more than 0. When a procedure that contains an atomic compound statement is called. When the handler is invoked. If the compound statement is successful.DEPT_NUMBER. execution of the compound statement is terminated and the error is returned in the SQLCA. the BONUS_CNT is incremented. DECLARE CONTINUE HANDLER FOR 42710 SELECT COUNT(*) INTO CNT FROM DATALIB. and CLOSE of cursor C1. Processing continues on the SET statement following the INSERT statement.BONUS refers to the SQL variable that contains the value of column BONUS for each row selected. the table specified in the FOR statement must exist when the procedure is created. If the procedure attempts to insert a name that already exists in the table.DEPT_NUMBER is the DEPT_NUMBER parameter for the procedure CREATE_BONUS_TABLE. MIDINIT. since there is no statement following the compound statement. v Indicates the procedure is an SQL procedure that modifies SQL data v Defines the procedure body. FOR_1. – Declares a continue handler for SQLSTATE 42710. The following example creates a table that contains all employees in a specific department. END FOR FOR_1. – Declares a continue handler for SQLSTATE 23505. – Uses the FOR statement to declare cursor C1 to read the records from the EMPLOYEE table. In this case. and LASTNAME are concatenated together with a blank in between and the result is put in SQL variable NAME. duplicate key. You can also use dynamic SQL in an SQL procedure. CNT is set to 0. Within the FOR statement. In the example. Because the data type of the select list items must be known when the procedure is created. data from columns FIRSTNME. table already exists. – Declares SQL variable NAME as varying character. If unqualified SQL variable names are used in SQL statements where column names are also allowed. FOR_1. CS1. For each row. 122 DB2 UDB for AS/400 SQL Programming V4R4 . – Declares an UNDO handler for SQLEXCEPTION. the column names from the select list are used as SQL variables that contain the data from the row fetched. If the EMPLOYEE_BONUS table already exists. v Defines parameter DEPT_NUMBER which is an input parameter and is a character data type of length 3 and parameter CNT which is an input/output parameter and is an integer data type. This CREATE PROCEDURE statement: v Names the procedure CREATE_BONUS_TABLE. the name will be used to refer to the column. the procedure returns. The department number is passed as input to the procedure and is concatenated to the table name.EMPLOYEE_BONUS VALUES(CS1. and processing continues after the compound statement. the handler is invoked and decrements CNT. The SQLCODE and SQLSTATE are reset to 0 and processing continues with the FOR statement. If invoked.SET NAME = FIRSTNME || ' ' || MIDINIT || ' '||LASTNAME. END IF. the handler is invoked and retrieves the number of records in the table.BONUS).NAME is the variable NAME defined in the compound statement with the beginning label CS1. CREATE_BONUS_TABLE. the previous statements are rolled back. SET CNT = CNT + 1. END CS1.NAME. SQL variables NAME and BONUS are inserted into the EMPLOYEE_BONUS table. An SQL variable name can be qualified with the label name of the FOR statement or compound statement in which it is defined. END IF. Parameter names can also be qualified with the procedure name. and the variable name is the same as a column name. INSERT INTO DATALIB. – Sets variable STMT to the CREATE statement. SET STMT = 'INSERT INTO ' ³³ TABLE_NAME ³³ 'SELECT EMPNO. – Sets variable STMT to the INSERT statement. Chapter 7. With the handler. – Declares SQL variable STMT and an SQL variable TABLE_NAME as character. SALARY DECIMAL(9. PREPARE S2 FROM STMT. FIRSTNME VARCHAR(6) NOT NULL. and prepares and executes the statement. Stored Procedures 123 . v Defines the procedure body. If the procedure is called passing value ’D21’ for the department. PREPARE S3 FROM STMT. and prepares and executes the statement. DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET MESSAGE = 'ok'. v Indicates the procedure is an SQL procedure. DECLARE MESSAGE CHAR(20). If the table does not exist. FIRSTNME. – Sets variable STMT to the DROP statement. SET STMT = 'CREATE TABLE ' ³³ TABLE_NAME ³³ '( EMPNO CHAR(6) NOT NULL.2))'. When the statement is executed. A parameter marker is specified in the where clause. – Declares a CONTINUE handler. EXECUTE S3 USING P_DEPT. DECLARE TABLE_NAME CHAR(30). SET TABLE_NAME = 'DEPT_' ³³ P_DEPT ³³ '_T'. the variable P_DEPT is passed on the USING clause. EXECUTE S2. MIDINIT CHAR(1) NOT NULL. MIDINIT. This CREATE PROCEDURE statement: v Names the procedure CREATE_DEPT_TABLE v Defines parameter P_DEPT which is an input parameter and is a character data type of length 3. table DEPT_D21_T is created and the table is initialized with all the employees that are in department ’D21’. EXECUTE S1.CREATE PROCEDURE CREATE_DEPT_TABLE (IN P_DEPT CHAR(3)) LANGUAGE SQL BEGIN DECLARE STMT CHAR(1000). PREPARE S1 FROM STMT. The procedure attempts to DROP the table in case it already exists. and prepares and executes the statement. SET STMT = 'DROP TABLE ' ³³ TABLE_NAME. processing will continue. END. – Sets variable TABLE_NAME to ’DEPT_’ followed by the characters passed in parameter P_DEPT. followed by ’_T’. the first EXECUTE would fail. LASTNAME CHAR(15) NOT NULL. SALARY FROM EMPLOYEE WHERE WORKDEPT = ?'. LASTNAME. it is one short integer since there is only one parameter in the CREATE PROCEDURE statement. the first argument is a C NUL-terminated string eleven characters long containing the contents of host variable HV1. There are three types of CALL statements which need to be addressed since DB2 SQL for AS/400 has different rules for each type. 124 DB2 UDB for AS/400 SQL Programming V4R4 .PROC1 before returning to the user program. DCL IND1 FIXED BIN(15). : EXEC SQL CALL P1 (:HV1 :IND1). Programs created by SQL procedures can only be called by invoking the procedure name specified on the CREATE PROCEDURE statement. On the CALL statement. They are: v Embedded or dynamic CALL statement where a procedure definition exists v Embedded CALL statement where no procedure definition exists v Dynamic CALL statement where no CREATE PROCEDURE exists Note: Dynamic here refers to: v A dynamically prepared and executed CALL statement v A CALL statement issued in an interactive environment (for example. Note that on a call to an ILE C procedure. graphic.Invoking a Stored Procedure The CALL statement invokes a stored procedure. The following PL/I example shows a CALL statement which corresponds to the CREATE PROCEDURE statement shown. special registers. Arguments may be constants. through STRSQL or Query Manager) v A CALL statement executed in an EXECUTE IMMEDIATE statement. DB2 SQL for AS/400 adds one character to the parameter declaration if the parameter is declared to be a character. or timestamp variable. Following is a discussion of each type. a call to program MYLIB/PROC1 is made and two arguments are passed. or host variables. In this case. Since the first parameter is declared as INOUT. SQL updates the host variable HV1 and the indicator variable IND1 with the values returned from MYLIB. DCL HV1 CHAR(10). Since the language of the program is ILE C.PROC1 LANGUAGE C GENERAL WITH NULLS. The second argument is the indicator array. date. time. Using CALL Statement Where Procedure Definition Exists This type of CALL statement gets all the information about the procedure and the argument attributes from the CREATE PROCEDURE catalog definition. This argument contains the contents of indicator variable IND1 on entry to the procedure. : EXEC SQL CREATE P1 PROCEDURE (INOUT PARM1 CHAR(10)) EXTERNAL NAME MYLIB. : When this CALL statement is invoked. the name of the stored procedure and any arguments are specified. The external stored procedure specified in the CALL statement does not need to have a corresponding CREATE PROCEDURE statement. no additional argument is passed to the program for indicator variables. the first of type SHORT INT and the second of type CHAR with a length of 4. the naming convention. Note: If an indicator variable is specified on the CALL statement and its value is less than zero when the CALL statement is executed. Assume that the stored procedure is expecting 2 parameters. assume that the naming option of *SYS (system naming) is used and that a DFTRDBCOL parameter was not specified on the CRTSQLPLI command. Chapter 7. Example of Embedded CALL Statement Where No Procedure Definition Exists The following is a PL/I example of an embedded CALL statement where no procedure definition exists: DCL HV2 CHAR(10). the library list is searched for a program named P2. Since the call type is GENERAL.Note: The procedure names specified on the CREATE PROCEDURE and CALL statements must match EXACTLY in order for the link between the two to be made during the SQL precompile of the program. if necessary. an error results because there is no way to pass the indicator to the procedure. and. 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. as illustrated in the following C example. Assuming program P2 is found in the library list. Stored Procedures 125 . v The CALL type is GENERAL (no indicator argument is passed). the DECLARE PROCEDURE statement will be used. : When the CALL statement is invoked. : EXEC SQL CALL P2 (:HV2). Using Embedded CALL Statement Where No Procedure Definition Exists A static CALL statement without a corresponding CREATE PROCEDURE statement is processed with the following rules: v All host variable arguments are treated as INOUT type parameters. an SQLDA may be passed rather than a parameter list. For the above example. Using Embedded CALL Statement With an SQLDA In either type of embedded CALL (where a procedure definition may or may not exist). Note: For an embedded CALL statement where both a CREATE PROCEDURE and a DECLARE PROCEDURE statement exist. In this case. v The language of the program to call is determined based on information retrieved from the system about the program. DB2 SQL for AS/400 attempts to find the program based on standard SQL naming conventions. v The program to call is determined based on the procedure name specified on the CALL. dap->sqlvar[1].P3 is expecting parameters.sqldata = (char*) &col1. dap->sqld = SQLDA_HV_ENTRIES.. then either a parameter list or an SQLDA passed with the USING DESCRIPTOR clause may be used. as shown in the previous example. main() { char proc_name[15].#define SQLDA_HV_ENTRIES 2 #define SHORTINT 500 #define NUL_TERM_CHAR 460 exec sql include sqlca.sqllen = 2.. . dap->sqlvar[0].. For example: . int bc. The procedure name cannot be specified as a parameter marker. typedef struct sqlda* Sqldap. strcpy(col2. } 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.P3").. /* bc set in the malloc statement above */ dap->sqln = SQLDA_HV_ENTRIES. . /* SQLDASIZE is a macro defined in the sqlda include */ col1 = 431.8)."SQLDA ". dap->sqlvar[0]..sqldata = col2. dap->sqlvar[0]... exec sql include sqlda.. } In the above example.. dap->sqlvar[1]..sqltype = SHORTINT. instead of the hard-coded procedure name.sqltype = NUL_TERM_CHAR. dap->sqlvar[0]. dap = (Sqldap) malloc(bc=SQLDASIZE(SQLDA_HV_ENTRIES))... .. dap->sqldabc = bc. More examples for calling stored procedures may be found later in this chapter and also in the DATABASE 2 Advanced Database Functions book.. typedef struct sqlda Sqlda. char col2[4]. . strncpy(dap->sqldaid. "MYLIB. .sqlname. short col1. EXEC SQL CALL P1 USING DESCRIPTOR :*dap. 126 DB2 UDB for AS/400 SQL Programming V4R4 . When a host variable containing the procedure name is used in the CALL statement and a CREATE PROCEDURE catalog definition exists. if MYLIB. strcpy (proc_name. dap->sqlvar[1].. it will be used....length = 0. main() { Sqldap dap. . .. EXEC SQL CALL :proc_name ."abc").sqllen = 4. as in the previous example. v The language of the program to call is determined based on information retrieved from the system about the program.P3 expected an argument of only 5 characters.2). EXEC SQL EXECUTE IMMEDIATE :string.45 is passed as a packed decimal(5. the length of the expected argument in the program must be kept in mind. it is always safer to use host variables on the CALL statement so that the attributes of the procedure can be matched exactly and so that characters are not lost. : This example shows a dynamic CALL statement executed through an EXECUTE IMMEDIATE statement.01 is also passed with a precision and scale of 5 and 2. v All floating point constants are passed as double-precision floating point. Note: For this reason. v The CALL type is GENERAL (no indicator argument is passed). For numeric constants passed on a CALL statement.string[100].P3 ('P3 TEST')"). v The program to call is determined based on the procedure name specified on the CALL and the naming convention. Precision and scale are determined based on the constant value. v CURRENT TIME Passed as an 8-byte character string in ISO format. Example of Dynamic CALL Statement Where No CREATE PROCEDURE Exists The following is a C example of a dynamic CALL statement: char hv3[10]. a value of 001. Stored Procedures 127 . a value of 123. If program MYLIB. v All decimal constants are passed as packed decimal values. the last 2 characters of the constant specified in the example would be lost to the program.P3 with one parameter passed as a character variable containing ’P3 TEST’. Special registers specified on a dynamic CALL statement are passed as follows: v CURRENT DATE Passed as a 10-byte character string in ISO format. host variables can be specified for CALL statement arguments if the PREPARE and EXECUTE statements are used to process it. : strcpy(string.Using Dynamic CALL Statement Where No CREATE PROCEDURE Exists The following rules pertain to the processing of a dynamic CALL statement when there is no CREATE PROCEDURE definition: v All arguments are treated as IN type parameters. For dynamic SQL. respectively. The call is made to program MYLIB. For instance. When executing a CALL statement and passing a constant."CALL MYLIB. Likewise. the following rules apply: v All integer constants are passed as fullword binary integers. v CURRENT TIMESTAMP Passed as a 26-byte character string in IBM SQL format. Chapter 7. v CURRENT PATH Passed as a 558-byte varying character length character string. v CURRENT SERVER Passed as an 18-byte varying length character string.v CURRENT TIMEZONE Passed as a packed decimal number with a precision of 6 and a scale of 0. PIC S9(p-s)V9(s) DISPLAY SIGN LEADING SEPARATE Note: Precision must not be greater than 18. | Parameter Passing Conventions for Stored Procedures The CALL statement can pass arguments to programs written in all supported host languages and REXX procedures. Other columns in that row contain an indication of whether that data type is supported as a parameter type for a particular language. NUMERIC(p. the data type is not supported as a parameter type for that language. When calling an SQL procedure. Table 19. [n+1] char .. v USER Passed as an 18-byte varying length character string. The declaration indicates how host variables must be declared to be received and set properly by the procedure. [n+1] TYPE(*CHAR) LEN(n) - VARCHAR(n) FOR BIT DATA VARCHAR structured form (see C chapter) - 128 DB2 UDB for AS/400 SQL Programming V4R4 .s) CL TYPE(*DEC) LEN(p s) COBOL for AS/400 and ILE COBOL for AS/400 PIC S9(4) BINARY PIC S9(9) BINARY PIC S9(p-s)V9(s) PACKED-DECIMAL Note: Precision must not be greater than 18. COMP-2 Note: Only supported for ILE COBOL for AS/400. A host variable declaration indicates that DB2 SQL for AS/400 supports this data type as a parameter in this language. all SQL data types are supported so no column is provided in the table. The SQL data type is contained in the leftmost column of the following table. Each language supports different data types which are tailored to it. PIC X(n) Varying-Length Character String (see COBOL chapter) Note: Only supported for ILE COBOL for AS/400.. COMP-1 Note: Only supported for ILE COBOL for AS/400..s) C and C++ short long decimal(p. Data Types of Parameters SQL Data Type SMALLINT INTEGER DECIMAL(p.. Varying-Length Character String (see COBOL chapter) Note: Only supported for ILE COBOL for AS/400. If the column contains a dash (-).s) - - REAL or FLOAT(p) float - DOUBLE PRECISION or FLOAT or FLOAT(p) CHARACTER(n) VARCHAR(n) double - char . . [27] TYPE(*CHAR) LEN(26) Indicator Variable short CLOB structured form (see C chapter) - | | | | | | | | | | | | CLOB BLOB BLOB structured form (see C chapter) - DBCLOB DBCLOB structured form (see C chapter) - Table 20. Data Types of Parameters (continued) SQL Data Type GRAPHIC(n) C and C++ wchar_t . [n+1] CL COBOL for AS/400 and ILE COBOL for AS/400 PIC G(n) DISPLAY-1 or PIC N(n) Note: Only supported for ILE COBOL for AS/400. Varying-Length Graphic String (see COBOL chapter) Note: Only supported for ILE COBOL for AS/400. PIC X(10) For ILE COBOL for AS/400 only. then an E. BLOB string (see COBOL chapter). FORMAT TIME. PIC S9(4) BINARY CLOB string (see COBOL chapter).Table 19. PIC X(8) For ILE COBOL for AS/400 only.. DBCLOB string (see COBOL chapter). (then an optional sign).s) - FIXED DEC(p. PIC X(26) For ILE COBOL for AS/400 only. [9] TYPE(*CHAR) LEN(8) TIMESTAMP char .. (then an optional sign).s) NUMERIC(p..s) REAL or FLOAT(p) REAL*4 FLOAT BIN(p) DOUBLE PRECISION or FLOAT or FLOAT(p) CHARACTER(n) REAL*8 FLOAT BIN(p) CHARACTER*n CHAR(n) 129 . FORMAT DATE. FORMAT TIMESTAMP. numeric string with a decimal (and an optional leading sign) string with digits. [11] TYPE(*CHAR) LEN(10) TIME char . Note: only supported for ILE COBOL for AS/400. then digits string with digits. VARGRAPHIC(n) VARGRAPHIC structured form (see C chapter) - DATE char . Data Types of Parameters SQL Data Type SMALLINT INTEGER FORTRAN INTEGER*2 INTEGER*4 PL/I FIXED BIN(15) FIXED BIN(31) REXX numeric string with no decimal (and an optional leading sign).... then an E.. then digits string with n characters within two apostrophes Chapter 7. Note: only supported for ILE COBOL for AS/400. Stored Procedures DECIMAL(p. Note: only supported for ILE COBOL for AS/400. Data specification. INTEGER DECIMAL(p. Data Types of Parameters (continued) SQL Data Type VARCHAR(n) VARCHAR(n) FOR BIT DATA GRAPHIC(n) FORTRAN PL/I CHAR(n) VAR CHAR(n) VAR REXX string with n characters within two apostrophes string with n characters within two apostrophes string starting with G’. ILE RPG Data specification. B in position 43. length must be 4. F in position 40. P in position 43 and 0 through 9 through 31 in positions 41-42 of the in position 52 of the sub-field specification.s) REAL or FLOAT(p) DOUBLE PRECISION or FLOAT or FLOAT(p) 130 DB2 UDB for AS/400 SQL Programming V4R4 . and 00 in positions 41-42 of the sub-field specification. Blank in position 43 and 0 through 9 in position 52 of the sub-field specification. Data Types of Parameters SQL Data Type SMALLINT RPG Data structure that contains a single sub-field. Data specification. and 0 in position 52 of the sub-field specification. F in position 40. then ’ string starting with G’. Data specification. length must be <=09 and >=05. length must be 4. sub-field specification. then n double byte characters. P in position 40 and 00 Data structure that contains a single sub-field. S in position 40. length must be 2. B in position 40. length must be <= 4. - VARGRAPHIC(n) - - DATE TIME TIMESTAMP Indicator Variable CHARACTER*10 CHARACTER*8 CHARACTER*26 INTEGER*2 CHAR(10) CHAR(8) CHAR(26) FIXED BIN(15) | | | | | | CLOB BLOB DBCLOB - CLOB structured form (see PL/I chapter) BLOB structured form (see PL/I chapter) DBCLOB structured form (see PL/I chapter) Table 21. NUMERIC(p. and 0 in position 52 of the sub-field specification. length must be 8. then n double byte characters. Data structure that contains a single sub-field. and 00 in positions 41-42 of the sub-field specification. or A numeric input field or calculation result field. Data specification. B in position 43. Data structure that contains a single sub-field. or Blank in position 40 and 00 through 31 in position 41-42 of the sub-field specification. then ’ string with 10 characters within two apostrophes string with 8 characters within two apostrophes string with 26 characters within two apostrophes numeric string with no decimal (and an optional leading sign). B in position 40.Table 20.s) Data specification. Length is 10. length must be 2. Data Types of Parameters (continued) SQL Data Type CHARACTER(n) RPG Data structure field without sub-fields or data structure that contains a single sub-field. Blank in position 43 and 52 of the sub-field specification. and 0 in position 52 of the sub-field specification. TIME Data specification. G in position 40 of the sub-field specification. or A character input field or calculation result field. sub-field. or A character input field or calculation result field. TIMFMT(*ISO) in data structure that contains a single position 44-80. Data specification. A in position 40. Blank in position 43 and 52 of the sub-field specification. TIMESTAMP Indicator Variable Data specification. Data specification. VARCHAR(n) FOR BIT DATA - GRAPHIC(n) VARGRAPHIC(n) - DATE Data structure field without sub-fields or data structure that contains a single sub-field. T in position 40 of the Data structure field without sub-fields or sub-field specification. or Blank in position 40 and 41-42 of the sub-field specification and the keyword VARYING in positions 44-80. Stored Procedures 131 . Data specification. Blank in position 43 and 52 of the sub-field specification. ILE RPG Data specification. Data specification. Data structure that contains a single sub-field. G in position 40 of the sub-field specification and the keyword VARYING in positions 44-80. or Blank in position 40 and 41-42 of the sub-field specification and the keyword VARYING in positions 44-80. B in position 43. Z in position 40 of the sub-field specification. B in position 40.Table 21. and 00 in positions 41-42 of the sub-field specification. Length is 8. or Blank in position 40 and 41-42 of the sub-field specification. CLOB structured form (see RPG chapter) BLOB structured form (see RPG chapter) DBCLOB structured form (see RPG chapter) | | | | CLOB BLOB DBCLOB Chapter 7. A in position 40. Data specification. Data structure field without sub-fields or data structure that contains a single sub-field. A in position 40. or A character input field or calculation result field. or A character input field or calculation result field. Blank in position 43 and 52 of the sub-field specification. length must be <=4. Length is 26. DATFMT(*ISO) in position 44-80. D in position 40 of the sub-field specification. VARCHAR(n) Data specification. INOUT DECOUT2 DECIMAL(7. A CALL statement with indicator variables is processed as follows: v If the indicator variable is negative. is set to a negative value. the correct method of coding their handling is to check the value of the indicator variable first before using the associated host variable. provided host variables are used for the parameters. In this case. which is a two-byte integer. Notice that the logic checks the value of the indicator variable before using the associated variable.2)) EXTERNAL NAME LIB1. to pass additional information to and from the procedure. the host variable and the indicator variable are passed unchanged. To indicate that an associated host variable contains the null value. The following example illustrates the handling of indicator variables in CALL statements. and this is their primary use.Indicator Variables and Stored Procedures Indicator variables can be used with the CALL statement.2). A default value is passed for the associated host variable on the CALL and the indicator variable is passed unchanged. Also note the method that the indicator variables are passed into procedure PROC1 (as a third argument consisting of an array of two-byte values).PROC1 LANGUAGE RPGLE GENERAL WITH NULLS) 132 DB2 UDB for AS/400 SQL Programming V4R4 . Assume a procedure was defined as follows: CREATE PROCEDURE PROC1 (INOUT DECIMALOUT DECIMAL(7. Indicator variables are the SQL standard means of denoting that the associated host variable should be interpreted as containing the null value. Note that these rules of processing are the same for input parameters to the procedure as well as output parameters returned from the procedure. this denotes the null value. this denotes that the host variable contains a non-null value. v If the indicator variable is not negative. When indicator variables are used with stored procedures. the indicator variable. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 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 . Handling of Indicator Variables in CALL Statements (Part 1 of 2) Chapter 7. :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 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Figure 4. Stored Procedures 133 . The calling program that invokes the procedure is QSQCALL.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 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. Handling of Indicator Variables in CALL Statements (Part 2 of 2) Returning a Completion Status to the Calling Program One method of returning a status to the SQL program issuing the CALL statement is to code an extra INOUT type parameter and set it prior to returning from the procedure. C EVAL NULLARRAY(1) = -5 C RETURN ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ End of PROGRAM PROC1 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Figure 4. THERE IS NO POINT C* IN SETTING THE VALUE IN INOUTP SINCE IT WON'T BE C* PASSED BACK TO THE CALLER. this is not always possible.5 C EVAL NULLARRAY(2) = 0 C* C* INDICATE THAT THE SECOND PARAMETER IS TO CONTAIN C* THE NULL VALUE UPON RETURN. QSQCALL turns the error into SQLCODE/SQLSTATE -443/38501. When the message is signalled. When the procedure being called is an existing program. Refer to the respective language reference to determine the proper way to signal a message. 134 DB2 UDB for AS/400 SQL Programming V4R4 . Each language has methods for signalling conditions and sending messages. Another method of returning a status to the SQL program issuing the CALL statement is to send an escape message to the calling program (operating system program QSQCALL) which invokes the procedure. 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. INOUT PARM6 DECIMAL(10. INOUT PARM2 INTEGER. Procedure P2 is written in PL/I and also has 10 parameters. INOUT PARM8 DATE.CALLPROC2 LANGUAGE C GENERAL WITH NULLS EXEC SQL CREATE PROCEDURE P2 (INOUT PARM1 CHAR(10).Examples These examples show how the arguments of the CALL statement are passed to the procedure for several languages. INOUT PARM10 TIMESTAMP) EXTERNAL NAME TEST12. INOUT PARM5 FLOAT(53). The first example shows the calling ILE C program that uses the CREATE PROCEDURE definitions to call the P1 and P2 procedures. Assume two procedures are defined as follows: EXEC SQL CREATE PROCEDURE P1 (INOUT PARM1 CHAR(10). INOUT PARM4 FLOAT(22). INOUT PARM6 DECIMAL(10. They also show how to receive the arguments into local variables in the procedure. INOUT PARM8 DATE. INOUT PARM3 SMALLINT. INOUT PARM10 TIMESTAMP) EXTERNAL NAME TEST12. Procedure P1 is written in C and has 10 parameters. INOUT PARM9 TIME. INOUT PARM7 VARCHAR(10). INOUT PARM7 VARCHAR(10). INOUT PARM4 FLOAT(22). INOUT PARM9 TIME. Stored Procedures 135 .5). INOUT PARM5 FLOAT(53).CALLPROC LANGUAGE PLI GENERAL WITH NULLS Chapter 7.5). INOUT PARM2 INTEGER. INOUT PARM3 SMALLINT. float PARM4. /* FOR DATE */ char PARM9[8].Example 1. double PARM5. } PARM7. char PARM1[10]. decimal(10.5) PARM6.h> main() { EXEC SQL INCLUDE SQLCA. ILE C and PL/I Procedures Called From ILE C Applications /**************************************************************/ /*********** START OF SQL C Application ***********************/ #include <stdio. /* FOR TIMESTAMP */ Figure 5.h> #include <decimal. char PARM8[10]. struct { signed short int parm7l.h> #include <string. signed short int PARM3. /* FOR TIME */ char PARM10[26]. char parm7c[10]. signed long int PARM2. Sample of CREATE PROCEDURE and CALL (Part 1 of 2) 136 DB2 UDB for AS/400 SQL Programming V4R4 . :PARM7.26). strncpy(PARM8. : } */ */ */ */ */ /******** END OF C APPLICATION **********************************/ /****************************************************************/ Figure 5. /* FOR TIMESTAMP */ /***********************************************/ /* Call the C procedure */ /* */ /* */ /***********************************************/ EXEC SQL CALL P1 (:PARM1. strcpy(PARM7.parm7c. :PARM5. PARM7.00". :PARM10 ). :PARM2."00000". :PARM9. :PARM6.10).parm7l = 5. PARM6 = 10.0. :PARM9. PARM4 = 1. :PARM5. :PARM6."00000".00. /* FOR TIME */ strncpy(PARM10. :PARM3."PARM1"). Sample of CREATE PROCEDURE and CALL (Part 2 of 2) Chapter 7. :PARM8. if (strncmp(SQLSTATE. :PARM3."PARM7").000000". if (strncmp(SQLSTATE.2. PARM3 = -1. PARM5 = 1."1994-12-31-12.00. :PARM7. :PARM8. :PARM4. : /***********************************************/ /* Call the PLI procedure */ /* */ /* */ /***********************************************/ /* Reset the host variables prior to making the CALL /* : EXEC SQL CALL P2 (:PARM1.555. Stored Procedures 137 .8). /* FOR DATE */ strncpy(PARM9.5)) { /* Handle error or warning returned on CALL statement } /* Process return values from the CALL.5)) { /* Handle error or warning returned on CALL statement */ } /* Process return values from the CALL. :PARM2."12. :PARM10 )."1994-12-31".00. PARM2 = 7000./*******************************************************/ /* Initialize variables for the call to the procedures */ /*******************************************************/ strcpy(PARM1. :PARM4. ind3.argv[1]). char parm9[8]. long int parm2. Note that */ /* the argument vector could be used directly instead of */ /* copying the parameters into local variables . /* Copy double precision number into local variable parm5 = *(double *) argv[5]. /* Copy decimal number into local variable parm6 = *(decimal(10. double parm5. float parm4.h> main(argc. decimal(10.i.ind9.ind4. /* Copy floating point number into local variable parm4 = *(float *) argv[4].5) *) argv[6]. */ /* *********************************************************/ /* Copy 10 byte character string into local variable strcpy(parm1./******** START OF C PROCEDURE P1 *******************************/ /* PROGRAM TEST12/CALLPROC2 */ /****************************************************************/ #include <stdio.ind1. char *argv[].ind5. and timestamp are passed as */ /* NUL terminated strings . char parm10[26]. time. ind8.*ind.j. /* Copy 4 byte integer into local variable parm2 = *(int *) argv[2]. { char parm1[11].5) parm6.cast the argument vector to */ /* the proper data type for each variable.ind2.ind6. /* *********************************************************/ /* Receive the parameters into the local variables */ /* Character.ind7.argv) int argc. short int parm3.the copy */ /* is done here just to illustrate the method.h> #include <string. char parm7[11]. char parm8[10]. date.h> #include <decimal. Sample Procedure P1 (Part 1 of 2) 138 DB2 UDB for AS/400 SQL Programming V4R4 . /* Copy 2 byte integer into local variable parm3 = *(short int *) argv[3].ind10. */ */ */ */ */ */ Figure 6. ind8 = *(ind++). */ /**********************************************************/ /* Copy timestamp into local variable. */ /* Below is one way to set each indicator into separate */ /* variables. strcpy would work here just as well.argv[8]. */ /* IBM SQL timestamp format is always passed so the length*/ /* of the string is known. ind2 = *(ind++). ind10 = *(ind++). */ /* Note that the parameter in the CREATE PROCEDURE was */ /* declared as varying length character. ind1 = *(ind++). */ /**********************************************************/ strncpy(parm10.26). } /******** END OF C PROCEDURE P1 *******************************/ Figure 6.argv[9].10). ind7 = *(ind++). Sample Procedure P1 (Part 2 of 2) Chapter 7. /**********************************************************/ /* Copy date into local variable. Stored Procedures 139 . There is one entry for each parameter passed */ /* on the CREATE PROCEDURE (10 for this example).argv[7]). */ /**********************************************************/ ind = (short int *) argv[11]. ind6 = *(ind++).argv[10]. */ /**********************************************************/ strncpy(parm8. : /* Perform any additional processing here */ : return. ind9 = *(ind++). varying */ /* length are passed as NUL terminated strings unless */ /* FOR BIT DATA is specified in the CREATE PROCEDURE */ /**********************************************************/ strcpy(parm7. /**********************************************************/ /* The indicator array is passed as an array of short */ /* integers. ind4 = *(ind++). For C. ind5 = *(ind++). */ /* Note that date and time variables are always passed in */ /* ISO format so that the lengths of the strings are */ /* known./**********************************************************/ /* Copy NUL terminated string into local variable. ind3 = *(ind++). /* Copy time into local variable strncpy(parm9.8). IN PARM2 INTEGER. IN PARM10 TIMESTAMP) EXTERNAL NAME 'TEST.PARM3.5). IN PARM6 GRAPHIC(4). IN PARM9 TIME. /* FOR TIME */ DCL PARM10 CHAR(26).CALLSRC(CALLREXX)' LANGUAGE REXX GENERAL WITH NULLS 140 DB2 UDB for AS/400 SQL Programming V4R4 .PARM11).Variables can be set to other values for */ /* return to the calling program. /* FOR TIMESTAMP */ DCL PARM11(10) FIXED BIN(15). IN PARM4 DOUBLE PRECISION. /* FOR DATE */ DCL PARM9 CHAR(8).PARM6. IN PARM8 DATE. PARM8. DCL SYSPRINT FILE STREAM OUTPUT EXTERNAL.PARM4. OPEN FILE(SYSPRINT). DCL PARM2 FIXED BIN(31).PARM2. IN PARM3 DECIMAL(10. DCL PARM6 FIXED DEC(10./******** START OF PL/I PROCEDURE P2 **************************/ /******** PROGRAM TEST12/CALLPROC *****************************/ /**************************************************************/ CALLPROC :PROC( PARM1. DCL PARM8 CHAR(10). /* Indicators */ /* PERFORM LOGIC . */ : END CALLPROC. IN PARM5 VARCHAR(10). IN PARM7 VARGRAPHIC(10). DCL PARM3 FIXED BIN(15).PARM9.PARM7.5).PARM5. Figure 7. Sample Procedure P2 The next example shows a REXX procedure called from an ILE C program.PARM10. DCL PARM7 CHARACTER(10) VARYING. Assume a procedure is defined as follows: EXEC SQL CREATE PROCEDURE REXXPROC (IN PARM1 CHARACTER(20). DCL PARM5 BIN FLOAT(53). DCL PARM4 BIN FLOAT(22). DCL PARM1 CHAR(10). h> /*-----------------------------------------------------------*/ exec sql include sqlca. decimal(10. 0x0000 }. Sample REXX Procedure Called From C Application /**************************************************************/ /*********** START OF SQL C Application ***********************/ #include <decimal. char parm9[8]. } parm7 = {0x0009. 0xC1C1.0xE4E4. struct { short dlen. 0xE7E7.h> #include <stdio. } parm5. exec sql include sqlda. char parm10[26].Example 2. Sample REXX Procedure Called From C Application (Part 1 of 4) Chapter 7. main() { Figure 8. 0xC2C2. 0xC3C3.h> #include <wcstr.5) parm3. 0xE5E5. char dat[10]. char parm8[10]. wchar_t parm6[4] = { 0xC1C1. 0xE8E8. 0x0000 }. 0xE2E2. Stored Procedures 141 . wchar_t dat[10]. double parm4. 0xE9E9.h> #include <string. /* ***********************************************************/ /* Declare host variable for the CALL statement */ /* ***********************************************************/ char parm1[20]. 0xE6E6. struct { short dlen. signed long int parm2.0xE3E3. :parm8."parm6"). strcpy(parm9. */ /* the procedure detected an error. parm4 = 3e3.on return from the CALL statement the */ /* SQLCODE should be 0. :parm6.5. :parm3."1994-01-01"). if (strncpy(SQLSTATE./* *************************************************************/ /* Call the procedure .dat. Sample REXX Procedure Called From C Application (Part 2 of 4) 142 DB2 UDB for AS/400 SQL Programming V4R4 ."13. */ /* *************************************************************/ strcpy(parm1. strcpy(parm10.01. :parm9.01."1994-01-01-13. :parm10)."00000".00. parm3 = 5. parm2 = 12345. strcpy(parm5.000000"). :parm5.:parm4. If the SQLCODE is non-zero."TestingREXX").5)) { /* handle error or warning returned on CALL : } : */ } /****** END OF SQL C APPLICATION ************************************/ /**********************************************************************/ Figure 8.00"). strcpy(parm8. parm5. :parm2. EXEC SQL CALL REXXPROC (:parm1. :parm7.dlen = 5. 01.5) = 5.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.00.01./**********************************************************************/ /****** 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 */ /* 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. Sample REXX Procedure Called From C Application (Part 3 of 4) Chapter 7.00'" then signal ar9tag if ar10 <> "'1994-01-01-13.00' */ /* AR10 TIMESTAMP = */ /* '1994-01-01-13. signal ar7tag if ar8 <> "'1994-01-01'" then signal ar8tag if ar9 <> "'13.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 . Stored Procedures 143 .00.000000'" then signal ar10tag if ar11 <> "+0+0+0+0+0+0+0+0+0+0" then signal ar11tag Figure 8.01. /************************************************************/ /* 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 **********************************/ Figure 8. Sample REXX Procedure Called From C Application (Part 4 of 4) 144 DB2 UDB for AS/400 SQL Programming V4R4 .. Therefore. Note: The use of the DB2 object-oriented mechanisms (UDTs. you can now define new types and functions of your own to store and manipulate application objects within the database. In addition. UDFs. you can make the semantic behavior of stored objects an important resource that can be shared among all your applications by means of the database. you can incorporate object-oriented (OO) concepts and methodologies into your relational database. These new types and functions should reflect the semantics of the objects in your application domain. and LOBs can better represent the objects in your application and thus work together. This section shows you how to use LOBs along with the steps that are required to define UDTs and UDFs.Chapter 8. there is an important synergy among these object-oriented features. Why Use the DB2 Object Extensions? | | | | | | | With the object extensions of DB2. With these extensions. you can store instances of object-oriented data types in columns of tables. 1997. You accomplish this by extending it with richer sets of types and functions. Objects of the same type behave in the same way because they share the same set of type-specific functions. text. As described in subsequent sections. In turn. user-defined functions (UDFs). v Why Use the DB2 Object Extensions? v DB2 Approach to Supporting Objects v Using Large Objects (LOBs) v User-Defined Functions (UDF) v User-defined Distinct Types (UDT) v Synergy Between UDTs. The UDT may in turn be internally represented as a LOB. you can define new types and functions of your own. the UDT’s behavior may be implemented in terms of UDFs. To incorporate object-orientation into your relational database systems. UDFs. 1999 145 . You can model a complex object in the application domain as a UDT. Using the Object-Relational Capabilities This chapter discusses the object-oriented capabilities of DB2. Some of the data objects you want to model may be large and complex (for example. Just as the C++ programming language implements all sorts of non-object-oriented applications. image. UDTs. and financial data). and LOBs are general-purpose mechanisms that can be used to model any database © Copyright IBM Corp. and LOBs One of the most important recent developments in modern programming language technology is object-orientation. UDFs. Object orientation is the notion that entities in the application domain can be modeled as independent objects that are related to one another by means of classification. and Large Objects (LOBs) are the mechanisms that are provided by DB2. and operate on them by means of functions in SQL statements. With DB2. Object-orientation lets you capture the similarities and differences among objects in your application domain and group those objects together into related types. voice. You will also learn how UDTs. These functions reflect the behavior of your objects in the application domain. User-defined Distinct types (UDTs). you may also need mechanisms for the storage and manipulation of large objects. the object-oriented mechanisms provided by DB2 can also support all kinds of non-object-oriented applications. UDFs. and LOBs) is not restricted to the support of object-oriented applications. UDFs. UDTs can be internally represented in different ways. In a relational system. and Double-Byte Character Large OBjects (DBCLOBs). Along with storing large objects (LOBs). DB2 provides three data types to store these data objects as strings of up to fifteen (15) megabytes (MB) in size. LOBs are just one example of this. UDT instances are stored in columns of tables and manipulated by UDFs in SQL queries.application. and images. and modify each LOB in the database. UDT’s. use. Locators are useful to identify and manipulate a large object value at the database server and for extracting pieces of the LOB value. support the manipulation of UDT instances. The three data types are: Binary Large OBjects (BLOBs). Although a single row containing one or more LOB values cannot exceed 15 megabytes. For this reason. a table may contain nearly 256 gigabytes of LOB data. you will also need a method to refer to. 146 DB2 UDB for AS/400 SQL Programming V4R4 . DB2 Approach to Supporting Objects The object extensions of DB2 enable you to realize the benefits of object technology while building on the strengths of relational technology. object-oriented applications. While this may be sufficient for small to medium size text data. Operations on these instances are supported by means of operators or functions that can be invoked anywhere that expressions are allowed. applications often need to store large text documents. video. that is. Thus. like built-in functions or operators. Each DB2 table may have a large amount of associated LOB data. The content of the LOB column of a particular row at any point in time has a large object value. They may also need to store a wide variety of additional data types such as audio. The subsections that follow discuss the topics that are introduced above in more detail. drawings. However. Other means are necessary to manipulate these large values. like built-in types. UDFs are functions that you define. host variables use the client memory buffer which may not be large enough to hold LOB values. can be used to describe the data that is stored in columns of tables. Using Large Objects (LOBs) The VARCHAR and VARGRAPHIC data types have a limit of 32K bytes of storage. | | | | | | | The DB2 approach to support object extensions fits exactly into the relational paradigm. You can refer to and manipulate LOBs using host variables just as you would any other data type. these DB2 object extensions offer extensive support for both non-traditional. mixed text and graphics. UDTs are data types that you define. single-byte Character Large OBjects (CLOBs). File reference variables are useful for physically moving a large object value (or a large part of it) to and from the client. data types describe the data stored in columns of tables where the instances (or objects) of these data types are stored. in addition to improving support for traditional ones. or the locator is explicitly freed. voice. Using the Object-Relational Capabilities 147 . The LOB locator is associated with a LOB value or LOB expression. after selecting a LOB value into a locator. and other types of business or application-specific data. Specifically. UDTs using BLOBs as the source type are created to store image. In a similar way. you cannot perform an operation on the original row(s) or tables(s) that would have any effect on the value referenced by the locator. v Select the entire LOB value into a host variable. When you use the LOB locator.Understanding Large Object Data Types (BLOB. The FREE LOCATOR statement releases a locator from its associated value. Therefore. When selecting a LOB value. LOB locators can also be passed between DB2 and UDFs. use a small. For more information on UDTs. easily managed value to refer to a much larger value. LOB locators represent a simple idea that has been around for a while. it is a perfect source type for use by User-defined Distinct Types (UDTs). DBCLOB) | Large object data types store data ranging in size from zero bytes to 15 megabytes. Code page conversion of the information is supported as well as compatibility with the other character types. The LOB value remains on the server. graphical. see “User-defined Distinct Types (UDT)” on page 169. a program can manipulate the LOB value as if the LOB value was stored in a regular host variable. Within the UDF. those functions that work on LOB data are available to manipulate the LOB values using LOB locators. v Binary Large OBjects (BLOBs) — A binary string made up of bytes with no associated code page. Using a LOB locator. The value associated with the locator is valid until the unit of work ends. Again. you have three options. | | Chapter 8. there is no need to transport the LOB value from the server to the application (and possibly back again). Therefore. v Select the LOB value into a LOB locator. This data type may be the most useful because it can store binary data. a commit or roll-back operation frees all LOB locators associated with the transaction. CLOB. code page conversion of the information is supported as well as compatibility with the other double-byte character types. The entire LOB value is copied into the host variable. whichever comes first. The three large object data types have the following definitions: v Character Large OBjects (CLOBs) — A character string made up of single-byte characters with an associated code page. This data type is best for holding text-oriented information where the amount of information could grow beyond the limits of a regular VARCHAR data type (upper limit of 32K bytes). | | | | | Understanding Large Object Locators Conceptually. it is not copied to the host variable. not a row or physical storage location in the database. This data type is best for holding text-oriented information where double-byte character sets are used. a LOB locator is a 4-byte value stored in a host variable that a program uses to refer to a LOB value (or LOB expression) held in the database system. v Double-Byte Character Large OBjects (DBCLOBs) — A character string made up of double-byte characters with an associated code page. Host variables are prefixed with a colon (:) when referenced in an SQL statement. The use of the LOB value within the program can help the programmer determine which method is best.c file. CLOB LOCATOR host variables are declared. then it uses the locator to extract the data from the LOB value. The LOB value is moved to an Integrated File System (IFS) file. there are still three options available to you. You can select the entire value into a regular or file reference host variable. the application program retrieves a locator for a LOB value. 2. then there is no choice but to transfer the LOB. Example: Using a Locator to Work With a CLOB Value In this example. The BEGIN DECLARE SECTION and END DECLARE SECTION statements delimit the host variable declarations. the program allocates only enough storage for one piece of LOB data (the size is determined by the program). The location of this error checking utility depends on the programming language that is used: C check_error is redefined as CHECKERR and is located in the util. Free the LOB LOCATORS. keep the value in a locator. If the LOB value is very large and is needed only as an input value for one or more subsequent SQL statements. The CHECKERR macro/function is an error checking utility which is external to the program. 3. Using this method. You may also select the LOB value into a locator and read it piecemeal from the locator into a regular host variable. the program needs to issue only one fetch call using the cursor. The LOB LOCATORS used in this example are freed. as suggested in the following example.v Select the entire LOB value into a file reference variable. | | | | | If the program needs the entire LOB value regardless of the size. Even in this case. | | | 148 DB2 UDB for AS/400 SQL Programming V4R4 . releasing the locators from their previously associated values. Fetch the LOB value into the locator host variable. How the Sample LOBLOC Program Works 1. A CURSOR and FETCH routine is used to obtain the location of a LOB field in the database to a locator host variable. Declare host variables. In addition. EXEC SQL CONNECT TO sample USER :userid USING :passwd. :resume :lobind. char buffer[1000]="". /* Append the "Department Information" section to the :buffer var.Info" */ EXEC SQL VALUES (POSSTR(:resume. */ EXEC SQL VALUES(:buffer || :deptBuffer) INTO :buffer. CHECKERR ("VALUES1"). } #endif printf ("%s\n". char passwd[19]. because the lobeval program manipulates the record for A10030 so that it is not compatible with lobloc */ EXEC SQL DECLARE c1 CURSOR FOR SELECT empno. 'Education')) INTO :deptInfoEndLoc. CHECKERR ("VALUES2"). EXEC SQL OPEN c1.:deptInfoBeginLoc)) INTO :deptBuffer. return 1. short lobind. Using the Object-Relational Capabilities 149 . if (lobind < 0) { printf ("NULL LOB indicated\n"). long deptInfoBeginLoc. /* Obtain ONLY the "Department Information" section by using SUBSTR */ EXEC SQL VALUES(SUBSTR(:resume.h> #include "util. :deptInfoBeginLoc. 2 if (SQLCODE != 0) break.h> #include <string. :deptBuffer. bufptr++. EXEC SQL FREE LOCATOR :resume.buffer). CHECKERR ("OPEN CURSOR"). } /* endif */ } while ( 1 ). SQL TYPE IS CLOB_LOCATOR resume.C Sample: LOBLOC. do { EXEC SQL FETCH c1 INTO :number.SQC #include <stdio. while ( *bufptr != '\0' ) { if ( *bufptr == 0x0A ) *bufptr = 0x0D. /* Locate the beginning of "Education" section (end of "Dept. CHECKERR ("VALUES4"). long deptInfoEndLoc. if (argc == 1) { EXEC SQL CONNECT TO sample. CHECKERR ("VALUES3"). strcpy (passwd. 3 Chapter 8.h> #include <stdlib. } /* endif */ /* Employee A10030 is not included in the following select. int main(int argc. EXEC SQL END DECLARE SECTION.h" EXEC SQL INCLUDE SQLCA. char *argv[]) { #ifdef DB2MAC char * bufptr. argv[1]). #endif EXEC SQL BEGIN DECLARE SECTION. :deptInfoEndLoc . } else { /* EVALUATE the LOB LOCATOR */ /* Locate the beginning of "Department Information" section */ EXEC SQL VALUES (POSSTR(:resume. CHECKERR ("CONNECT TO SAMPLE"). } else { printf ("\nUSAGE: lobloc [userid passwd]\n\n"). } else if (argc == 3) { strcpy (userid. 'Department Information')) INTO :deptInfoBeginLoc. printf( "Sample C program: LOBLOC\n" ). resume FROM emp_resume WHERE resume_format='ascii' AND empno <> 'A00130'. 1 char number[7]. argv[2]). #ifdef DB2MAC /* Need to convert the newline character for the Mac */ bufptr = &(buffer[0]). &sqlca) != 0) return 1. SQL TYPE IS CLOB_LOCATOR deptBuffer. CHECKERR ("CONNECT TO SAMPLE"). #define CHECKERR(CE_STR) if (check_error (CE_STR. char userid[9]. call "checkerr" using SQLCA errloc. End-Main. 01 lobind pic s9(4) comp-5. * display contents of the buffer. call "checkerr" using SQLCA errloc. CHECKERR ("CLOSE CURSOR"). EXEC SQL CONNECT TO sample USER :userid USING :passwd END-EXEC. EXEC SQL BEGIN DECLARE SECTION END-EXEC. perform Fetch-Loop thru End-Fetch-Loop until SQLCODE not equal 0. EXEC SQL CONNECT RESET. 01 passwd. EXEC SQL END DECLARE SECTION END-EXEC. * Get database connection information. Move 0 to buffer-length. * Employee A10030 is not included in the following select. call "checkerr" using SQLCA errloc. display "Enter your user id (default none): " with no advancing. * Passwords in a CONNECT * format with the length inspect passwd-name before initial " statement must be entered in a VARCHAR of the input string.SQC */ COBOL Sample: LOBLOC.cbl". move "CONNECT TO" to errloc. 01 empnum pic x(6). 01 di-begin-loc pic s9(9) comp-5. return 0. 1 01 userid pic x(8). 01 di-end-loc pic s9(9) comp-5. move "FREE LOCATOR" to errloc. 49 passwd-length pic s9(4) comp-5 value 0. copy "sqlenv. 77 errloc pic x(80). Program-ID. Main Section.SQB Identification Division. EXEC SQL CONNECT RESET END-EXEC.cbl". tallying passwd-length for characters ". 01 di-buffer USAGE IS SQL TYPE IS CLOB-LOCATOR. call "checkerr" using SQLCA errloc. because * the lobeval program manipulates the record for A10030 so that it is * not compatible with lobloc EXEC SQL DECLARE c1 CURSOR FOR SELECT empno.CHECKERR ("FREE LOCATOR"). 49 passwd-name pic x(18). EXEC SQL FREE LOCATOR :resume. move "CONNECT RESET" to errloc. accept userid. resume FROM emp_resume WHERE resume_format = 'ascii' AND empno <> 'A00130' END-EXEC. } /* end of program : LOBLOC. Data Division. copy "sqlca. "lobloc". CHECKERR ("CONNECT RESET"). call "checkerr" using SQLCA errloc.cbl". :di-buffer END-EXEC. 01 buffer USAGE IS SQL TYPE IS CLOB(1K). 3 150 DB2 UDB for AS/400 SQL Programming V4R4 . if userid = spaces EXEC SQL CONNECT TO sample END-EXEC else display "Enter your password : " with no advancing accept passwd-name. display "Sample COBOL program: LOBLOC". EXEC SQL CLOSE c1 END-EXEC. move "CLOSE CURSOR" to errloc. 01 resume USAGE IS SQL TYPE IS CLOB-LOCATOR. EXEC SQL OPEN c1 END-EXEC. copy "sql. display buffer-data(1:buffer-length). EXEC SQL CLOSE c1. Working-Storage Section. Procedure Division. move "OPEN CURSOR" to errloc. A file reference variable represents (rather than contains) the file. To carry out the movement of LOB data. however. It is likely that most LOBs begin as data stored in files on the client before they are moved to the database on the server. :resume :lobind 2 END-EXEC. EXEC SQL FETCH c1 INTO :empnum. :di-begin-loc. subtract di-begin-loc from di-end-loc. Chapter 8. * Obtain ONLY the "Department Information" section by using SUBSTR EXEC SQL VALUES (SUBSTR(:resume. display "NULL LOB indicated". a negative indicator variable value indicates that the LOB value represented by the LOB locator is NULL. exit. call "checkerr" using SQLCA errloc. move "VALUES1" to errloc. 'Education')) INTO :di-end-loc END-EXEC. just as a LOB locator represents (rather than contains) the LOB value. NULL-lob-indicated. * Value exists. Since a locator host variable itself can never be NULL. move "VALUES2" to errloc. Fetch-Loop Section. the meaning of indicator variables is slightly different. stop run. The use of file reference variables assists in moving LOB data. End-Prog. call "checkerr" using SQLCA errloc. In the case of LOB locators. Database queries. if SQLCODE not equal 0 go to End-Fetch-Loop. Evaluate the LOB locator. The NULL information is kept local to the client using the indicator variable value — the server does not track NULL values with valid locators. Using the Object-Relational Capabilities 151 . * Locate the beginning of "Education" section (end of Dept. call "checkerr" using SQLCA errloc. or to retrieve. 'Department Information')) INTO :di-begin-loc END-EXEC. End-Fetch-Loop. Indicator Variables and LOB Locators For normal host variables in an application program. * Append the "Department Information" section to the :buffer var EXEC SQL VALUES (:buffer || :di-buffer) INTO :buffer END-EXEC. when selecting a NULL value into a host variable.Info) EXEC SQL VALUES (POSSTR(:resume. if lobind less than 0 go to NULL-lob-indicated. a negative value is assigned to the indicator variable signifying that the value is NULL. * Locate the beginning of "Department Information" section. For very large objects. move "VALUES4" to errloc. single LOB values. updates. and inserts may use file reference variables to store. move "VALUES3" to errloc. * check to see if the host variable indicator returns NULL. files are natural containers. the application does not have to write utility routines to read and write files using host variables. call "checkerr" using SQLCA errloc. go to End-Fetch-Loop. :di-end-loc)) INTO :di-buffer END-EXEC. EXEC SQL VALUES (POSSTR(:resume.go to End-Prog. Programs use file reference variables to transfer LOB data from the IFS file directly to the database engine. LOB File Reference Variables File reference variables are similar to host variables except they are used to transfer data to and from IFS files (not to and from memory buffers). Should the file already exist. (The value for COBOL is SQL-FILE-APPEND. The file name length is specified within the application program. the data length is set by the application requestor code to the length of the new data that is written to the file. Values (shown for C) and options when using input file reference variables are as follows: v SQL_FILE_READ (Regular file) — This option has a value of 2. It is used either as the source of data (input) or as the target of data (output). Otherwise. The data length portion of the file reference variable is unused during input. it creates a new file.) v SQL_FILE_OVERWRITE (Overwrite file) — This option has a value of 16. see Integrated File System Introduction. | | | | | | Example: Extracting a Document To a File This program example shows how CLOB elements can be retrieved from a table into an external file. How the Sample LOBFILE Program Works 1. DB2 then returns the length through the data_length field of the file reference variable structure. A file reference variable has a data type of BLOB. and closed. this would be the server. 152 DB2 UDB for AS/400 SQL Programming V4R4 . the new data overwrites the data in the file. The BEGIN DECLARE SECTION and END DECLARE SECTION statements delimit the host variable declarations. (The value for COBOL is SQL-FILE-READ. During output. A CLOB FILE REFERENCE host variable is declared. or DBCLOB.) Note: If a LOB file reference variable is used in an OPEN statement. an error message is returned. (The value for COBOL is SQL-FILE-CREATE. For more information about integrated file system.Note: The file referenced by the file reference variable must be accessible from (but not necessarily resident on) the system on which the program runs. This option has the output appended to the file.) Values and options when using output file reference variables are as follows: | | | | | | | | | | v SQL_FILE_CREATE (New file) — This option has a value of 8. The file reference variable may have a relative file name or a complete path name of the file (the latter is advised). (The value for COBOL is SQL-FILE-OVERWRITE.) v SQL_FILE_APPEND (Append file) — This option has a value of 32. read. This option creates a new file. Choices for assignment to the field covering both input and output values are shown below. Host variables are prefixed with a colon (:) when referenced in an SQL statement. | | | | When using file reference variables there are different options on both input and output. This is a file that can be open. if it exists. CLOB. do not delete the file associated with the LOB file reference variable until the cursor is closed. For a stored procedure. Declare host variables. You must choose an action for the file by setting the file_options field in the file reference variable structure. If the file already exists. DB2 determines the length of the data in the file (in bytes) when opening the file. This option creates a new file if none already exists. If the pathname does not begin with the forward slash (/) character.cbl". 3 if (lobind < 0) { printf ("NULL LOB indicated \n"). resume. 1 Chapter 8.name_length = strlen("RESUME. #define CHECKERR(CE_STR) if (check_error (CE_STR. 3.SQC #include <stdio. EXEC SQL END DECLARE SECTION.SQB Identification Division. "lobfile". copy "sqlenv. Working-Storage Section.name.TXT"). } else { printf ("Resume for EMPNO 000130 is in file : RESUME. "RESUME. } /* end of program : LOBFILE. Using the Object-Relational Capabilities 153 . char passwd[19].c file. Data Division. Program-ID. A file name without a fully declared path is.file_options = SQL_FILE_OVERWRITE. The CHECKERR macro/function is an error checking utility which is external to the program. CHECKERR ("CONNECT RESET"). } /* endif */ EXEC SQL CONNECT RESET. if (argc == 1) { EXEC SQL CONNECT TO sample. strcpy (passwd. int main(int argc. placed in the user’s current directory. &sqlca) != 0) return 1.| | | | | | 2. EXEC SQL SELECT resume INTO :resume :lobind FROM emp_resume WHERE resume_format='ascii' AND empno='000130'. by default. } else if (argc == 3) { strcpy (userid. CHECKERR ("CONNECT TO SAMPLE"). Select into the CLOB FILE REFERENCE host variable. short lobind. printf( "Sample C program: LOBFILE\n" ). The data from the resume field is selected into the filename that is referenced by the host variable.SQC */ COBOL Sample: LOBFILE. argv[2]). char *argv[]) { EXEC SQL BEGIN DECLARE SECTION. CHECKERR is an external program named checkerr. return 1.cbl". } /* endif */ strcpy (resume. 1 SQL TYPE IS CLOB_FILE resume. argv[1]).cbl C Sample: LOBFILE. The location of this error checking utility depends upon the programming language used: C COBOL check_error is redefined as CHECKERR and is located in the util. CHECKERR ("CONNECT TO SAMPLE").h> #include <string. EXEC SQL BEGIN DECLARE SECTION END-EXEC.cbl".h" EXEC SQL INCLUDE SQLCA. char userid[9]. it is not qualified. copy "sql.h> #include "util. 2 resume.h> #include <stdlib.h> #include <sql. } else { printf ("\nUSAGE: lobfile [userid passwd]\n\n"). EXEC SQL CONNECT TO sample USER :userid USING :passwd. CLOB FILE REFERENCE host variable is set up. The attributes of the FILE REFERENCE are set up. copy "sqlca.TXT").TXT\n"). return 0. End-Prog. display "Resume for EMPNO 000130 is in file : RESUME. hv_text_file. hv_text_file. dirname represents a subdirectory name of “userid”. display "Sample COBOL program: LOBFILE". The following example shows how to insert data from a regular file referenced by :hv_text_file into a CLOB column: strcpy(hv_text_file. if lobind less than 0 go to NULL-LOB-indicated. * Get database connection information. Main Section. * Passwords in a CONNECT * format with the length inspect passwd-name before initial " statement must be entered in a VARCHAR of the input string. tallying passwd-length for characters ". EXEC SQL CONNECT TO sample USER :userid USING :passwd END-EXEC. End-Main. 77 errloc pic x(80). 01 passwd.01 userid pic x(8). filnam.1 can become the name of one of your documents that you wish to insert into the table.TXT". EXEC SQL CONNECT RESET END-EXEC. display "NULL LOB indicated". move "CONNECT TO" to errloc. 49 passwd-length pic s9(4) comp-5 value 0. 49 passwd-name pic x(18). 01 resume USAGE IS SQL TYPE IS CLOB-FILE. | | | | | | | | 154 DB2 UDB for AS/400 SQL Programming V4R4 .file_options = SQL_FILE_READ.name_length = strlen("/home/userid/dirname/filnam. 01 lobind pic s9(4) comp-5. 2 Example: Inserting Data Into a CLOB Column In v v v the path description of the following C program segment: userid represents the directory for one of your users.1"). move "CONNECT RESET" to errloc. v clobtab is the name of the table with the CLOB data type. Procedure Division. move "RESUME. /* this is a 'regular' file */ EXEC SQL INSERT INTO CLOBTAB VALUES(:hv_text_file).TXT" to resume-NAME. move 10 to resume-NAME-LENGTH. if userid = spaces EXEC SQL CONNECT TO sample END-EXEC else display "Enter your password : " with no advancing accept passwd-name. NULL-LOB-indicated.1"). call "checkerr" using SQLCA errloc. call "checkerr" using SQLCA errloc.name. go to End-Main. accept userid. EXEC SQL END DECLARE SECTION END-EXEC. stop run. EXEC SQL SELECT resume INTO :resume :lobind 3 FROM emp_resume WHERE resume_format = 'ascii' AND empno = '000130' END-EXEC. display "Enter your user id (default none): " with no advancing. move SQL-FILE-OVERWRITE to resume-FILE-OPTIONS. "/home/userid/dirname/filnam. For more information on the Journal handling of LOB columns. say you have a table that holds three columns: ColumnOne Char(10). each row of data would look as follows. ColumnTwo CLOB(40K). Using the Object-Relational Capabilities 155 . Refer to the section above on the Display Layout of LOB Columns for an example of how the length of this first part is calculated. when the value *TYPEPTR is specified for the ENTFMT keyword v Retrieve Journal Entries (QjoRetrieveJournalEntries) API The layout of the LOB columns in these entries is as follows: v 0 to 15 bytes of hex zeros v 1 byte of system information set to ’00’x v 4 bytes holding the length of the LOB data addressed by the pointer. The number of bytes in the first portion of the value is set to the number needed to 16 byte boundary align the second part of the value. Journal Entry Layout of LOB Columns Two commands return a buffer that gives the user addressability to LOB data that had been journaled: v Receive Journal Entry (RCVJRNE) CL command. Journals and Journal Receivers″ chapter of the Backup and Recovery book. *TYPE2. If you were to issue a DSPPFM of this table. The number of bytes in this area depends on the length of the columns that proceed the LOB column. v For ColumnThree: 16 bytes filled with hex zeros and 16 bytes filled with ’*POINTER ’. Instead. The full set of commands that display LOB columns in this way is: v Display Physical File Member (DSPPFM) v Copy File (CPYF) when the value *PRINT is specified for the TOFILE keyword v Display Journal (DSPJRN) v Retrieve Journal Entry (RTVJRNE) v Receive Journal Entry (RCVJRNE) when the values *TYPE1. v For ColumnOne: 10 bytes filled with character data. below v 8 bytes of hex zeros v 16 bytes holding a pointer to the LOB data stored in the Journal Entry. refer to the ″Working with Journal Entries. and ColumnThree BLOB(10M). the Database will show a special value for the LOB columns. The first part of this layout is intended to 16 byte boundary align the pointer to the LOB data. v 16 bytes beginning with *POINTER and followed by blanks. the LOB data stored in that row will not be displayed. *TYPE3 and *TYPE4 are specified for the ENTFMT keyword. For example. v For ColumnTwo: 22 bytes filled with hex zeros and 16 bytes filled with ’*POINTER ’.| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Display Layout of LOB Columns When a row of data from a table holding LOB columns is displayed using CL commands such as Display Physical File Member (DSPPFM). The layout of this special value is as follows: v 13 to 28 bytes of hex zeros. Chapter 8. Many of the programs at your site implement the same basic set of functions. you should still consider: v Re-use. Although it appears easier to implement new operations as subroutines or functions in your application. v Flexibility. If you correctly implement these functions once. v Standardization. a trivial calculation. by providing behavior and encapsulating the types. SQL UDFs provide a way for users to further manipulate and enhance the capabilities of the database (to the specialization required) in this area.User-Defined Functions (UDF) A user-defined function is a mechanism with which you can write your own extensions to SQL. or a complicated multivariate analysis. The database will take care of many data type promotions of the function arguments automatically. then all these programs can use the same implementation directly in SQL and provide consistent results. In addition. and package the function effectively for their use. Whether the function is a simple transformation. you have a choice when implementing desired actions or operations: v As a UDF v As a subroutine or function in your application. SQL UDFs provide the support to manipulate Large Objects and DataLink types. you are unsure about the consistency of the results you receive. Why Use UDFs? In writing DB2 applications. this process ignores the interactive users like 156 DB2 UDB for AS/400 SQL Programming V4R4 . but there are minor differences in all the implementations. While the database provides several built-in functions which are useful in working with these datatypes. you would have to inform all other interested application developers. (You would not have to define the function to DB2. you may need to extend SQL for the following reasons: v Customization. As discussed in “User-defined Distinct Types (UDT)” on page 169. the function can be invoked directly in SQL wherever an expression can be used by any user of the database. Thus. However. UDTs can be very useful in extending the capability and increasing the safety of DB2. in a UDF. It may seem easier to implement your new function as a normal function. Thus. For example. | | | | | In addition. UDFs act as the methods for UDTs. then UDFs can help to reuse it. but compatible data types. The function specific to your application does not exist in DB2. but they may not satisfy all of your requirements.) If you did this. with DECIMAL to DOUBLE. v Object-relational support. The DB2 built-in function does not quite permit the variations that you wish to include in your application. The built-in functions supplied with DB2 are a useful set of functions. | | | | | | | | | | | If the new operation is something of which other users or programs at your site can take advantage. you can probably use a UDF to do the job. the database will allow your function to be applied to different. For additional details on UDTs and the important concept of castability discussed herein. <. The type create statement: CREATE DISTINCT TYPE BOAT AS BLOB(1MEG) Chapter 8. For example. The performance value of packaging this function as a UDF could be enormous. only the rows and column of interest are passed across the interface between the application and the database. You have to provide any additional behavior yourself. you are automatically provided cast functions between the distinct type and its source type. This also applies to any other tools that use SQL (such as Visualizer). Here. For more information on UDTs. Your application could issue the following select statement: SELECT A. and RUNSQLSTM. if SELECTION_CRITERIA() is implemented as a UDF. You can implement the behavior of a user-defined distinct type (UDT).| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | those who normally use the Command Line Processor (CLP) to access the database. that do not get recompiled. your application can issue the following statement: SELECT C FROM T WHERE SELECTION_CRITERIA(A. >. it runs SELECTION_CRITERIA against the data to decide if it is interested in processing the data further. defined over a one megabyte BLOB. also called distinct type. every row of table T must be passed back to the application. STRQM. These cases occur when the function is used in record selection processing. Consider a simple scenario where you want to process some data. suppose that you have a BOAT distinct type. depending on the particular situation. See “Indicator Variables and LOB Locators” on page 151 for an example of a similar scenario. see the CREATE DISTINCT TYPE statement in the DB2 UDB for AS/400 SQL Reference. You may also be provided comparison operators such as =.B)=1 In this case. But. therefore.) v Object Orientation. Using the Object-Relational Capabilities 157 . etc. When you create a distinct type. You can use UDFs. v Performance. (Note that you can also extract a portion of a LOB by using a LOB locator. You can meet some selection criteria which can be expressed as a function SELECTION_CRITERIA(). In certain cases. depending on the source type. Another case where a UDF can offer a performance benefit is when dealing with Large Objects (LOB). It is best to keep the behavior of a distinct type in the database where all of the users of the distinct type can easily access it. in addition to many clients such as ODBC. as the implementation mechanism. B. functions written for use only within programs ignores those (interactive) users who do not have associated programs. This includes commands such as STRSQL. invoking the UDF directly from the database engine instead of from your application can have a considerable performance advantage. CLP users cannot use your function unless it is a UDF in the database. You can perform this extraction right on the database server and pass only the extracted value back to the application. However. C FROM T When it receives each row. and so on. see “User-defined Distinct Types (UDT)” on page 169. JDBC. You willl notice this advantage when the function may be used in the qualification of data for further processing. Suppose you have a function that extracts some information from a value of one of the LOB types. using a UDF. This is more efficient than passing the entire LOB value back to the application and then performing the extraction. CURR_APPRAISL CANADIAN_DOLLAR. However.| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | The BLOB contains the various nautical specifications. ) CREATE TABLE MY_BOATS ( BOAT_ID CHAR(5). ) You can execute the following SQL SELECT statement: SELECT INV. In fact. you do not get the comparison operations automatically generated for you.BOAT_ID = '19GCC' AND BOAT_COMPARE(INV.OWNER.BOAT_ID. .. BOAT) RETURNS INTEGER . DESIGN_DATE DATE. You may wish to compare sizes of boats. INV. You create the BOAT_COMPARE function as follows: CREATE SQL FUNCTION BOAT_COMPARE (BOAT.DESIGNER = MY.SPEC) = 1 AND INV. metric tonnage. BOAT_TYPE VARCHAR(25). You can implement a BOAT_COMPARE function which decides if one boat is bigger than another based on a measure that you choose. These could be: displacement. BOAT_TYPE VARCHAR(25).DESIGNER This simple example returns all the boats from BOATS_INVENTORY from the same designer that are bigger than a particular boat in MY_BOATS. it completely avoids passing any values of data type BOAT.. If your function returns: – 1 the first BOAT is bigger – 2 the second is bigger and – 0 they are equal. You could use this function in your SQL code to compare boats.DESIGN_DATE FROM BOATS_INVENTORY INV. DESIGNER VARCHAR(40)... SPEC BOAT. INV. MY. DESIGNER VARCHAR(40). INV. This is a significant improvement in storage and performance as BOAT is based on a one megabyte BLOB data type. ACQUIRE_DATE DATE.. MY_BOATS MY WHERE MY. . UDF Concepts The following is a discussion of the important concepts you need to know prior to coding UDFs: Function Name | v Full name of a function. length over all. INV.BOAT_TYPE. DESIGN_DATE DATE. Note that the example only passes the rows of interest back to the application because the comparison occurs in the database server. ACQUIRE_PRICE CANADIAN_DOLLAR. OWNER VARCHAR(40). with a distinct type defined over a BLOB source type. SPEC BOAT.DESIGNER. or another calculation based on the BOAT object.SPEC. Suppose you create the following tables: CREATE TABLE BOATS_INVENTORY ( BOAT_ID CHAR(5).. and some drawings. 158 DB2 UDB for AS/400 SQL Programming V4R4 . In cases where a function reference matches functions in more than one schema in the path. see “Example: BLOB String Search” on page 162. These are functions provided by and shipped with the database. which means that multiple functions. Function names can be overloaded.FOO QSYS2. It provides a set of schemas for resolving unqualified references to UDFs as well as UDTs. The path is set by the SET PATH statement for dynamic SQL."QSYS2".SUBSTR QSYS2. SUBSTR() is an example. For example: SNOWBLOWER_SIZE FOO SUBSTR FLOOR v Path The concept of path is central to DB2’s resolution of unqualified references that occur when schema-name is not specified. in which case. These are functions created by users and registered to the database. The path is an ordered list of schema names. Using the Object-Relational Capabilities 159 . the order of the schemas in the path is used to resolve this match. v Overloaded function names."<ID>" This applies to both static and dynamic SQL. The path is established by means of the SQLPATH option on the precompile and bind commands for static SQL.SNOWBLOWER_SIZE SMITH. see the description of the corresponding CREATE FUNCTION statement in the DB2 UDB for AS/400 SQL Reference. For the use of path in DDL statements that refer to functions. are processed through the function selection algorithm. – User-defined. It is the function resolution algorithm that takes into account the facts of overloading and function path to choose the best fit for every function reference. When the first SQL statement that runs in an activation group runs with SQL naming. the default path is *LIBL. have the same signature. Chapter 8. v Function resolution. See the DB2 UDB for AS/400 SQL Reference book for more information on signature and function resolution.| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | The full name of a function using *SQL naming is <schema-name>. can have the same name. whether it is a qualified or an unqualified reference. you may also omit the <schema-name>. For an example of an overloaded function. Function names cannot be qualified using *SYS naming in DML statements. These are functions implicitly generated by the database engine when a DISTINCT TYPE is created. the path has the following default value: "QSYS". There are several types of functions: – Built-in. even in the same schema. You can use this full name anywhere you refer to a function.<functionname>. DB2 must determine the function to which you are referring. even built-in functions. These functions provide casting operations between the DISTINCT TYPE and its base type. which can be defined to be the qualified function name concatenated with the defined data types of all the function parameters in the order in which they are defined. where <ID> represents the current statement authorization ID. Two functions cannot..FLOOR However. All functions. When the first SQL statement in an activation group runs with system naming. – System-generated. For example: QGPL. v Types of function. The full name of a function in *SYS naming is <schema-name>/<function-name>. however. For example. – Defining the interface between the database and the function is by use of SQL declares. the built-in function SUBSTR() is a scalar function. v Sourced UDFs. datalinks. SQL UDFs are functions written entirely in the SQL language. For SQL UDFs. Their ’code’ is actually SQL statements embedded within the CREATE FUNCTION statement itself. The SQLPATH precompile option is discussed in the command appendix. 1. each function can be further classified as a scalar or column function. and the function resolution algorithm are discussed in detail in the DB2 UDB for AS/400 SQL Reference. For example. or sourced (using the implementation of an existing function). or in SQL—an SQL function). An external UDF cannot be defined as a column function. System-generated functions are always scalar functions. COBOL. external. As such. Writing User-Defined Functions (UDFs)” on page 185. the SET PATH statement. However. These are simply functions registered to the database that themselves reference another function. a sourced UDF is defined to be a column function if it is sourced on one of the built-in column functions. These are also called aggregating functions in DB2. The latter is useful for distinct types. and UDTs as parameters. v SQL UDFs. you could define a UDF. this registration step does everything necessary to define the function to the database. AVG(SHOESIZE). if a distinct type SHOESIZE exists that is defined with base type INTEGER. Writing User-Defined Functions (UDFs)” on page 185 for more information on writing external functions. the CREATE FUNCTION statement contains everything necessary to 160 DB2 UDB for AS/400 SQL Programming V4R4 . making them quite portable. In the case of source functions. must understand the interface between the program and the database.| | | | | | | | | | | | | | | | | | | In addition. SQL UDFs provide several advantages: – They are written in SQL. The concept of path. The implementation of each type is considerably different. besides knowing the high level language and how to develop code in it. and subsequent manipulation of them in the function itself. external UDFs require that the UDF writer. – They allow the passing of large objects. See “Chapter 9. Some built-in functions are column functions. More information about SQL functions can be found in “Chapter 9. the database will invoke the program or service program whenever the function is referenced in a DML statement. Regardless of which type of UDF is being created. and SQL. An example of a column function is the built-in function AVG(). v External functions. Registering the UDF with DB2. A column function receives a set of like values (a column of data) and returns a single value answer from this set of values. They. Implementing UDFs There are three types of UDFs: sourced. or RPG. as a column function sourced on the existing built-in column function. Scalar UDFs can either be external (coded in a programming language such as C. These are references to programs and service programs written in a high level language such as C. nothing more is required in implementing these functions than registering them to the database using the CREATE FUNCTION statement. Once the function is registered to the database. A scalar function returns a single value answer each time it is called. As such. in effect. map the sourced function. they all need to be registered to the database using the CREATE FUNCTION statement. AVG(INTEGER). with no need to worry about details of actual parameter passing. as are many built-in functions. These options help to more specifically identify to the database the intention of the function and how calls to the database can be optimized. except that the syntax of the CREATE statement is much more complex (contains actual SQL executable code). See “Chapter 9. ALLOW PARALLEL. For information on testing your UDF. | | | | | | | | | | | | | | | | | After these steps are successfully completed. to avoid any problems with running your UDF. The statement allows you to specify the language and name of the program. The examples include: v Example: Exponentiation v Example: String Search v v v v Example: String Search over UDT Example: External Function with UDT Parameter Example: AVG over a UDT Example: Counting Example: Exponentiation Suppose you have written an external UDF to perform exponentiation of floating point values. your UDF is ready for use in data manipulation language (DML) or data definition language (DDL) statements such as CREATE VIEW. CREATE FUNCTION MATH. Using the Object-Relational Capabilities 161 . Writing User-Defined Functions (UDFs)” on page 185. See “Registering UDFs” for more information. you are encouraged to write and test it extensively before registering it. It is possible to define the UDF prior to actually writing it. For external UDFs.define the function as well. However. You can find detailed explanations for this statement and its options in the DB2 UDB for AS/400 SQL Reference. Debugging the UDF. Registering UDFs A UDF must be registered in the database before the function can be recognized and used by the database. Examples of Registering UDFs | | | | | | | | | | | | | | | | | The examples which follow illustrate a variety of typical situations where UDFs can be registered. the CREATE FUNCTION statement only registers the function to the database. Writing User-Defined Functions (UDFs)” on page 185.EXPON (DOUBLE. the supporting code that actually implements the function must be written separately. see “Chapter 9. along with options such as DETERMINISTIC. You should register the UDF to DB2 after you have written and completely tested the actual code. DOUBLE) RETURNS DOUBLE EXTERNAL NAME 'MYLIB/MYPGM(MYENTRY)' LANGUAGE C PARAMETER STYLE DB2SQL NO SQL Chapter 8. 2. and RETURN NULLS ON NULL INPUT. and wish to register it in the MATH schema. You can register a UDF using the CREATE FUNCTION statement. VARCHAR(200)) RETURNS INTEGER CAST FROM FLOAT SPECIFIC "willie_fblob_feb95" EXTERNAL NAME 'MYLIB/MYPGM(FINDSTR)' LANGUAGE C PARAMETER STYLE DB2SQL NO SQL DETERMINISTIC NO EXTERNAL ACTION 162 DB2 UDB for AS/400 SQL Programming V4R4 . Willie. has written a UDF to look for the existence of a given short string. Additionally. This is desirable since you want the result to be NULL if either argument is NULL. The UDF returns the position of the string within the CLOB if it finds the string. Because the UDF was not written to handle NULL values. VARCHAR(200)) RETURNS INTEGER CAST FROM FLOAT SPECIFIC "willie_find_feb95" EXTERNAL NAME 'MYLIB/MYPGM(FINDSTR)' LANGUAGE C PARAMETER STYLE DB2SQL NO SQL DETERMINISTIC NO EXTERNAL ACTION RETURNS NULL ON NULL INPUT | | | | | | | | | | Note that a CAST FROM clause is used to specify that the UDF body really returns a FLOAT value but you want to cast this to INTEGER before returning the value to the statement which used the UDF. you use the RETURNS NULL ON NULL INPUT. passed as an argument. the NO SCRATCHPAD and NO FINAL CALL default values are used. Also. Willie has written the function to return a FLOAT result. within a given CLOB value. As discussed in the DB2 UDB for AS/400 SQL Reference. Since you do not require a scratchpad and no final call is necessary. Suppose you know that when it is used in SQL. the INTEGER built-in function can perform this cast for you. You can create the following function: CREATE FUNCTION FINDSTRING (CLOB(500K). the system uses the RETURNS NULL ON NULL INPUT default value. you define another FINDSTRING taking BLOB as the first parameter: CREATE FUNCTION FINDSTRING (BLOB(500K).| | | | | | | | | DETERMINISTIC NO EXTERNAL ACTION RETURNS NULL ON NULL INPUT ALLOW PARALLEL In this example. the ALLOW PARALLELISM default value is used. As there is no reason why EXPON cannot be parallel. you use the NO SCRATCHPAD and NO FINAL CALL default values. the ALLOW PARALLEL value is specified. you wish to provide your own specific name for the function and later reference it in DDL (see “Example: String Search over UDT” on page 163). which is also passed as an argument. Example: BLOB String Search | | | | | | | | | | | | Because you want this function to work on BLOBs as well as on CLOBs. or zero if it does not. As there is no reason why FINDSTRING cannot be parallel. Example: String Search Your associate. And because there is no scratchpad. it should always return an INTEGER. so you create another FINDSTRING function. This function is sourced on the FINDSTRING which operates on BLOB values in “Example: BLOB String Search” on page 162. Using the Object-Relational Capabilities 163 . Because you are using the SOURCE clause. Because this is an unqualified reference. this function needs to generate the cost to build the boat in the required currency. managed outside of DB2. Say you are satisfied with the FINDSTRING functions from “Example: BLOB String Search” on page 162. You wish to provide your own specific name for possible later reference in DDL. You also want FINDSTRING to operate on values having data type BOAT. and the answer depends on what it finds in this file. CREATE FUNCTION BOAT_COST (BOAT) RETURNS INTEGER EXTERNAL NAME 'MYLIB/COSTS(BOATCOST)' LANGUAGE C PARAMETER STYLE DB2SQL NO SQL NOT DETERMINISTIC NO EXTERNAL ACTION | | Observe that CAST FROM and SPECIFIC are not specified. Even though internally. but now you have defined a distinct type BOAT with source type BLOB. Example: External Function with UDT Parameter You have written another UDF to take a BOAT and examine its design attributes and generate a cost for the boat in Canadian dollars. the same source code can be used. but that NOT DETERMINISTIC is specified. you cannot use the EXTERNAL NAME clause or any of the related keywords specifying function attributes. or US dollars. Example: String Search over UDT This example is a continuation of the previous example.| This example illustrates overloading of the UDF name. or the reference will not be resolved. This makes the function NOT DETERMINISTIC. VARCHAR(200)) RETURNS INT SPECIFIC "slick_fboat_mar95" SOURCE SPECIFIC "willie_fblob_feb95" Note that this FINDSTRING function has a different signature from the FINDSTRING functions in “Example: BLOB String Search” on page 162. the schema in which this source function resides must be in the function path. length followed by data. DB2 does not check if the UDF using a particular function body is in any way consistent with any other UDF using the same body. Canadian dollars. Finally. so there is no problem overloading the name. and shows that multiple UDFs can share the same body. Note that although a BLOB cannot be assigned to a CLOB. Note the further overloading of FINDSTRING in this example: CREATE FUNCTION FINDSTRING (BOAT. or Japanese yen. the labor cost may be priced in German marks. Chapter 8. This means it has to get current exchange rate information from the exchange_rate file. observe that in identifying the source function you are using the specific function name explicitly provided in “Example: BLOB String Search” on page 162. There is no programming problem in the above example as the programming interface for BLOB and CLOB between DB2 and UDF is the same. These attributes are taken from the source function. There are a few restrictions of UDF usage. DLURLCOMPLETE. and DLURLSERVER cannot be referenced in an ORDER BY or GROUP BY clause. In this case.AVG(DECIMAL(9. 164 DB2 UDB for AS/400 SQL Programming V4R4 . SQL UDFS and the built-in functions DLVALUE. This function takes no SQL arguments. Example: Counting Your simple counting function returns a 1 the first time and increments the result by one each time it is called. DLURLPATH. or DLURLSERVER. Since the COUNTER function requires that a single scratchpad be used to operate properly.2)) Note that in the SOURCE clause you have qualified the function name. and by definition it is a NOT DETERMINISTIC function since its answer varies from call to call. DLURLPATHONLY. but since DECIMAL is the source type for CANADIAN_DOLLAR you know these casts will work. DLURLSCHEME.Example: AVG over a UDT | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | This example implements the AVG column function over the CANADIAN_DOLLAR distinct type. Check constraints also cannot contain references to the built-in functions DLVALUE. and each time it is invoked it increments this value and returns it. DLURLPATHONLY. just empty parentheses. DLURLSCHEME. which is sufficient for a counter. Using UDFs Scalar and column UDFs can be invoked within an SQL statement almost everywhere that an expression is valid. CREATE FUNCTION COUNTER () RETURNS INT EXTERNAL NAME 'MYLIB/MYFUNCS(CTR)' LANGUAGE C PARAMETER STYLE DB2SQL NO SQL NOT DETERMINISTIC NOT FENCED SCRATCHPAD 4 DISALLOW PARALLEL Note that no parameter definitions are provided. just in case there might be some other AVG function lurking in your SQL path. It uses the scratchpad to save the last value returned. The ability to do this depends on being able to cast from DECIMAL to CANADIAN_DOLLAR and vice versa. and uses the default specification of NO FINAL CALL. the size of the scratchpad is set to only 4 bytes. DISALLOW PARALLEL is added to prevent DB2 from operating it in parallel. unless the SQL statement is read-only and allows temporary processing (ALWCPYDTA(*YES) or (*OPTIMIZE). Strong typing prevents you from using the built-in AVG function on a distinct type. See “Example: Money” on page 171 for the definition of CANADIAN_DOLLAR. v External UDFs. however: v UDFs and system generated functions cannot be specified in check constraints. It turns out that the source type for CANADIAN_DOLLAR was DECIMAL. The above function specifies SCRATCHPAD. DLURLCOMPLETE. CREATE FUNCTION AVG (CANADIAN_DOLLAR) RETURNS CANADIAN_DOLLAR SOURCE "QSYS2". and so you implement the AVG by sourcing it on the AVG(DECIMAL) built-in function. DLURLPATH. Both the position of the arguments and the function definition must conform to the function body itself.BLOOP(:hostvar) "search_schema"(CURRENT PATH. 'GENE') SUBSTR(COLUMN2. The resolution of any Data Manipulation Language (DML) reference to a function uses the function resolution algorithm.USER. 1) CTR() FLOOR(FLOAT_COLUMN) PABLO. and are expressions which may contain: v A column name. function_name can be either an unqualified or a qualified function name. whether it is a UDF. Referring to Functions Each reference to a function. 0. The arguments can number from 0 to 90. DB2 does not attempt to shuffle arguments to better match a function definition. You can find the details for both of these concepts in the DB2 UDB for AS/400 SQL Reference. 0. 1. Refer to “UDF Concepts” on page 158 for a summary of the use and importance of the path and the function resolution algorithm. functions cannot be qualified. expression ) | | | | | | | | | | | | | | | | In the above.BLOOP(A+B) PABLO. so it is important to understand how it works.The DB2 UDB for AS/400 SQL Reference discusses all these contexts in detail. qualified or unqualified v A constant v A host variable v A special register v A parameter marker with a CAST function v An expression v A function The position of the arguments is important and must conform to the function definition for the semantics to be correct. Examples of Function Invocations | | | | | | | | | | | | Some valid examples of function invocations are: AVG(FLOAT_COLUMN) BLOOP(COLUMN1) BLOOP(FLOAT_COLUMN + CAST(? AS INTEGER)) BLOOP(:hostvar :indicvar) BRIAN. Using the Object-Relational Capabilities 165 . The discussion and examples used in this section focus on relatively simple SELECT statement contexts.8. Note that when using the *SYS naming convention. but note that their use is not restricted to these contexts. or a built-in function. contains the following syntax: function_name ( ALL DISTINCT .3) Chapter 8. and DB2 does not attempt to determine the semantics of the individual function parameters.PARSE(CONCAT(CHAR_COLUMN. BLOOP is thus overloaded within the PABLO schema.AVG(QSYS2. the second BLOOP will be chosen. yet you can pass it a SMALLINT argument. and if column1 is not one of the numeric types. the statement will fail. for example INTEGER. If for some reason you want to invoke the second BLOOP with a SMALLINT or INTEGER argument. column1. function selection will resolve to the first BLOOP. It does not matter that user SERGE has defined a BLOOP function. depending on your exact intent: | | | | SELECT PABLO. and then the function selection logic can proceed: BLOOP(CAST(? AS INTEGER)) Using Qualified Function Reference If you use a qualified function reference. see the DB2 UDB for AS/400 SQL Reference) and DB2 performs the appropriate data value conversions.. Several points about this example: 1.SALARY)) QSYS2.. On the other hand if column1 is either SMALLINT or INTEGER. depending on the data type of the argument.. or whether or not there is a built-in BLOOP function. In this case.LENGTH(COLUMN3)) Using Parameter Markers in Functions An important restriction involves parameter markers. You can use the CAST specification to provide a type for the parameter marker. you have the following statement: SELECT PABLO.BLOOP(INTEGER(COLUMN1)) FROM T SELECT PABLO. it cannot resolve the reference. 2. The function selection algorithm supports promotions among the built-in data types (for details. Alternatively. you cannot simply code the following: BLOOP(?) As the function selection logic does not know what data type the argument may turn out to be.SALARY)) QSYS2. and the function selection algorithm would choose the best BLOOP. both of the PABLO. The first BLOOP is defined with an INTEGER parameter.| | | | QSYS2.. you have to take an explicit action in your statement as follows: SELECT PABLO.BLOOP(FLOOR(COLUMN1)) FROM T You should investigate these other functions in the DB2 UDB for AS/400 SQL Reference. you restrict DB2’s search for a matching function to that schema. The INTEGER function is a built-in function in the QSYS2 schema. you have your choice of explicit actions. It illustrates argument promotion.BLOOP(DOUBLE(COLUMN1)) FROM T 3. if you want to invoke the first BLOOP with a DECIMAL or DOUBLE argument.FLOOR(EMP. For example. CREATE FUNCTION BLOOP (DOUBLE) RETURNS . Now suppose that user PABLO has defined two BLOOP functions in his schema: CREATE FUNCTION BLOOP (INTEGER) RETURNS .BLOOPs take numeric arguments.BLOOP(COLUMN1) FROM T Only the BLOOP functions in schema PABLO are considered. 166 DB2 UDB for AS/400 SQL Programming V4R4 . while if column1 is DECIMAL or DOUBLE.11.SUBSTR(COLUMN2.FLOOR(AVG(EMP. "QSYS2". instead of a qualified function reference. suppose you have forgotten that you are using a script for precompiling and binding which you previously wrote for another purpose. and your statement would execute without error. as the deciding factor if two identically good matches are found in different schemas. the function selection could very well resolve to Kathy’s function. DB2’s search for a matching function normally uses the function path to qualify the reference. however. illustrated by the examples at the end of “Using Qualified Function Reference” on page 166. This is generally true for built-in functions as well as UDFs. it is important that you know what your function path is. In this script."PABLO" However. conflicting functions exist in the schemas of your current function path. Chapter 8. If the following default function path is used. the first BLOOP is chosen (since column1 is INTEGER). a best match among these functions. the function selection algorithm looks at all the applicable functions. and you want and expect one of them to be chosen. you explicitly coded your SQLPATH parameter to specify the following function path for another reason that does not apply to your current work: "KATHY".Using Unqualified Function Reference | | | | | | | | | | | | | | | | If."QSYS". Summary of Function References For both qualified and unqualified function references. in the case of an unqualified reference only. both built-in and user-defined. even references to the same function. and what. You are not notified because DB2 assumes that you know what you are doing. if they are unqualified for *SQL naming. Using the Object-Relational Capabilities 167 ."PABLO" If Kathy has written a BLOOP function for her own purposes. where COLUMN1 is data type INTEGER: SELECT BLOOP(COLUMN1) FROM T You have created the two BLOOP functions cited in “Using Qualified Function Reference” on page 166. In the case of the DROP FUNCTION or COMMENT ON FUNCTION functions. It becomes your responsibility to identify the incorrect output from your statement and make the required correction. (Applicable functions means functions in the named schema for a qualified reference. or failing that. the reference is qualified using the current authorization ID. or *LIBL for *SYS naming.) The algorithm looks for an exact match. if there is no conflicting BLOOP in QSYS or QSYS2: "QSYS". The details of the algorithm can be found in the DB2 UDB for AS/400 SQL Reference. you use an unqualified function reference."QSYS2". or functions in the schemas of the function path for an unqualified reference. suppose you are PABLO and your static SQL statement is as follows. The current function path is used. if any. is the fact that function references can be nested. there are some limitations when column functions are involved. For example. An interesting feature. that have: v The given name v The same number of defined parameters as arguments in the function reference v Each parameter identical to or promotable from the type of the corresponding argument. Thus. Now suppose you write the following SELECT statement: SELECT 'ABCDEFG' CONCAT BLOOP(SMALLINT_COL) FROM T | | | | | | | | | | Because the best match. DB2 will materialize the entire LOB value in storage before invoking such a function.. is the first BLOOP defined above. You can define the following UDF: CREATE FUNCTION "+" (BOAT.. =. Because this BLOOP returns an INTEGER. in this way. Look at these BLOOP functions. For example. BOAT) RETURNS . or DBCLOB. the outer BLOOP also resolves to the first BLOOP. the second operand of the CONCAT resolves to data type INTEGER. resolved using the SMALLINT argument. even if the source of the value is a LOB locator host variable.. /* LOB host var */ SQL TYPE IS CLOB_LOCATOR clob_locator1. The statement fails because CONCAT demands string arguments.. the inner BLOOP reference resolves to the second BLOOP defined above.. CLOB.. A few additional points important for function references are: v You can define a function with the name of one of the SQL operators. /* LOB locator host var */ char string[40]. CREATE FUNCTION BLOOP (DOUBLE) RETURNS INTEGER . CREATE FUNCTION BLOOP (DOUBLE) RETURNS CHAR(10). the inner bloop reference resolves to the first BLOOP defined above. modified a bit from before: CREATE FUNCTION BLOOP (INTEGER) RETURNS INTEGER .Refining an earlier example: CREATE FUNCTION BLOOP (INTEGER) RETURNS INTEGER .. if column1 is a SMALLINT or INTEGER column. If the first BLOOP was not present. the other BLOOP would be chosen and the statement execution would be successful. IN. Then you can write the following valid SQL statement: SELECT "+"(BOAT_COL1. SQL TYPE IS CLOB(150K) clob150K . 168 DB2 UDB for AS/400 SQL Programming V4R4 . Alternatively. In this case. Because this BLOOP returns an INTEGER. consider the following fragment of a C language application: EXEC SQL BEGIN DECLARE SECTION. Now consider the following DML statement: SELECT BLOOP( BLOOP(COLUMN1)) FROM T If column1 is a DECIMAL or DOUBLE column. the outer BLOOP resolves to the first BLOOP... BOAT_COL2) FROM BIG_BOATS WHERE BOAT_OWNER = 'Nelson Mattos' Note that you are not permitted to overload the built-in conditional operators such as >. For example. and so on.. LIKE. suppose you can attach some meaning to the "+" operator for values which have distinct type BOAT. you are seeing nested references to the same function. v The function selection algorithm does not consider the context of the reference in resolving to a particular function. /* string host var */ EXEC SQL END DECLARE SECTION. v UDFs can be defined with parameters or results having any of the LOB types: BLOB. Distinct type values which originate in a host variable and which are used as arguments to a UDF which has its corresponding parameter defined as a distinct type. Extensibility. which takes an object of type BOAT as its argument. If there are multiple BOAT distinct types in the database... Thus. You can also use this capability on UDF parameters or results which have a distinct type that is based on a LOB... both of the following are valid in the program: . So. SELECT BOAT_COST (BOAT(:ship)) FROM .. SELECT BOAT_COST (CAST(:ship AS BOAT)) FROM . v Non-SQL UDF parameters or results which have one of the LOB types can be created with the AS LOCATOR modifier. Note that the argument to such a function can be any LOB value of the defined type.. Both of the following statements correctly resolve to the BOAT_COST function. a LOB LOCATOR is passed to the UDF... EXEC SQL END DECLARE SECTION. SELECT FINDSTRING (:clob150K. There is no host language type for distinct types. Instead. SELECT FINDSTRING (:clob_locator1. v UDFs can be defined with distinct types as parameters or as the result. This capability is limited to non-SQL UDFs. the host variable :ship holds the BLOB value that is to passed to the BOAT_COST function: EXEC SQL BEGIN DECLARE SECTION. .. You are no longer restricted to using system-supplied built-in data types to model your businesses and capture the semantics of your data.| | | | | | | | | | | | | | | Either host variable :clob150K or :clob_locator1 is valid as an argument for a function whose corresponding parameter is defined as CLOB(500K). consider the BOAT distinct type which is defined over a BLOB. it does not have to be a host variable defined as one of the LOCATOR types.. In the following fragment of a C language application. because both cast the :ship host variable to type BOAT: .. . SQL TYPE IS BLOB(150K) ship. Otherwise your results may be ambiguous. or BOAT UDFs in other schema. The use of host variable locators as arguments is completely unrelated to the use of AS LOCATOR in UDF parameters and result definitions. you must exercise care with your function path. and consider the BOAT_COST UDF from “Example: External Function with UDT Parameter” on page 163. DB2’s strong typing necessitates this.. must be explicitly cast to the distinct type by the user. Chapter 8. Otherwise your results may be ambiguous. Why Use UDTs? There are several benefits associated with UDTs: 1. User-defined Distinct Types (UDT) Enabling you to define new data types to DB2 gives you considerable power and extends your capabilities with the built-in data types. A user-defined distinct type is the DB2 mechanism you can use for this purpose.) DB2 will pass the value to the UDF in the format of the source data type of the distinct type.. (Earlier examples have illustrated this. the entire LOB value is not materialized prior to invocation.. :string) FROM . :string) FROM . referring to the FINDSTRING defined in “Example: String Search” on page 162.. Using the Object-Relational Capabilities 169 . In this case.. The definition of user-defined functions on types can augment the functionality provided to manipulate your UDT at any time. Distinct types are highly integrated into the database manager. Extensible behavior. These functions are important for the manipulation of UDTs in queries. 2. 7. Encapsulation. Strong typing insures that your UDTs will behave appropriately. Previously defined UDTs cannot be used as source types of other UDTs. The source type of the UDT is the type used by DB2 to internally represent the UDT. need to be defined with a CREATE statement. 3. (See “User-Defined Functions (UDF)” on page 156) 6. indexes. you can indefinitely increase the set of types provided by DB2 to support your applications. Detailed explanations for the statement syntax and all its options are found in the DB2 UDB for AS/400 SQL Reference. 5. Flexibility. For this reason. See the DB2 UDB for AS/400 SQL Reference for a discussion of when additional casts to the UDTs are generated. Performance. 4. the cast function called DOUBLE is created. for built-in data types. comparison operators. This provides flexibility in the implementation since running applications do not depend on the internal representation that you chose for your type. they share the same efficient code used to implement built-in functions. it must be a built-in data type. and UDFs. Because distinct types are internally represented the same way as built-in data types. The name of the new UDT can be a qualified or an unqualified name. | | | | | For the CREATE DISTINCT TYPE statement. The behavior of your UDTs is restricted by the functions and operators that can be applied on them. DB2 always generates cast functions to: v Cast from the UDT to the source type. etc. Defining a UDT UDTs. UDTs are the foundation for most object-oriented features. using the standard name of the source type. if you create a distinct type based on FLOAT. You can specify any semantics and behavior for your new type by using user-defined functions (UDFs) to augment the diversity of the types available in the system. 2. As part of a UDT definition. It guarantees that only functions defined on your UDT can be applied to instances of the UDT. For example.By defining new types. Foundation for object-oriented extensions. 170 DB2 UDB for AS/400 SQL Programming V4R4 . v Cast from the source type to the UDT. indexes. like other objects such as tables. Consistent behavior. note that: 1. Use the CREATE DISTINCT TYPE statement to define your new UDT. They represent the most important step towards object-oriented extensions. Following are examples using CREATE TABLE: v Example: Sales v Example: Application Forms Example: Sales Suppose you want to define tables to keep your company’s sales in different countries as follows: CREATE TABLE US_SALES (PRODUCT_ITEM INTEGER. For information on how unqualified function references are resolved.2) CREATE DISTINCT TYPE GERMAN_MARK AS DECIMAL (9. except if the type name or function is v Created v Dropped v Commented on. MONTH INTEGER CHECK (MONTH BETWEEN 1 AND 12). Remember that conversions are necessary whenever you want to compare values of different currencies. TOTAL US_DOLLAR) Chapter 8. Examples of Using CREATE DISTINCT TYPE The following are examples of using CREATE DISTINCT TYPE: v Example: Money v Example: Resume Example: Money Suppose you are writing applications that need to handle different currencies and wish to ensure that DB2 does not allow these currencies to be compared or manipulated directly with one another in queries. Because these functions cannot be applied to regular character strings (because they are certainly not able to find the information they are supposed to return).2) CREATE DISTINCT TYPE CANADIAN_DOLLAR AS DECIMAL (9. see “Using Qualified Function Reference” on page 166.Resolving Unqualified UDTs The function path is used to resolve any references to an unqualified type name or function.APPLICATION_FORM AS CLOB(32K) Defining Tables with UDTs After you have defined several UDTs. Using the Object-Relational Capabilities 171 . one for each currency that you may need to represent: | | | | | | | | | | | CREATE DISTINCT TYPE US_DOLLAR AS DECIMAL (9. you can start defining tables with columns whose types are UDTs.2) Example: Resume Suppose you would like to keep the form filled by applicants to your company in a DB2 table and you are going to use functions to extract the information from these forms. you define a UDT to represent the filled forms: CREATE DISTINCT TYPE PERSONAL. YEAR INTEGER CHECK (YEAR > 1985). So you define as many UDTs as you need. you do not want this same function to be used to convert German marks to Canadian dollars because it will certainly return the wrong amount. Note that the above examples use check constraints. Example: Application Forms Suppose you need to define a table where you keep the forms filled out by applicants as follows: | | | | | | | | | | | CREATE TABLE APPLICATIONS (ID INTEGER. for example. As a consequence of strong typing. For the same reason. For example. NAME VARCHAR (30). In the same sense. Remember that whenever type and function names are not fully qualified. YEAR INTEGER CHECK (YEAR > 1985). MONTH INTEGER CHECK (MONTH BETWEEN 1 AND 12). If you want to compare instances of UDTs with instances of another type.APPLICATION_FORM) You have fully qualified the UDT name because its qualifier is not the same as your authorization ID and you have not changed the default function path. DB2 will not let you apply functions defined on other types to UDTs. YEAR INTEGER CHECK (YEAR > 1985). UDT instances with instances of the UDT source type. you have to cast the instances of one or the other type. APPLICATION_DATE DATE. if you have defined a function to convert US dollars to Canadian dollars according to the current exchange rate. DB2 searches through the schemas listed in the current function path and looks for a type or function name matching the given unqualified name. TOTAL CANADIAN_DOLLAR) CREATE TABLE GERMAN_SALES (PRODUCT_ITEM INTEGER. DB2 does not allow you to write queries that compare. .CREATE TABLE CANADIAN_SALES (PRODUCT_ITEM INTEGER. 172 DB2 UDB for AS/400 SQL Programming V4R4 . FORM PERSONAL. Manipulating UDTs One of the most important concepts associated with UDTs is strong typing. MONTH INTEGER CHECK (MONTH BETWEEN 1 AND 12). TOTAL GERMAN_MARK) The UDTs in the above examples are created using the same CREATE DISTINCT TYPE statements in “Example: Money” on page 171. you have to cast the UDT instance to the type of the parameter of a function that is not defined on a UDT if you want to apply this function to a UDT instance. For information on check constraints see the DB2 UDB for AS/400 SQL Reference. Strong typing guarantees that only functions and operators defined on the UDT can be applied to its instances. Strong typing is important to ensure that the instances of your UDTs are correct. accesses the exchange rate file. dollars. dollars. you have used the cast function provided by DB2 to cast from DECIMAL to US dollars.Examples of Manipulating UDTs The following are examples of manipulating UDTs: v Example: Comparisons Between UDTs and Constants v Example: Casting Between UDTs v Example: Comparisons Involving UDTs v v v v v Example: Sourced UDFs Involving UDTs Example: Assignments Involving UDTs Example: Assignments in Dynamic SQL Example: Assignments Involving Different UDTs Example: Use of UDTs in UNION Example: Comparisons Between UDTs and Constants Suppose you want to know which products sold more than US $100 000.S. and returns the corresponding amount in U. Either way you decide to cast. DECIMAL) directly. However. The UDTs representing different currencies have been defined as DECIMAL. Suppose you can obtain the current exchange rate from a file managed outside of DB2. 1992 (7/92). your UDF should be defined as follows: | | | | | | CREATE FUNCTION CDN_TO_US_DOUBLE(DOUBLE) RETURNS DOUBLE EXTERNAL NAME 'MYLIB/CURRENCIES(C_CDN_US)' LANGUAGE C PARAMETER STYLE DB2SQL NO SQL NOT DETERMINISTIC Chapter 8. Your UDF will need to receive and return DOUBLE values. or the functional notation. you can use the cast specification notation to perform the casting. from or to the UDT.S. Thus. since this is the only data type provided by C that allows the representation of a DECIMAL value without losing the decimal precision.00 in the US in the month of July. That is. the one to cast from US dollars to DECIMAL) and cast the column total to DECIMAL. such a UDF may appear easy to write. you could have written the above query as: SELECT PRODUCT_ITEM FROM US_SALES WHERE TOTAL > CAST (100000 AS us_dollar) AND MONTH = 7 AND YEAR = 1992 Example: Casting Between UDTs Suppose you want to define a UDF that converts Canadian dollars to U. At first glance. SELECT PRODUCT_ITEM FROM US_SALES WHERE TOTAL > US_DOLLAR (100000) AND month = 7 AND year = 1992 Because you cannot compare US dollars with instances of the source type of US dollars (that is. You can also use the other cast function provided by DB2 (that is. not all C compilers support DECIMAL values. Using the Object-Relational Capabilities 173 . You would then define a UDF that obtains a value in Canadian dollars. and then to U. so you declare it as NOT DETERMINISTIC.S. CANADIAN_SALES AS CDN. That is. where C1 is a column whose type is Canadian dollars. The first brings the DOUBLE values to a DECIMAL representation. The DECIMAL values must be cast to DOUBLE.TOTAL) AND US. dollars would be similar to the example above: | | | | | | | | | | | | | | CREATE FUNCTION GERMAN_TO_US_DOUBLE(DOUBLE) RETURNS DOUBLE EXTERNAL NAME 'MYLIB/CURRENCIES(C_GER_US)' LANGUAGE C PARAMETER STYLE DB2SQL NO SQL NOT DETERMINISTIC CREATE FUNCTION GERMAN_TO_US_DEC (DECIMAL(9.2) SOURCE CDN_TO_US_DOUBLE (DOUBLE) CREATE FUNCTION US_DOLLAR (CANADIAN_DOLLAR) RETURNS US_DOLLAR SOURCE CDN_TO_US_DEC (DECIMAL()) Note that an invocation of the US_DOLLAR function as in US_DOLLAR(C1). you need to define two sourced UDFs. dollars) that is cast to decimal.2)) RETURNS DECIMAL(9. you define the following: CREATE FUNCTION CDN_TO_US_DEC (DECIMAL(9.PRODUCT_ITEM = CDN.MONTH = 3 AND US. The question now is.TOTAL) AND US.PRODUCT_ITEM.S. Such casts are performed automatically by DB2 anytime you define sourced UDFs.S. US. C1 (in Canadian dollars) is cast to decimal which in turn is cast to a double value that is passed to the CDN_TO_US_DOUBLE function.TOTAL > US_DOLLAR (GERMAN.PRODUCT_ITEM AND US. Therefore.PRODUCT_ITEM = GERMAN. has the same effect as invoking: US_DOLLAR (DECIMAL(CDN_TO_US_DOUBLE (DOUBLE (DECIMAL (C1))))) That is.2)) RETURNS DECIMAL(9. GERMAN_SALES AS GERMAN WHERE US.S.S. dollars may change between two invocations of the UDF. whose parameter and return type do not exactly match the parameter and return type of the source function. This function accesses the exchange rate file and returns a double value (representing the amount in U.2) SOURCE GERMAN_TO_US_DOUBLE(DOUBLE) CREATE FUNCTION US_DOLLAR(GERMAN_MARK) RETURNS US_DOLLAR SOURCE GERMAN_TO_US_DEC (DECIMAL()) Example: Comparisons Involving UDTs Suppose you want to know which products sold more in the US than in Canada and Germany for the month of March. dollars from it? The Canadian dollars must be cast to DECIMAL values. A function to convert German marks to U.| The exchange rate between Canadian and U. You also need to have the returned DOUBLE value cast to DECIMAL and the DECIMAL value cast to U. 1989 (3/89): SELECT US.YEAR = 1989 174 DB2 UDB for AS/400 SQL Programming V4R4 .S. dollars.TOTAL > US_DOLLAR (CDN. dollars. The second brings the DECIMAL values to the UDT.TOTAL FROM US_SALES AS US.PRODUCT_ITEM AND US. how do you pass Canadian dollars to this UDF and get U. AND AND AND AND CDN. EXEC SQL END DECLARE SECTION. :hv_form) You do not explicitly invoke the cast function to convert the character string to the UDT personal. You would like to obtain the total sales in US dollars: SELECT PRODUCT_ITEM. You have defined a host variable containing the character string value used to represent the filled form: EXEC SQL BEGIN DECLARE SECTION.MONTH = 3 GERMAN. Example: Sourced UDFs Involving UDTs Suppose you have defined a sourced UDF on the built-in SUM function to support SUM on German Marks: CREATE FUNCTION SUM (GERMAN_MARKS) RETURNS GERMAN_MARKS SOURCE SYSIBM. SQL TYPE IS CLOB(32K) hv_form. US_DOLLAR (SUM (TOTAL)) FROM GERMAN_SALES WHERE YEAR = 1994 GROUP BY PRODUCT_ITEM You could not write SUM (us_dollar (total)). CURRENT DATE. you can use parameter markers as follows: EXEC SQL BEGIN DECLARE SECTION.SUM (DECIMAL()) You want to know the total of sales in Germany for each product in the year of 1994. long id. and the UDF to cast the amount in German Marks to US dollars. you use the UDF to cast the amount in Canadian dollars to US dollars. /* Code to fill hv_form */ INSERT INTO APPLICATIONS VALUES (134523. 'Peter Holland'.YEAR = 1989 GERMAN. That is.YEAR = 1989 Because you cannot directly compare US dollars with Canadian dollars or German Marks. SQL TYPE IS CLOB(32K) form. Using the Object-Relational Capabilities 175 .MONTH = 3 CDN. You cannot cast them all to DECIMAL and compare the converted DECIMAL values because the amounts are not monetarily comparable. unless you had defined a SUM function on US dollar in a manner similar to the above. EXEC SQL END DECLARE SECTION. This is because DB2 lets you assign instances of the source type of a UDT to targets having that UDT. /* Code to fill host variables */ Chapter 8. the amounts are not in the same currency.application_form . char command[80]. Example: Assignments Involving UDTs Suppose you want to store the form filled by a new applicant into the database. Example: Assignments in Dynamic SQL If you want to use the same statement given in “Example: Assignments Involving UDTs” in dynamic SQL. char name[30]. :form. Example: Assignments Involving Different UDTs Suppose you have defined two sourced UDFs on the built-in SUM function to support SUM on US and Canadian dollars. US_DOLLAR (SUM (TOTAL)) FROM GERMAN_SALES WHERE YEAR = 1994 GROUP BY PRODUCT_ITEM INSERT INTO CANADIAN_SALES_94 SELECT PRODUCT_ITEM. TOTAL US_DOLLAR) CREATE TABLE CANADIAN_SALES_94 (PRODUCT_ITEM INTEGER.SUM (DECIMAL()) Now suppose your supervisor requests that you maintain the annual total sales in US dollars of each product and in each country. you cannot specify that the type of a parameter marker is a UDT. Remember that you cannot declare a host variable of a UDT type.strcpy(command. TOTAL US_DOLLAR) INSERT INTO US_SALES_94 SELECT PRODUCT_ITEM. SUM (TOTAL) FROM US_SALES WHERE YEAR = 1994 GROUP BY PRODUCT_ITEM INSERT INTO GERMAN_SALES_94 SELECT PRODUCT_ITEM. Therefore.SUM (DECIMAL()) CREATE FUNCTION SUM (US_DOLLAR) RETURNS US_DOLLAR SOURCE SYSIBM. ?. US_DOLLAR (SUM (TOTAL)) FROM CANADIAN_SALES WHERE YEAR = 1994 GROUP BY PRODUCT_ITEM 176 DB2 UDB for AS/400 SQL Programming V4R4 . ?)"). a type that is assignable to the UDT column. in separate tables: CREATE TABLE US_SALES_94 (PRODUCT_ITEM INTEGER. You made use of DB2’s cast specification to tell DB2 that the type of the parameter marker is CLOB(32K). EXEC SQL EXECUTE APP_INSERT USING :id. TOTAL US_DOLLAR) CREATE TABLE GERMAN_SALES_94 (PRODUCT_ITEM INTEGER. :name."(?. since host languages do not support UDTs."INSERT INTO APPLICATIONS VALUES"). similar to the UDF sourced on German Marks in “Example: Sourced UDFs Involving UDTs” on page 175: CREATE FUNCTION SUM (CANADIAN_DOLLAR) RETURNS CANADIAN_DOLLAR SOURCE SYSIBM. EXEC SQL PREPARE APP_INSERT FROM :command. strcat(command. CURRENT DATE. and LOBs). as you will see in this section. Each of these types have a name. UDFs. Consequently. To have better control and organization of your related UDTs and UDFs. you can define the behavior of the new type. and behavior. Example: Use of UDTs in UNION Suppose you would like to provide your American users with a view containing all the sales of every product of your company: CREATE VIEW ALL_SALES AS SELECT PRODUCT_ITEM. Using the Object-Relational Capabilities 177 . and LOBs together in complex applications: Example: Defining the UDT and UDFs Example: Exploiting LOB Function to Populate the Database Example: Exploiting UDFs to Query Instances of UDTs Example: Exploiting LOB Locators to Manipulate UDT Instances Chapter 8. an internal representation. YEAR. Examples of Complex Applications The following examples show how you can use UDTs. and LOBs In previous sections. UDFs. YEAR. UDFs. By using UDFs.You explicitly cast the amounts in Canadian dollars and German Marks to US dollars since different UDTs are not directly assignable to each other. MONTH. UDFs. An application type with a complex data structure and behavior is modeled as a UDT that is internally represented as a LOB. A LOB is one of the possible internal representations for your new type and is the most suitable representation for large. MONTH. complex structures. you can tell DB2 the name of your new type and how it is internally represented. The rules governing the semantic integrity of your application type will be represented as constraints and triggers. there is a lot of synergy between these three object extensions. and LOBs According to the concept of object-orientation. YEAR. You cannot use the cast specification syntax because UDTs can only be cast to their own source type. Synergy Between UDTs. TOTAL FROM US_SALES UNION SELECT PRODUCT_ITEM. By using UDTs. you should keep them in the same schema. US_DOLLAR (TOTAL) FROM GERMAN_SALES You cast Canadian dollars to US dollars and German Marks to US dollars because UDTs are union compatible only with the same UDT. similar objects in the application domain are grouped into related types. You must use the functional notation to cast between UDTs since the cast specification only lets you cast between UDTs and their source types. However. with its behavior implemented by UDFs. there is an important synergy between UDTs. Combining UDTs. and LOBs. MONTH. you learned how to define and use the individual DB2 object extensions (UDTs. UDFs. US_DOLLAR (TOTAL) FROM CANADIAN_SALES UNION SELECT PRODUCT_ITEM. Therefore. a receiver. such as functions to extract the subject of the e-mail. You define a set of UDFs on your e-mail type. You also define functions that can perform searches on the content of the e-mail. the subject. VARCHAR (200)) RETURNS INTEGER EXTERNAL NAME 'LIB/PGM(CONTAINS)' LANGUAGE C PARAMETER STYLE DB2SQL 178 DB2 UDB for AS/400 SQL Programming V4R4 . and so on. E-mail can be quite large. and the e-mail content). you plan to write queries over such e-mail to find out their subject. how often your e-mail service is used to receive customer orders. You do the above using the following CREATE statements: | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | CREATE DISTINCT TYPE E_MAIL AS BLOB (1M) CREATE FUNCTION SUBJECT (E_MAIL) RETURNS VARCHAR (200) EXTERNAL NAME 'LIB/PGM(SUBJECT)' LANGUAGE C PARAMETER STYLE DB2SQL NO SQL DETERMINISTIC NO EXTERNAL ACTION CREATE FUNCTION SENDER (E_MAIL) RETURNS VARCHAR (200) EXTERNAL NAME 'LIB/PGM(SENDER)' LANGUAGE C PARAMETER STYLE DB2SQL NO SQL DETERMINISTIC NO EXTERNAL ACTION CREATE FUNCTION RECEIVER (E_MAIL) RETURNS VARCHAR (200) EXTERNAL NAME 'LIB/PGM(RECEIVER)' LANGUAGE C PARAMETER STYLE DB2SQL NO SQL DETERMINISTIC NO EXTERNAL ACTION CREATE FUNCTION SENDING_DATE (E_MAIL) RETURNS DATE CAST FROM VARCHAR(10) EXTERNAL NAME 'LIB/PGM(SENDING_DATE)' LANGUAGE C PARAMETER STYLE DB2SQL NO SQL DETERMINISTIC NO EXTERNAL ACTION CREATE FUNCTION CONTENTS (E_MAIL) RETURNS BLOB (1M) EXTERNAL NAME 'LIB/PGM(CONTENTS)' LANGUAGE C PARAMETER STYLE DB2SQL NO SQL DETERMINISTIC NO EXTERNAL ACTION CREATE FUNCTION CONTAINS (E_MAIL. and so on. the sender. the date. Ignoring any issues of privacy.Example: Defining the UDT and UDFs Suppose you would like to keep the electronic mail (e-mail) sent to your company in DB2 tables. date. and it has a complex internal structure (a sender. you decide to represent the e-mail by means of a UDT whose source type is a large object. | | | | | | | NO SQL DETERMINISTIC NO EXTERNAL ACTION CREATE TABLE ELECTRONIC_MAIL (ARRIVAL_TIMESTAMP TIMESTAMP. These UDFs know how to interpret the data without the need to expose its representation. SENDING_DATE (MESSAGE).NAME.NAME). :hv_email_file). HV_EMAIL_FILE.NAME_LENGTH = strlen(HV_EMAIL_FILE. its internal representation and structure are hidden and can only be manipulated by the defined UDFs. your UDT e-mail is completely encapsulated. Example: Exploiting UDFs to Query Instances of UDTs Suppose you need to know how much e-mail was sent by a specific customer regarding customer orders and you have the e-mail address of your customers in the customers table. HV_EMAIL_FILE. CUSTOMERS WHERE SUBJECT (EMAIL. SUBJECT (MESSAGE) FROM ELECTRONIC_MAIL WHERE CONTAINS (MESSAGE. SELECT SENDER (MESSAGE). That is. You would execute the following INSERT statement multiple times with different values of the HV_EMAIL_FILE until you have stored all your e_mail into DB2: EXEC SQL BEGIN DECLARE SECTION SQL TYPE IS BLOB_FILE HV_EMAIL_FILE. Using the Object-Relational Capabilities 179 . Therefore.MESSAGE) AND CUSTOMERS.NAME = 'Customer X' You have used the UDFs defined on the UDT in this SQL query since they are the only means to manipulate the UDT. You have not used the cast function to convert values of BLOB type into your e-mail type. SELECT COUNT (*) FROM ELECTRONIC_MAIL AS EMAIL. EXEC SQL INSERT INTO ELECTRONIC_MAIL VALUES (CURRENT TIMESTAMP. MESSAGE E_MAIL) Example: Exploiting LOB Function to Populate the Database Suppose you populate your table by transferring your e-mail that is maintained in files into DB2. '"performance" AND "products" AND "marketplace"') = 1 You have used the contains UDF which is capable of analyzing the contents of the message searching for relevant keywords or synonyms. In this sense. Suppose you need to know the details of all the e-mail your company received in 1994 which had to do with the performance of your products in the marketplace. EXEC SQL END DECLARE SECTION strcpy (HV_EMAIL_FILE. you have used LOB file reference variables to assign the contents of the file into the UDT column. Chapter 8.FILE_OPTIONS = 2.MESSAGE) = 'customer order' AND CUSTOMERS. "/u/mail/email/mbox"). | | | | | All the function provided by DB2 LOB support is applicable to UDTs whose source type are LOBs.EMAIL_ADDRESS = SENDER (EMAIL. This is because DB2 let you assign values of the source type of a distinct type to targets to the distinct type. The method used for resolving to the object is to store a Uniform Resource Locator (URL). you can use LOB locators for that purpose: EXEC SQL BEGIN DECLARE SECTION long hv_len. The SQL table would use traditional SQL data types to contain information about each clip. Each row in the table would store a URL 180 DB2 UDB for AS/400 SQL Programming V4R4 .. a voice recording. then... . But the clip itself would be referenced using a DataLink column... char hv_current_time[26]. without actually containing the object itself. char hv_sender[200]... This object can be anything. a text file... Using DataLinks The DataLink data type is one of the basic building blocks for extending the types of data that can be stored in database files. A good solution would be to use DataLinks. This concept gives the user much more flexibility in the types of data that can be managed using an SQL table. the user has thousands of video clips stored in the integrated file system of their AS/400.. If. they simply want the SQL table to contain references to the objects. but the object itself might not be deleted. With the DataLink data type.. char hv_buf[4096]... EXEC SQL VALUES (SUBJECT (E_MAIL(:hv_email_locator)) INTO :hv_subject.. date. char hv_subject[200]. EXEC SQL END DECLARE SECTION EXEC SQL SELECT MESSAGE INTO :hv_email_locator FROM ELECTRONIC MAIL WHERE ARRIVAL_TIMESTAMP = :hv_current_time. there is a fairly loose relationship between the row and the object.. you have explicitly converted the BLOB locator to your UDT.Example: Exploiting LOB Locators to Manipulate UDT Instances Suppose you would like to obtain information about a specific e-mail without having to transfer the entire e-mail into a host variable in your application program... An SQL table created with a DataLink column can be used to hold information about an object. whenever it was used as an argument of a UDF defined on the UDT... deleting a row will sever the relationship to the object referenced by the DataLink. if the e_mail is relevant. etc.. ... not contain the actual bytes of storage.. they may want to use an SQL table to contain information about these video clips... an image file. code that checks if the subject of the e_mail is relevant ...) Since your UDT is defined on a LOB...... SQL TYPE IS BLOB_LOCATOR hv_email_locator..... etc. such as title. (Remember that an e-mail can be quite large. Because your host variable is of type BLOB locator (the source type of the UDT). for instance. The user can use new SQL scalar functions to get back the path to the object and the server on which the object is stored. EXEC SQL VALUES (SENDER (CAST (:hv_email_locator AS E_MAIL))) INTO :hv_sender. But since the user already has the objects stored in a directory. length. For instance. and the object itself can be referenced using the DataLink data type.. The idea of a DataLink is that the actual data stored in the column is only a pointer to the object.. This means that a row in a table can be used to contain information about the object in traditional data types.. This option provides control of the object’s existence for the duration of time that it is linked. with a valid server name and file name. Once the row containing that reference is deleted. Using the Object-Relational Capabilities 181 . A DataLink column can be created such that the referenced object cannot be deleted. the old object is unlinked. an object cannot be linked more than once. and then use a browser or other playback software to work with the URL and display the video clip. and allowing the file system to handle streaming of video. the object is unlinked. FILE LINK CONTROL (with File System Permissions) When the DataLink column is created as FILE LINK CONTROL with file system (FS) permissions. Then an application that is working with the clips can retrieve the URL using SQL interfaces. or renamed while there is a row in the SQL table that references that object. Also. FILE LINK CONTROL (with Database Permissions) When the DataLink column is create as FILE LINK CONTROL with database permissions. that would not fit into a character column. but there is no check to make sure that the server is accessible. Using DataLinks also gives control over the objects while they are in ″linked″ status. When the object is found. v The hierarchical nature of the integrated file system is well-suited to organizing and working with the stream file objects. there is no linking that takes place when rows are added to the SQL table. To understand this concept fully.for the object and an optional comment. the URL is verified. displaying images. v The integrated file system can store extremely large objects. it will be marked as linked. moved. or that the file even exists. The file must exist at the time that row is being inserted into the SQL table. text. If a DataLink value is updated to a different value. The integrated file system is still responsible for managing permissions for the linked object. If the server name portion of the URL specifies a remote system. This means that the object cannot be moved. that system must be accessible. v By leaving the bytes of the object outside the database and in the integrated file system. This object would be considered linked. The ownership of the object is changed to a special system-supplied user Chapter 8. or renamed during the time that it is linked. There are several advantages to using this technique: v The integrated file system can store any type of stream file. etc. The permissions are not modified during the link or unlink processes. the object is unlinked. NO LINK CONTROL When a column is created with NO LINK CONTROL. or perhaps even a LOB column. Refer to the SQL Reference for the exact syntax used when creating DataLink columns. one should know the levels of control that can be specified when creating a DataLink column. and the new object is linked. The URL is verified to be syntactically correct. and all existing permissions to the object are removed. the system will verify that any DataLink value is a valid URL. applications can achieve better performance by allowing the SQL runtime engine to handle queries and reports. deleted. If a row containing a DataLink value is deleted. v The system that contains the SQL tables must have the Relational Database Directory updated to reflect the local database system. the only access to the object is by obtaining the URL from the SQL table that has the object linked. Commands Used for Working with DataLinks Support for the DataLink data type can be broken down into 3 different components: 1. See the discussion below on prefixes. as well as the systems that will contain the objects to be linked. This is because the DATALINK itself is not compatible with any host variable type. and keeps track of meta-data for each file. The DB2 database support has a data type called DATALINK. The command CFGTCP can be used to configure the TCP/IP names. There is a DLVALUE scalar function that must be used in SQL to INSERT and UPDATE the values in the column. The column cannot have any default other than NULL. During the time that the object is linked. there are several steps that must be taken to properly configure the system: v TCP/IP must be configured on any systems that are going to be used when working with DataLinks. Since the URL that is used to reference the object contains a TCP/IP server name. 3. or a remote AS/400’s integrated file system. and optionally.profile. An important aspect of DataLinks is that the DLFM need not be on the same physical system as the SQL table that contains the DataLink column. Since the only access to the object is by obtaining the access token from an SQL operation. This can be specified on SQL statements such as CREATE TABLE and ALTER TABLE. This is handled by using a special access token that is appended to the URL returned by SQL. if the user is authorized to access the file. or to register a TCP/IP name server. If the file name includes an access token. This code handles linking. SQL scalar functions can be used to retrieve the DATALINK value in character form. unlinking. this name must be recognized by the system that is going to contain the DataLink. This component determines if the file is linked. The command WRKRDBDIRE can be used to add or modify 182 DB2 UDB for AS/400 SQL Programming V4R4 . this will be the same system. Without the access token. If the URL with the access token is retrieved from the SQL table by normal means (FETCH. So an SQL table can link an object that resides in either the same system’s integrated file system. an administrator can effectively control access to the linked objects by using the database permissions to the SQL table that contains the DataLink column. 2. In most cases. The DataLink filter must be executed when the file system tries operations against files that are in directories designated as containing linked objects. The DataLink File Manager (DLFM) is the component that maintains the link status for the files on a server. When working with DataLinks. the token will be verified. and commitment control issues.) the file system filter will validate the access token and allow the access to the object. Access to the data must be using SQL interfaces. etc. Since there is extra overhead in this filter process. and any optional remote systems. it is only executed when the accessed object exists in one of the directories within a DataLink ″prefix’. This would include the systems on which the SQL tables with DataLink columns are going to be created. all attempts to access the object will fail with an authority violation. This option provides the control of preventing updates to the linked object for users trying to access the object by direct means. SELECT INTO. most or all of the DLFM configuration can be accomplished without using the script interface. it is recommended that the same names be used as the TCP/IP server name and the Relational Database name. This is not a commonly used function since it can only be executed if there are no linked objects anywhere in the directory structure contained within the prefix name. Now links for URLs such as: http://TESTSYS1/mydir/datalinks/videos/file1. The script command dfmadmin -add_prefix is used to add prefixes. If the DLFM is on the same system as the SQL tables that will contain the DataLinks. For the most commonly used functions.txt would be valid since their path begins with a valid prefix. where you have already added the /mydir/datalinks/ prefix. CL commands have also been provided. then only the local database name needs to be added. For instance.information in this directory. Once the DLFM has been started. Adding a prefix . on server TESTSYS1. you can choose to use either the script commands from the QSH command entry screen or the CL commands from the CL command entry screen. on server TESTSYS1. The CL command to add prefixes is ADDPFXDLFM. Using the Object-Relational Capabilities 183 . The command STRTCPSVR *DLFM can be used to start the DLFM server. they all require the *IOSYSCFG special authority. The script command dfmadmin -help can be used to display help text and syntax diagrams. there are some steps needed to configure the DLFM. there is a directory called /mydir/datalinks/ that contains the objects that will be linked. This will bring up a command entry screen from which you can enter the DLFM script commands. The administrator uses the command ADDPFXDLFM PREFIX((’/mydir/datalinks/’)) to add the prefix.mpg or file://TESTSYS1/mydir/datalinks/text/story1. use the CL command QSH. To get to the interactive shell interface. the administrator must add any prefixes that will be used for DataLinks. These DLFM functions are available via an executable script that can be entered from the QShell interface. v The DLFM server must be started on any systems that will contain objects to be linked. Using the CL commands. then all of their names must be registered with the DLFM. It is also possible to remove a prefix using the script command dfmadmin -del_prefix. Depending on your preferences. Adding a Host Database . For consistency. If the DLFM will have link requests coming from remote systems. The script command to add a host database is dfmadmin -add_db and the CL command is ADDHDBDLFM. This function also requires that the libraries containing the SQL tables also be registered.A host database is a relational database system from which a link request originates.A prefix is a path or directory that will contain objects to be linked. When setting up the DLFM on a system. The DLFM server can be ended by using the CL command ENDTCPSVR *DLFM. you want SQL tables on the local system in either library Chapter 8. Since these functions are meant for a system administrator or a database administrator. For instance. Use the following command: ADDHDBDLFM HOSTDBLIB((TESTDB) (PRODDB)) HOSTDB(TESTSYS1) Once the DLFM has been started. and the prefixes and host database names have been registered. you can begin linking objects in the file system.TESTDB or PRODDB to be allowed to link objects on this server. 184 DB2 UDB for AS/400 SQL Programming V4R4 . which is normally a query operation that potentially runs against thousands of rows in a table. if you have a long running UDF and wish to increase the wait time. SQL and external function UDFs require that you write and execute separate code. so that it is known to the database v write the function code to perform the function and pass the appropriate parameters v debug and test the function. that there is a maximum time limit that the database will not exceed. Since resources are held while the UDF is run. If the UDF does not finish in the time allocated. and SQL. Because of the critical nature of holding resources for long periods of time.| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Chapter 9. there are certain resources (locks and seizes) being held at the time the UDF is invoked and for the duration of the UDF execution. this can be done using the UDF_TIME_OUT option in the query INI file. The default UDF wait time used by the database should be more than sufficient to allow a normal UDF to run to completion. the UDF should not try to perform any insert. As a consequence of being invoked from such a low level. See “Query Options File QAQQINI” on page 543 for more information on the INI file. Writing User-Defined Functions (UDFs) User Defined Functions (UDFs) consist of three types: sourced. regardless of the value specified for UDF_TIME_OUT. Specifically. external. it is important that the UDF not perform operations that may take an extended period of time (minutes or hours). UDF runtime environment There are several things to consider about the environment in which a UDF executes and the limitations of that environment. which can be quite aggravating to the end user. it is important that the UDF not operate on the same tables or indexes allocated for the original SQL statement or. if it does. Sourced function UDFs call other functions to perform the operation. These factors should be considered carefully if you are contemplating writing complex function code for UDFs. To write external and SQL functions. However. 1999 185 . update or delete record operation on those tables. Length of time that the UDF runs UDFs are invoked from within an SQL statement execution. © Copyright IBM Corp. you need to do the following: v understand the “UDF runtime environment” v register the UDF. the SQL statement will fail. This chapter is about writing SQL and external functions. that it does not perform an operation that conflicts with the one being performed in the SQL statement. however. the UDF needs to be invoked from a low level of the database. These resources are primarily locks on any tables and indexes involved in the SQL statement that is invoking the UDF. the database only waits for a certain period of time for the UDF to finish. Due to these held resources. Note. 1997. Because of this. However. see Database considerations for multithreaded programming. It also involves understanding the interface between the database and the function code to define it correctly. Writing function code Writing function code involves knowing how to write the SQL or external function to perform the function. v the UDF cannot perform any operation that is blocked from being run in a secondary thread. This means that the same UDF program can be running in multiple threads at the same time. v UDFs do not inherent any program adopted authority that may have been active at the time the SQL statement was invoked. As such. it shares much of the same environment as the SQL statement. if ALLOW PARALLEL is specified for the UDF. Parallel processing A UDF can be defined to allow parallel processing. a function that returns a priority based on a date: 186 DB2 UDB for AS/400 SQL Programming V4R4 . these are the table resources discussed above. see Database considerations for multithreaded programming. Writing UDFs as SQL functions SQL functions are UDFs that you have defined. and determining packaging options when creating the executable program.| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Threads considerations A UDF runs in the same job as the SQL statement that invoked it. written. the following threads considerations apply: v the UDF will conflict with thread level resources held by the SQL statement’s thread. Therefore. ensure that it is thread safe. However. The CREATE FUNCTION statement for SQL functions follow the general flow of: CREATE FUNCTION function name(parameters) RETURNS return value LANGUAGE SQL BEGIN sql statements END For example. For more information about threads. separate from the thread that is running the SQL statement. UDF authority comes from either the authority associated with the UDF program itself or the authority of the user running the SQL statement. they are written using only the SQL language and their definition is completely contained within one (potentially large) CREATE FUNCTION statement. Primarily. Programs that specify ACTGRP(*NEW) will not be allowed to run as UDFs. because it runs under a separate thread. v the UDF program must be created such that it either runs under a named activation group or in the activation group of its caller (ACTGRP parameter). For more information about threads. and registered using the CREATE FUNCTION statement. the UDF runs in a system thread. Because the UDF runs in the same job as the SQL statement. it provides the flexibility for you to use whatever language is most effective for you. While this method is slightly more cumbersome than an SQL function. can cause the function to see invalid input data or cause the value returned to the database to be invalid. Therefore. For the most part.| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | CREATE FUNCTION PRIORITY(indate date) RETURNS CHAR(7) LANGUAGE SQL BEGIN RETURN( CASE WHEN indate>CURRENT DATE-3 DAYS THEN 'HIGH' WHEN indate>CURRENT DATE-7 DAYS THEN 'MEDIUM' ELSE 'LOW' END ). The parameters are all stored in the same space and exceeding a given parameter’s storage space can overwrite another parameter’s value. the parameters are passed into the external program as follows (in the order specified): SQL-result SQL-argument SQL-argument-ind | Chapter 9. END The function could then be invoked as: SELECT ORDERNBR. For service programs. This is the normal parameter passing method for programs. the styles differ in how many parameters are passed to the external program or service program. Therefore. The executable code can be contained in either a program or service program. Parameter style SQL: The parameter style SQL conforms to the industry standard Structured Query Language (SQL). When defining and using the parameters in the UDF. Writing User-Defined Functions (UDFs) 187 . With parameter style SQL. This. generates the executable code for the function. and defines to the database the details of how parameters are actually passed. PRIORITY(ORDERDUEDATE) FROM ORDERS The creation of an SQL function causes the registration of the UDF. Passing arguments from DB2 to external functions DB2 provides the storage for all parameters passed to a UDF. ensure that the parameters are defined correctly in the function code. writing these functions is quite clean and provides less chance of introducing errors into the function. in turn. parameters are passed to the external function by address. There are four supported parameter styles available to external UDFs. care should be taken to ensure that no more storage is referenced for a given parameter than is defined for that parameter. Writing UDFs as external functions You can also write the executable code of a UDF in a language other than SQL. any changes to the parameter values made by the UDF are ignored by DB2. It can be used by the UDF to determine if the corresponding SQL-argument is null or not. Each indicator is defined as a two-byte signed integer. The database provides the storage for the return value. the address is of the storage where the indicator value should be placed. Since the parameter is passed by address. if it is defined with CALLS ON NULL INPUT. This results in an SQL warning. Here xx may be one of several possible strings. However. it can be used to signal an error or warning to the database as follows: 01Hxx The function code detected a warning situation. SQL-argument-ind This argument is set by DB2 before calling the UDF. the database interprets the result of the function as null. 188 DB2 UDB for AS/400 SQL Programming V4R4 . The value of each of these arguments is taken from the expression specified in the function invocation. SQL-result-ind This argument is set by the UDF before returning to DB2. It is expressed in the data type of the defined parameter in the create function statement. This parameter is passed in from the database set to '00000' and can be set by the function as a result state for the function. described previously. The nth SQL-argument-ind corresponds to the nth SQL-argument. any changes to the parameter values made by the UDF are ignored by DB2. where n is the number of arguments specified in the function reference. otherwise DB2 assumes the UDF returns the value as defined in the RETURNS clause. The database provides as much storage as needed for the return value as defined on the CREATE FUNCTION statement. SQL-state This argument is a CHAR(5) value that represents the SQLSTATE. Note: these parameters are treated as input only. the address is of the storage where the return value should be placed. DB2 assumes the UDF returns the value as defined in the CAST FROM clause.| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | SQL-result-ind SQL-state function-name specific-name diagnostic-message SQL-argument This argument is set by DB2 before calling the UDF. Note: These parameters are treated as input only. Since the parameter is passed by address. This value repeats n times. the database uses the value returned in SQL-result. While normally the SQLSTATE is not set by the function. If the function is defined with RETURNS NULL ON NULL INPUT. If set to a negative value. The argument is defined as a two-byte signed integer. the UDF does not need to check for a null value. If set to zero or a positive value. The database provides the storage for the return value. The argument is null. It is set to one of the following values: 0 -1 The argument is present and not null. any argument can be NULL and the UDF should check for null input. SQL-result This argument is set by the UDF before returning to DB2. If the CAST FROM clause is used in the CREATE FUNCTION statement. The database provides the storage for the return value indicator. SQL-result SQL-argument SQL-argument-ind | | | SQL-result-ind SQL-state function-name specific-name diagnostic-message Chapter 9. function-name This argument is set by DB2 before calling the UDF. they are passed to the UDF in the order defined below. It is a VARCHAR(139) value that contains the name of the function on whose behalf the function code is being invoked. The form of the function name that is passed is: <schema-name>. Refer to parameter style SQL for the common parameters. Here xxx may be one of several possible strings. DB2SQL allows additional optional parameters to be passed along as well. diagnostic-message This argument is set by DB2 before calling the UDF. It is initialized by the database on input to the UDF and may be set by the UDF with descriptive information. any changes to the parameter value made by the UDF are ignored by DB2. It results in a SQL error. Message text is ignored by DB2 unless the SQL-state parameter is set by the UDF. Note: This parameter is treated as input only. See Appendix B for more information on valid SQLSTATEs that the function may use. this parameter is useful when the function code is being used by multiple UDF definitions so that the code can distinguish which definition is being invoked. Like function-name. If more than one of the optional parameters below is specified in the UDF definition. the same parameters and same order of parameters are passed into the external program or service program as are passed in for parameter style SQL. any changes to the parameter value made by the UDF are ignored by DB2. However. Parameter style DB2SQL: With the DB2SQL parameter style. See the CREATE FUNCTION for more information about specific-name. Note: This parameter is treated as input only. It is a VARCHAR(128) value that contains the specific name of the function on whose behalf the function code is being invoked. It is a VARCHAR(70) value that can be used by the UDF to send message text back when an SQLSTATE warning or error is signaled by the UDF.| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | 38xxx The function code detected an error situation.<function-name> This parameter is useful when the function code is being used by multiple UDF definitions so that the code can distinguish which definition is being invoked. Writing User-Defined Functions (UDFs) 189 . specific-name This argument is set by DB2 before calling the UDF. | scratchpad call-type dbinfo | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | SQL-result = func ( SQL-argument ) scratchpad This argument is set by DB2 before calling the UDF. It is an INTEGER value that contains one of the following values: -1 0 1 This is the first call to the UDF for this statement. This value repeats n times. However. Note: These parameters are treated as input only. The scratchpad can be used by the UDF either as working storage or as persistent storage. No SQL-argument or SQL-argument-ind values are passed. v The actual scratchpad. initialized to all binary 0’s by DB2 before the first call to the UDF. the UDF may set the SQL-state and diagnostic-message arguments. Both of these are ignored by DB2 upon return from the UDF. This is a normal call. It is only present if the CREATE FUNCTION statement for the UDF specifies the DBINFO keyword. It is only present if the CREATE FUNCTION statement for the UDF specified the SCRATCHPAD keyword. These arguments are handled in a way similar to other calls to the UDF. dbinfo This argument is set by DB2 before calling the UDF. The format is: | | | | | | | | | SQL-argument This argument is set by DB2 before calling the UDF. A UDF should not return any answer using the SQL-result or SQL-result-ind arguments. It is expressed in the data type of the defined parameter in the CREATE FUNCTION statement. This is a final call. Parameter Style GENERAL (or SIMPLE CALL): With parameter style GENERAL. This argument is a structure with the following elements: v An INTEGER containing the length of the scratchpad. It is only present if the CREATE FUNCTION statement for the UDF specified the FINAL CALL keyword. (All the normal input argument values are passed). any changes to the parameter values made by the UDF are ignored by DB2. the parameters are passed into the external service program just as they are specified in the CREATE FUNCTION statement. where n is the number of arguments specified in the function reference. The value of each of these arguments is taken from the expression specified in the function invocation. call-type This argument is set by DB2 before calling the UDF. A first call is a normal call in that all SQL argument values are passed. The argument is a structure whose definition is contained in the sqludf include. since it is maintained across UDF invocations. 190 DB2 UDB for AS/400 SQL Programming V4R4 . any changes to the parameter values made by the UDF are ignored by DB2. If the CAST FROM clause is used in the CREATE FUNCTION statement. in C. In order to return the value correctly. the function code would be defined as follows: typedef struct { int rtnint. in order to be returned correctly. It is an Chapter 9. any function code used for parameter style GENERAL must be created into a service program. the function was defined as simply int func1(). .| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | SQL-result This value is returned by the UDF. SQL-argument-ind-array This argument is set by DB2 before calling the UDF. Note: These parameters are treated as input only. } rtnval_t. In addition. to return an INTEGER. where n is the number of arguments specified in the function reference. return(rtnval). otherwise DB2 assumes the UDF returns the value as defined in the RETURNS clause. Because of the requirement that the function code be a value-returning function. It is expressed in the data type of the defined parameter in the CREATE FUNCTION statement. Parameter Style GENERAL WITH NULLS: With parameter style GENERAL WITH NULLS. the parameters are passed into the service program as follows (in the order specified): SQL-result = funcname ( SQL-argument | | | | | | | | | | | | | | SQL-result-ind ) SQL-argument-ind-array SQL-argument This argument is set by DB2 before calling the UDF. DB2 copies the value into database storage. If. the return value would not be available for DB2 to use. . instead. The value of each of these arguments is taken from the expression specified in the function invocation. the return value defined in the function code must be defined as a simple structure. the function code must be a value-returning function. The database copies only as much of the value as defined for the return value as specified on the CREATE FUNCTION statement. This value repeats n times. }. Note: The return value must be defined as a simple structure. rtnval_t func1() { rtnval_t rtnval. It can be used by the UDF to determine if one or moreSQL-arguments are null or not. For example. Writing User-Defined Functions (UDFs) 191 . DB2 assumes the UDF returns the value as defined in the CAST FROM clause. the function was defined as simply int func1(. the function code must be a value-returning function. Because of the requirement that the function code be a value-returning function. instead.. any changes to the parameter value made by the UDF is ignored by DB2. For example. 192 DB2 UDB for AS/400 SQL Programming V4R4 . to return an INTEGER. the return value defined in the function code must be defined as a simple structure. the database interprets the result of the function as null. SQL-result-ind This argument is set by the UDF before returning to DB2.| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | array of two-byte signed integers (indicators). } rtnval_t. DB2 assumes the UDF returns the value as defined in the CAST FROM clause. the function code would be defined as follows: typedef struct { int rtnint. The argument is null. . If. . In order to be returned correctly. Note: This parameter is treated as input only.. Thenth array argument corresponds corresponds to the nth SQL-argument.). the address is of the storage where the indicator value should be placed. Note: The return value must be defined as a simple structure. If set to a negative value. Since the parameter is passed by address. If set to zero or a positive value. short parmind[]. The database provides the storage for the return value indicator. any function code used for parameter style GENERAL WITH NULLS must be created into a service program. SQL-result This value is returned by the UDF. The database copies only as much of the value as defined for the return value as specified on the CREATE FUNCTION statement. DB2 copies the value into database storage. short *rtnind) { rtnval_t rtnval. The database provides the storage for the return value. in C. The UDF should check for null input. The argument is defined as a two-byte signed integer. In order to return the value correctly. }. the return value would not be available for DB2 to use. . If the CAST FROM clause is used in the CREATE FUNCTION statement. return(rtnval). otherwise DB2 assumes the UDF returns the value as defined in the RETURNS clause. rtnval_t func1(short *parm1. the database uses the value returned in SQL-result. Each array entry is set to one of the following values: 0 -1 The argument is present and not null. short *inind. The query statement is: SELECT SQUARE(myint) FROM mytable The following examples show how to define the UDF several different ways. char *msgtext) { if (*inind<0) *outind=-1. char *sqlstate. v Using an SQL function CREATE FUNCTION SQUARE( inval INT) RETURNS INT LANGUAGE SQL BEGIN RETURN(inval*inval). } To create the external service program so it can be debugged: CRTCMOD MODULE(mylib/square) DBGVIEW(*SOURCE) CRTSRVPGM SRVPGM(mylib/math) MODULE(mylib/square) EXPORT(*ALL) ACTGRP(*CALLER) v Using an external function. else { *outval=*inval. *outind=0.| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Examples of UDF code These examples show how to implement UDF code by using SQL functions and external functions. double *outval. *outval=(*outval)*(*outval). parameter style SQL: The CREATE FUNCTION statement: CREATE FUNCTION SQUARE(INT) RETURNS INT CAST FROM FLOAT LANGUAGE C EXTERNAL NAME 'MYLIB/MATH(SQUARE)' DETERMINISTIC NO SQL NO EXTERNAL ACTION PARAMETER STYLE SQL ALLOW PARALLEL The code: void SQUARE(int *inval. short *outind. char *funcname. char *specname. parameter style GENERAL: The CREATE FUNCTION statement: Chapter 9. Writing User-Defined Functions (UDFs) 193 . } return. END v Using an external function. Example: Square of a number UDF Suppose that you wanted a function that returns the square of a number. char *funcname. short *outnull. outval. void ctr ( long *out.outf)*(outval. specific-name. char *specname. 194 DB2 UDB for AS/400 SQL Programming V4R4 . observe that: v It has no input SQL arguments defined. outval_t SQUARE(int *inval) { outval_t outval. /* structure scr defines the passed scratchpad for the function "ctr" */ struct scr { long len. }. char *mesgtext. function-name. char *sqlstate. So you write a UDF which increments and returns a counter. long countr. } To create the external service program so it can be debugged: CRTCMOD MODULE(mylib/square) DBGVIEW(*SOURCE) CRTSRVPGM SRVPGM(mylib/math) MODULE(mylib/square) EXPORT(*ALL) ACTGRP(*CALLER) Example: Counter Suppose you want to simply number the rows in your SELECT statement. v It appends the scratchpad input argument after the four standard trailing arguments.outf). return. return(outval). This example uses an external function with DB2 SQL parameter style and a scratchpad.outf=*inval. *outnull = 0.outf=(outval. } outval_t. but returns a value.| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | CREATE FUNCTION SQUARE(INT) RETURNS INT CAST FROM FLOAT LANGUAGE C EXTERNAL NAME 'MYLIB/MATH(SQUARE)' DETERMINISTIC NO SQL NO EXTERNAL ACTION PARAMETER STYLE GENERAL ALLOW PARALLEL The code: typedef struct { double outf. namely SQL-state. CREATE FUNCTION COUNTER() RETURNS INT SCRATCHPAD NOT DETERMINISTIC NO SQL NO EXTERNAL ACTION LANGUAGE C PARAMETER STYLE DB2SQL EXTERNAL NAME 'MYLIB/MATH(ctr)' DISALLOW PARALLELISM. outval. and message-text. /* /* /* /* /* /* /* output answer (counter) */ output NULL indicator */ SQL STATE */ function name */ specific function name */ message text insert */ scratch pad */ /* increment counter & copy out */ } /* end of UDF : ctr */ For this UDF. char not_used[96]. struct scr *scratchptr) { *out = ++scratchptr->countr. Chapter 9. because correct functioning of the UDF depends on a single scratchpad. (none in this case). because it depends on more than the SQL input arguments. This agrees with the code. causing DB2 to allocate. v No input parameters are defined.| | | | | | | | v It includes a structure definition to map the scratchpad which is passed. v You have correctly specified DISALLOW PARALLELISM. properly initialize and pass the scratchpad argument. Writing User-Defined Functions (UDFs) 195 . v You have specified it to be NOT DETERMINISTIC. v SCRATCHPAD is coded. 196 DB2 UDB for AS/400 SQL Programming V4R4 . RPG for AS/400 programs require the aid of PL/I. Some dynamic SQL statements require use of address variables. Notes: 1. binding. The following table shows all the statements supported by DB2 UDB for AS/400 and indicates if they can be used in a dynamic application. The run-time overhead is greater for statements processed using dynamic SQL than for static SQL statements. Other applications should access data from the database using normal (static) SQL statements. Dynamic SQL Applications Dynamic SQL allows an application to define and run SQL statements at program run time. 1999 Static SQL Y Y Y Y Y Y Y Y Dynamic SQL Y N Y N Y Y N Y 197 . or ILE RPG for AS/400 programs to manage the address variables. the numbers in the Dynamic SQL column correspond to the notes on the next page. COBOL. C. The application: v Builds or accepts as input an SQL statement v Prepares the SQL statement for running v Runs the statement v Handles SQL return codes Interactive SQL (described in Chapter 19. only applications requiring the flexibility of dynamic SQL should use it. Using Interactive SQL) is an example of a dynamic SQL program. The additional process is similar to that required for precompiling. and then running a program. List of SQL Statements Allowed in Dynamic Applications SQL Statement ALTER TABLE BEGIN DECLARE SECTION CALL CLOSE COMMENT ON COMMIT CONNECT CREATE ALIAS © Copyright IBM Corp.| Chapter 10. Note: In the following table. instead of only running it. An application that provides for dynamic SQL accepts as input (or builds) an SQL statement in the form of a character string. The ALWBLK(*ALLREAD) CRTSQLxxx option will imply a FOR READ ONLY declaration for all cursors that do not explicitly code FOR UPDATE OF or have positioned deletes or updates that refer to the cursor. Table 22. Cursors with an implied FOR READ ONLY will benefit from the second item in this list. 1997. Therefore. Programs that contain an EXECUTE or EXECUTE IMMEDIATE statement and that use a FOR READ ONLY clause to make a cursor read-only experience better performance because blocking is used to retrieve rows for the cursor. SQL statements are processed and run dynamically by interactive SQL. 2. The application does not need to know what type of SQL statement it will run. The examples in this chapter are PL/I examples. Y N Y 198 DB2 UDB for AS/400 SQL Programming V4R4 . See Note 2. N N N Y See Note 7. N Y Y Y See Note 5. See Note 6.Table 22. N N Y N See Note 1. Y Y See Note 4. N See Note 9. N Y Y N Y Y Y N See Note 3. List of SQL Statements Allowed in Dynamic Applications (continued) SQL Statement CREATE COLLECTION CREATE DISTINCT TYPE CREATE FUNCTION CREATE INDEX CREATE PROCEDURE CREATE SCHEMA CREATE TABLE CREATE VIEW DECLARE CURSOR DECLARE PROCEDURE DECLARE STATEMENT DECLARE VARIABLE DELETE DESCRIBE DESCRIBE TABLE DISCONNECT DROP END DECLARE SECTION EXECUTE EXECUTE IMMEDIATE FETCH FREE LOCATOR GRANT INCLUDE INSERT LABEL ON LOCK TABLE OPEN PREPARE RELEASE RENAME REVOKE ROLLBACK SELECT INTO SELECT statement SET CONNECTION SET OPTION SET PATH SET RESULT SETS SET TRANSACTION Static SQL Y Y Y Y Y N Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Dynamic SQL Y Y Y Y Y See Note 8. Cannot be prepared. but used to define the cursor for the associated dynamic SELECT statement prior to running. The SQL statement must be previously prepared by the PREPARE statement prior to using the EXECUTE statement. The EXECUTE IMMEDIATE statement causes the SQL statement to be prepared and run dynamically at program run time. but used to return a description of a prepared statement. 3. 9. List of SQL Statements Allowed in Dynamic Applications (continued) SQL Statement SET variable UPDATE VALUES INTO WHENEVER Static SQL Y Y Y Y Dynamic SQL N Y N N Notes: 1. Designing and Running a Dynamic SQL Application To issue a dynamic SQL statement. because dynamic SQL statements are not prepared at precompile time and therefore must be prepared at run time. Dynamic SQL Applications 199 . See example for PREPARE under “Using the PREPARE and EXECUTE Statements” on page 200. 5. and set up dynamic SELECT statements prior to running. Non-SELECT statements include such statements as DELETE. Cannot be prepared. 4.Table 22. See example for EXECUTE IMMEDIATE under “Processing Non-SELECT statements”. you must use the statement with either an EXECUTE statement or an EXECUTE IMMEDIATE statement. Processing Non-SELECT statements To build a dynamic SQL non-SELECT statement: Chapter 10. see the Client Access for Windows 3. and UPDATE. but used to run prepared SQL statements. Can only be run using the Run SQL Statements (RUNSQLSTM) command. There are two basic types of dynamic SQL statements: SELECT statements and non-SELECT statements.1 ODBC User’s Guide. optimize. Cannot be prepared. Cannot be used with EXECUTE or EXECUTE IMMEDIATE but can be prepared and used with OPEN. 7. 8. but used to parse. The EXECUTE IMMEDIATE statement causes the statement strings to be prepared and run dynamically at program run time. A SELECT INTO statement cannot be prepared or used in EXECUTE IMMEDIATE. 2. See example for PREPARE under “Processing Non-SELECT statements”. Cannot be prepared. INSERT. Cannot be prepared. 6. For more information on developing client server applications that use Client Access. but used with dynamic statement strings that do not have any ? parameter markers. Can only be used when running a REXX procedure. Client server applications that use interfaces such as ODBC typically use dynamic SQL to access the database. */ EXEC SQL PREPARE S1 FROM :DSTRING. Handle any SQL return codes that might result. CCSID of Dynamic SQL Statements The SQL statement is normally a host variable. The following example is of a prepared statement being run multiple times: DSTRING = 'DELETE FROM CORPDATA.*/ 200 DB2 UDB for AS/400 SQL Programming V4R4 . unless the USING clause is specified on the PREPARE statement. then EXECUTE the prepared statement. the preparation is delayed until the first time the statement is used in an EXECUTE or DESCRIBE statement.1. verify. This affects variant characters the most. it also can be a string expression. 2. Build the SQL statement. If the statement text CCSID is 65535. /*The ? is a parameter marker which denotes that this value is a host variable that is to be substituted each time the statement is run. Dynamic SQL statements are processed using the CCSID of the statement text. let us call it S1. it can be run many times within the same program. In this instance. Using Interactive SQL for more information. they can be run dynamically using the EXECUTE IMMEDIATE statement. the DELETE statement) and gives it a name of your choosing. the job CCSID is used as the CCSID of the statement text. However. 2. using different values for the parameter markers. The PREPARE statement prepares the non-SELECT statement (for example. See Chapter 19. or PREPARE the SQL statement. they must be run using PREPARE and EXECUTE. This means that SQL looks for the not sign (¬) at '5F'X. Verify that the SQL statement you want to build is one that can be run dynamically (see Table 22 on page 197). If DLYPRP (*YES) is specified on the CRTSQLxxx command. In PL/I. After the statement has been prepared. (Use Interactive SQL for an easy way to build. For example. The following is an example of an application running a dynamic SQL non-SELECT statement (stmtstrg): EXEC SQL EXECUTE IMMEDIATE :stmtstrg. The CCSID of the host variable is used as the CCSID of the statement text.) To run a dynamic SQL non-SELECT statement: 1. SQL processes variant characters as if they had a CCSID of 37. In this case. if the non-SELECT statements have parameter markers. /*DSTRING is the delete statement that the PREPARE statement is naming S1. the not sign (¬) is located at 'BA'X in CCSID 500.EMPLOYEE WHERE EMPNO = ?'. SQL expects the not sign (¬) to be located at 'BA'X. This means that if the CCSID of your statement text is 500. and run your SQL statement. Run the SQL statement using EXECUTE IMMEDIATE. Using the PREPARE and EXECUTE Statements If non-SELECT statements contain no parameter markers. In addition. because the host variables that provide the input data are declared when the program is being written. 2. unless the USING clause is specified on the PREPARE statement. fixed-list SELECT statements are those statements designed to retrieve data of a predictable number and type. Chapter 10. your application must: 1. In routines similar to the example above. When using these statements. Processing SELECT Statements and Using an SQLDA There are two basic types of SELECT statements: fixed-list and varying-list. and these values have the same data formats as those returned for the last FETCH. Declare a cursor for the statement name. you can anticipate and define host variables to accommodate the retrieved data. To process a fixed-list SELECT statement. so that an SQLDA is not necessary. Issue a PREPARE statement to validate the dynamic SQL statement and put it into a form that can be run. Place the input SQL statement into a host variable. Note: All prepared statements that are associated with an application server are destroyed whenever the connection to the application server ends. END. FETCH a row into a fixed list of variables (rather than into a descriptor area. 4. Open the cursor. To run fixed-list SELECT statements dynamically. Dynamic SQL Applications 201 . Varying-List Select-Statements). 5. You can use fixed-list dynamic SELECT statements with any SQL-supported application program. Fixed-List SELECT Statements In dynamic SQL. you must first declare an SQLDA structure. To process a varying-list SELECT statement. Connections are ended by a CONNECT (Type 1) statement. you must know the number of parameter markers and their data types. If DLYPRP (*YES) is specified on the CRTSQLxxx command. /*The application program reads a value for EMP from the display station.DO UNTIL (EMP =0). described in the following section. the preparation is delayed until the first time the statement is used in an EXECUTE or DESCRIBE statement. Each successive FETCH returns the same number of values as the last. as you would if you were using a varying-list SELECT statement. 3. a DISCONNECT statement.*/ EXEC SQL EXECUTE S1 USING :EMP. or a RELEASE followed by a successful COMMIT. You can specify host variables the same as you would for any SQL application. an SQLDA is not necessary. The SQLDA is a control block used to pass host variable input values from an application program to SQL and to receive output values from SQL. information about SELECT list expressions can be returned in a PREPARE or DESCRIBE statement. you do not have to use the SQL descriptor area (SQLDA). You can also code the PREPARE statement with an INTO clause to perform the functions of PREPARE and DESCRIBE with a single statement. the preparation is delayed until the first time the statement is used in an EXECUTE or DESCRIBE statement. in this case. FETCH-ROW. :EMPNAME END-EXEC. If DLYPRP (*YES) is specified on the CRTSQLxxx command. 3. 5. unless the USING clause is specified on the PREPARE statement. 6 on page 203. close the cursor. Handle any SQL return codes that result. Declare a cursor for the statement name.6. 7. PERFORM FETCH-ROW UNTIL SQLCODE NOT=0. Note: Remember that because the SELECT statement. 2. For example: MOVE 'SELECT EMPNO. 4. Issue a PREPARE statement to validate the dynamic SQL statement and put it into a form that can be run. Note: In REXX. EXEC SQL PREPARE S2 FROM :DSTRING END-EXEC. varying-list SELECT statements are ones for which the number and format of result columns to be returned are not predictable. Issue a DESCRIBE statement to request information from SQL about the type and size of each column of the result table. Open the cursor (declared in step 3) that includes the name of the dynamic SELECT statement. steps 5. Notes: a. you do not know how many variables you need. LASTNAME FROM CORPDATA. you cannot define host variables in advance to accommodate the result columns returned. When end of data occurs. or what the data types are. If your application accepts varying-list SELECT statements. always returns the same number and type of data items as previously run fixed-list SELECT statements. that is. your program has to: 1. EXEC SQL FETCH C2 INTO :EMP. EXEC SQL DECLARE C2 CURSOR FOR S2 END-EXEC. EXEC SQL OPEN C2 USING :EMP END-EXEC.EMPLOYEE WHERE EMPNO>?' TO DSTRING. 202 DB2 UDB for AS/400 SQL Programming V4R4 . Varying-List Select-Statements In dynamic SQL. STOP-RUN. Therefore. and 7 on page 203 are not applicable. Place the input SQL statement into a host variable. EXEC SQL CLOSE C2 END-EXEC.b on page 203. close the cursor. an SQLDA provides information about host variables. EXECUTE. 6. Put storage addresses into the SQLDA (SQL descriptor area) to tell SQL where to put each item of retrieved data. that program must call the RPG for AS/400 program. The SQLDA is a collection of variables required for running the DESCRIBE and DESCRIBE TABLE statements. get storage for that amount of space. C. For more information on SQLDA and SQLCA. 7. It also can be used on the PREPARE. and reissue the DESCRIBE statement. FETCH. If the SQLDA is not large enough to contain column descriptions for each retrieved column. Dynamic SQL Applications 203 . C. Since the area used must be declared by the PL/I. COBOL. or ILE RPG for AS/400 program. build a new SQLDA. CALL. and FETCH. see the DB2 UDB for AS/400 SQL Reference book. The meaning of the information in an SQLDA depends on its use. and RPG. 8. the program must determine how much space is needed. When end of data occurs. OPEN. SQLDAs can be used in C. The SQL Descriptor Area (SQLDA) You can use the SQLDA to pass information about an SQL statement between SQL and your application. pointers must be set outside the RPG for AS/400 program by a PL/I. COBOL. In PREPARE and DESCRIBE. Allocate the amount of storage needed to contain a row of retrieved data. COBOL. one for each dynamic SELECT statement. and then reused in a FETCH statement. 9. you can code several SQLDAs. or ILE RPG for AS/400 program. FETCH a row. the SQLDA provides information to an application program about the columns in a table or view. PL/I. Because RPG for AS/400 does not provide a way to set pointers. In DESCRIBE TABLE. an SQLDA provides information to an application program about a prepared statement. SQLDA is required for: v DESCRIBE v DESCRIBE TABLE SQLDA is an option for: v EXECUTE v FETCH v OPEN v PREPARE v CALL If your application lets you have several cursors open at the same time. An SQLDA is used with dynamic SQL. changed with the addresses of host variables. It can be used in a DESCRIBE statement. In OPEN. Chapter 10.b. REXX. Handle any SQL return codes that might result. and EXECUTE statements. 10. CALL. SQLDABC SQLDABC indicates the length of the SQLDA. In other statements. and EXECUTE. This flag is set to a blank if there are not any LOBs or distinct types. SQLVAR The variables of SQLVAR are SQLTYPE. SQLLEN. this field must be set prior to use to a value greater than or equal to 0 and less than or equal to SQLN.SQLDA Format The SQLDA consists of four variables followed by an arbitrary number of occurrences of a sequence of six variables collectively named SQLVAR. SQLN SQLN is a 2-byte integer that specifies the total number of occurrences of SQLVAR. | | | Byte 7 can be used to determine if more than one SQLVAR entry is needed for each column. It is a string of 8 characters that have the value 'SQLDA' after the SQLDA that is used in a PREPARE or DESCRIBE statement. Coding SQL Statements in REXX Applications. SQLDAID is not applicable in REXX. SQLRES. they must be set prior to use. SQLDATA. the number of host variables described by the SQLDA. SQLABC is not applicable in REXX. Note: The SQLDA in REXX is different. OPEN. Byte 7 of SQLDAID is used to indicate if there are extension SQL VARs used for LOBs or UDTs. The variables of SQLDA are as follows (variable names are in lowercase for C): SQLDAID SQLDAID is used for storage dumps. each occurrence of SQLVAR describes a host variable. see Chapter 17. and SQLNAME. It must be set prior to use by any SQL statement to a value greater than or equal to 0. 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. OPEN. For more information. When an SQLDA is used in OPEN. It is not used for FETCH. SQLLEN SQLLEN is a 2-byte integer variable that specifies the length attributes of the host variables shown in Figure 10-2. or EXECUTE. In other statements. This field is set by SQL on a DESCRIBE or PREPARE statement. SQLDABC must have a value equal to or greater than SQLN*LENGTH(SQLVAR) + 16 prior to use by FETCH. These variables are set by SQL on a DESCRIBE or PREPARE statement. 204 DB2 UDB for AS/400 SQL Programming V4R4 . that is. SQLD SQLD is a 2-byte integer that specifies the pertinent number of occurrences of SQLVAR. Odd values for SQLTYPE show that the host variable has an associated indicator variable addressed by SQLIND. FETCH. SQLN is not applicable in REXX. CALL. SQLIND. CALL. 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. CALL or EXECUTE. scale in byte 2 4 2 5 5 PASCAL L-string Floating point 484/485 488/489 496/497 500/501 504/505 Packed decimal Zoned decimal Large integer Small integer N/A Packed decimal Zoned decimal Large integer Small integer DISPLAY SIGN LEADING SEPARATE N/A Chapter 10. Dynamic SQL Applications 205 .Table 23. 8 for double precision Precision in byte 1. or EXECUTE For PREPARE and DESCRIBE SQLTYPE 384/385 COLUMN DATA TYPE Date SQLLEN 10 For FETCH. OPEN. scale in byte 2 388/389 Time 8 392/393 Timestamp 26 | | 396/397 400/401 392/393 DataLink6 N/A Timestamp Length attribute of N/A the column N/A 26 NUL-terminated graphic string Fixed-length character string representation of a timestamp BLOB CLOB DBCLOB | | | 404/405 408/409 412/413 452/453 456/457 460/461 464/465 468/469 472/473 476/477 480/481 BLOB CLOB DBCLOB Fixed-length character string Long varying-length character string N/A Varying-length graphic string Fixed-length graphic string Long varying-length graphic string N/A Floating point 07 07 07 Length attribute of Fixed-length character the column string Length attribute of Long varying-length the column character string N/A NUL-terminated character string Length attribute of Varying-length graphic the column string Length attribute of Fixed-length graphic string the column Length attribute of Long graphic string the column N/A 4 for single precision. scale in byte 2 4 2 Precision in byte 1.7 Not used.7 Not used. scale in byte 2 Precision in byte 1. DESCRIBE. CALL. scale in byte 2 Precision in byte 1. FETCH. 8 for double precision Precision in byte 1. and EXECUTE HOST VARIABLE DATA TYPE Fixed-length character string representation of a date Fixed-length character string representation of a time Fixed-length character string representation of a timestamp SQLLEN Length attribute of the host variable Length attribute of the host variable Length attribute of the host variable N/A Length attribute of the host variable Length attribute of the host variable Not used.7 Length attribute of the host variable Length attribute of the host variable Length attribute of the host variable Length attribute of the host variable Length attribute of the host variable Length attribute of the host variable Length attribute of the host variable 4 for single precision. CALL. SQLTYPE and SQLLEN Values for PREPARE. OPEN. FETCH. pointers must be on a quad-word boundary. CALL. or with the precision in byte 1 and the scale in byte 2. 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. graphic. FETCH. 206 DB2 UDB for AS/400 SQL Programming V4R4 . CCSIDs can be passed for character. In REXX. CALL. The SQLNAME field in an SQLVAR array entry of an input SQLDA can be set to specify the CCSID: 5. CALL. When the SQLDA is used on PREPARE and DESCRIBE. and EXECUTE. SQLDATA SQLDATA is a 16-byte pointer variable that specifies the address of the host variables when the SQLDA is used on OPEN. date. it indicates precision and scale. it can be used to pass the CCSID of character strings. This pointer is only used if SQLTYPE contains an odd value. A negative value indicates null and a non-negative indicates not null. Binary numbers can be represented in the SQLDA as either lengths 2 or 4. In OPEN. time. OPEN.Table 23. For BIT data. When the SQLDA is used on PREPARE and DESCRIBE. the CCSID is returned in the variable SQLCCSID. this area is reserved for future use. SQLRES is not applicable in REXX. 6. this area is overlaid with the following information: The CCSID of a character. timestamp. or system column name after a PREPARE or DESCRIBE.sqllonglen field in the secondary SQLVAR contains the length attribute of the column. and timestamp host variables. Note that. and EXECUTE HOST VARIABLE DATA TYPE BLOB file reference variable CLOB file reference variable DBCLOB file reference variable BLOB locator CLOB locator DBCLOB locator SQLLEN 267 267 267 4 4 4 | | | | | | | | | 916/917 920/921 924/925 960/961 964/965 968/969 SQLRES SQLRES is a 12-byte reserved area for boundary alignment purposes. the CCSID is 65535. 7. DESCRIBE. date. The DataLink datatype is only returned on DESCRIBE TABLE. or CALL. which contains the name of selected column. and graphic field is stored in the third and fourth bytes of SQLDATA. label. SQLTYPE and SQLLEN Values for PREPARE. If the first byte is greater than X’00’. or EXECUTE (continued) For PREPARE and DESCRIBE SQLTYPE COLUMN DATA TYPE N/A N/A N/A N/A N/A N/A SQLLEN N/A N/A N/A N/A N/A N/A For FETCH. in OS/400. EXECUTE. OPEN. time. FETCH. The len. SQLNAME SQLNAME is a variable-length character variable with a maximum length of 30. CALL. and EXECUTE. If SQLD is not set to a sufficient number of SQLVAR occurrences: v SQLD is set to the total number of SQLVAR occurrences needed for all sets. Chapter 10. It is used for LOB (BLOB.Data Type Character Character Character GRAPHIC Any other data type Sub-type SBCS MIXED BIT not applicable not applicable Length of SQLNAME 8 8 8 8 not applicable SQLNAME Bytes 1 & 2 X’0000’ X’0000’ X’0000’ X’0000’ not applicable SQLNAME Bytes 3 & 4 CCSID CCSID X’FFFF’ CCSID not applicable Note: It is important to remember that the SQLNAME field is only for overriding the CCSID. No SQLVAR entries are returned. | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | SQLVAR2 The Extended SQLVAR structure. v A +239 warning is returned in the SQLCODE field of the SQLCA if enough SQLVARs were not specified for even the Base SQLVAR Entries. If an associated double-byte CCSID does not exist. they contain the length attribute of the host variable and a pointer to the buffer that contains the actual length. Byte 7 of SQLDAID is always set to the number of sets of SQLVARs necessary. SQLLONGLEN SQLLONGLEN is part of the Extended SQLVAR. it contains a pointer to a 4-byte long buffer that contains the actual length in bytes (even for DBCLOB) of the data in the buffer pointed to from the SQLDATA field in the matching base SQLVAR. then the actual length is stored in the 4 bytes immediately before the start of the data. or DBCLOB) host variable. v A +237 warning is returned in the SQLCODE field of the SQLCA if at least enough were specified for the Base SQLVAR Entries. SQLDATALEN SQLDATALEN is part of the Extended SQLVAR. and DBCLOB) host variables only. It is a 16-byte pointer variable that specifies the address of the length of the host variable. CLOB. The default for graphic host variables is the associated double-byte CCSID for the job CCSID. For distinct types. Applications that use the defaults do not need to pass CCSID information. The actual length indicates the number of bytes for a BLOB or CLOB. For LOBs. but no Extended SQLVARs are returned. they contain the distinct type name. Extended SQLVARs are only needed (for all columns of the result) if the result includes any LOB or distinct type columns. Dynamic SQL Applications 207 . If this field is not NULL. these entries are not necessary. and SQLDATA points to the first byte of the field length. and the number of characters for a DBCLOB. the default CCSID for the job is used. It is a 4-byte integer variable that specifies the length attributes of a LOB (BLOB. If this field is NULL. If locators are used to represent LOBs. CLOB. The number of Extended SQLVAR occurrences needed depends on the statement that the SQLDA was provided for and the data types of the columns or parameters being described. The Base SQLVAR entries are returned. If a CCSID is not passed. 65535 is used. or it can be developed within an application program. Note: In PL/I the ALLOCATE statement is the only way to ensure the allocation of a quadword boundary. set an initial value equal to the number of SQLVAR array elements. because each item in the select-list must have a corresponding entry in SQLVAR. In the following example.) The techniques for acquiring storage are language dependent. Suppose. For a column name. even if they return only one row. named DSTRING) is then processed. The SQLDA must be allocated on a 16-byte boundary. in this example. Dynamic SELECT statements must not have an INTO clause. Therefore. The amount of storage you need to allocate depends on how many elements you want to have in the SQLVAR array. v For a label. Each column you select must have a corresponding SQLVAR array element. plus 16 for a total of 1616 bytes). it is impossible to know how many columns will be accessed. Example of a Select-Statement for Allocating Storage for SQLDA The SELECT statement can be read from a display station or from a host variable. This means that the SQLVAR array should have a dimension of 20 (for an SQLDA size 20 x 80. the database manager sets this to the first 20 bytes of the label. The host variable (for example. the database manager sets this to the fully qualified distinct type name.EMPLOYEE WHERE LASTNAME = 'PARKER' Note: The SELECT statement has no INTO clause. The header is followed by a varying-length array section (SQLVAR). or 1600. The following example shows a SELECT statement read from a display station: SELECT WORKDEPT. When the statement is read. as shown: EXEC SQL PREPARE S1 FROM :DSTRING. 208 DB2 UDB for AS/400 SQL Programming V4R4 . (Allocating storage is not necessary in REXX. Because SELECT statements are specified at run time. each element of which is 80 bytes in length. Consequently. it is truncated. set SQLN to 20: Allocate space for an SQLDA of 1616 bytes on a quadword boundary SQLN = 20. The SQLDA consists of a fixed-length header. that no more than 20 columns are ever expected to be accessed by a single SELECT statement. Allocating Storage You can allocate storage for the SQLDA. v If the qualified name is longer than 30 bytes. PHONENO FROM CORPDATA. you must estimate the number of columns. Having allocated what you estimated to be enough space for your SQLDA in the SQLN field of the SQLDA. 16 bytes long. using the PREPARE statement. It is a variable-length character variable with a maximum length of 30.| | | | | | | | | | | SQLDATATYPE_NAME SQLDATATYPE_NAME is part of the Extended SQLVAR. however. the number of columns listed in your SELECT statement determines how many SQLVAR array elements you should allocate. it is assigned to a host variable. It is set to one of the following: v For a distinct type column. the database manager sets this to the column name. Therefore. because the SQLVAR has too many elements. SQL sets the SQLD to the actual number of columns specified by the SELECT statement. as follows: EXEC SQL DESCRIBE S1 INTO :SQLDA. SQLDABC is the byte count or size of the SQLDA. SQL cannot describe the select-list. The example for running the SELECT statement for S1 is: SELECT WORKDEPT. IF SQLN <= SQLD THEN DO. allocate a larger SQLDA based on the value in SQLD.Having allocated storage. let the SELECT statement contain 27 select-list expressions instead of the 20 or less that you estimated. For example. after a DESCRIBE. you should compare the SQLN to the SQLD. When the DESCRIBE statement is run.*/ /*Reset SQLN to the larger value. Because the SQLDA was only allocated with an SQLVAR dimension of 20 elements. SQL places values in the SQLDA that provide information about the select-list. Chapter 10. If the value of SQLD is greater than the value of SQLN. The following Figure 9 shows the contents of the SQLDA after the DESCRIBE is run: SQLDA Size SQLDA (8 bytes) 453 37 SQLVAR Element 1 (80 bytes) 8 0 WORKDEPT 3 1616 SQLDA (4 bytes) (reserved) 20 SQLN (2 bytes) 2 SQLD (2 bytes) 453 37 SQLVAR Element 2 (80 bytes) 7 0 4 (reserved) P H O N E N O RV3W188-0 Figure 9. /*Allocate a larger SQLDA using the value of SQLD. Contents of SQLDA after a DESCRIBE Is Run SQLDAID is an identifier field initialized by SQL when a DESCRIBE is run. and the remainder of the structure is ignored.EMPLOYEE WHERE LASTNAME = 'PARKER' Your program might have to alter the SQLN value if the SQLDA is not large enough to contain the described SQLVAR elements. Dynamic SQL Applications 209 .*/ EXEC SQL DESCRIBE S1 INTO :SQLDA. You can ignore these for now. you can now issue a DESCRIBE statement. EXEC SQL DESCRIBE S1 INTO :SQLDA. END. PHONENO FROM CORPDATA. SQLIND. 210 DB2 UDB for AS/400 SQL Programming V4R4 . You can specify it this way: EXEC SQL DESCRIBE S1 INTO:SQLDA USING LABELS. If you specify LABELS. One of the parameters associated with the PREPARE and DESCRIBE statements is the USING clause. a code that describes the data type of the expressions and whether nulls are applicable or not. SQL sets SQLD to 0. such as functions (for example. labels.EMPLOYEE WHERE LASTNAME = 'PARKER' The first item in the select-list is WORKDEPT. If you specify ALL. SQLNAME is an empty string. Your program must now analyze the elements of SQLVAR. we identified that each SQLVAR element contains the fields SQLTYPE. The character data itself is usually the name of a column used in the SELECT statement (WORKDEPT in the above example. If you specify NAMES (or omit the USING parameter entirely). For WORKDEPT. and SQLNAME. SUM(SALARY)). This specifies that WORKDEPT is a fixed-length character string (CHAR) column and that nulls are permitted in the column. Because the data type of WORKDEPT is CHAR. you can describe each statement (after it is prepared) to determine whether it is a SELECT statement. and system column names are placed in the field with their corresponding lengths. the first 4 bytes of SQLDATA were set to the CCSID of the character column (see Figure 9 on page 209). names and labels are both placed in the field with their corresponding lengths. SQL returns. remember to triple the size of the SQLVAR array. PHONENO FROM CORPDATA.If you use DESCRIBE on a non SELECT statement. column names. In these cases. only the system column names are placed in the SQLNAME field. If you specify SYSTEM NAMES. SQLRES. only labels associated with the columns listed in your SQL statement are entered here. This sample routine is designed to process only SELECT statements. At the beginning of this section. Remember that each element describes a single select-list expression.) The exceptions to this are select-list items that are unnamed. and labels are placed in the field with their corresponding lengths. a storage area large enough to hold a CHAR(3) string is needed. labels are placed in the SQLNAME field for those columns that have labels. If you specify BOTH. when the SELECT statement is later run. if your program is designed to process both SELECT and non SELECT statements. and constants. For example. only column names are placed in the SQLNAME field. SQLDATA. The first 2 bytes of SQLNAME contain the length of the character data. the SQLD is not checked. If you specify ALL. Therefore. SQLLEN. the column names are entered. If you specify ALL: v Names. SQL sets SQLLEN equal to the length of the character string. A+B−C). Consider again the SELECT statement that is being processed: SELECT WORKDEPT. SQL sets SQLLEN to the length of the column. otherwise. SQL sets SQLTYPE to 453 in SQLVAR element 1 (see Figure 9 on page 209). The last field in an SQLVAR element is a varying-length character string called SQLNAME. expressions (for example. If you specify ANY. Because the data type of WORKDEPT is CHAR FOR SBCS DATA. Therefore. you must remember to double the size of the SQLVAR array because you are including twice the number of elements. SQLNAME can also contain a label rather than a name. that length is 3. however. If you specify BOTH. in the SQLTYPE field. SQLIND points to the place where the null indicator is to be put. /*Allocate an SQLDA of 1616 bytes. a character field of length 4 must be allocated. SQL sets SQLLEN to 4. After the storage is allocated. the second SQLVAR element contains the information for the second column used in the select: PHONENO. After analyzing the result of the DESCRIBE. For WORKDEPT. For more information on the USING option and on column labels. you can allocate storage for variables containing the result of the SELECT statement. /*Read a statement into the DSTRING varying-length character string host variable. The 453 code in SQLTYPE specifies that PHONENO is a CHAR column.*/ Chapter 10.v The size of the SQLVAR array must triple because you are including the number of elements. For a CHAR data type of length 4. EXEC SQL DESCRIBE S1 INTO :SQLDA. SQLDATA points to the place where the results are to be put.*/ SQLN =20. For each element of the SQLVAR array.*/ EXEC SQL PREPARE S1 FROM :DSTRING. for PHONENO.*/ /*Set SQLDATA and SQLIND for each column of the result table. a character field of length 3 must be allocated. Dynamic SQL Applications 211 . you must set SQLDATA and SQLIND to point to the appropriate areas.*/ /*Allocate storage to hold one row of the result table. In the example. The following figure shows what the structure looks like now: SQLDA Size S 453 Q 3 L D A (reserved) 1616 20 2 FLDA: (CHAR(3)) Address of FLDA SQLVAR Element 1 (80 bytes) Address of FLDAI 8 WORKDEPT FLDB: (CHAR(4)) 453 SQLVAR Element 2 (80 bytes) 4 (reserved) Address of FLDB Address of FLDBI 7 P H O N E N O Indicator Variables: (halfword) FLDAI: FLDBI: RV3W189-0 This is what was done so far: EXEC SQL INCLUDE SQLDA. see the DB2 UDB for AS/400 SQL Reference book. /*Analyze the results of the DESCRIBE. As you can see. the FETCH statement tells SQL to return results into areas described by the descriptor called SQLDA. The actual retrieval of result rows is made as follows: EXEC SQL OPEN C1.. Dynamically defined SELECT statements must not have an INTO statement. the results pointed to by SQLDATA*/ END. The cursor is opened. the only difference is that the name of the prepared SELECT statement (S1) is used instead of the SELECT statement itself.. Special forms of the DECLARE. there is no list of output host variables. the results are returned into the storage areas pointed to by the SQLDATA and SQLIND fields of the SQLVAR elements. In particular. all dynamically defined SELECT statements must use a cursor. /*Display ('END OF LIST')*/ EXEC SQL CLOSE C1. DO WHILE (SQLCODE = 0). SQLDA Size S 453 Q 3 L D A (reserved) 1616 20 2 FLDA: (CHAR(3)) E11 Address of FLDA SQLVAR Element 1 (80 bytes) Address of FLDAI 8 WORKDEPT FLDB: (CHAR(4)) 4502 453 SQLVAR Element 2 (80 bytes) 4 (reserved) Address of FLDB Address of FLDBI 7 P H O N E N O Indicator Variables: (halfword) FLDAI: FLDBI: 0 0 RV3W190-0 The meaning of the SMALLINT pointed to by SQLIND is the same as any other indicator variable: 212 DB2 UDB for AS/400 SQL Programming V4R4 . The SELECT result rows are then returned using FETCH. Notice that there are no input host variables needed for the example SELECT statement. Rather. The following figure shows what the structure looks like after the FETCH statement has been processed. The same SQLDA that was set up by DESCRIBE is now being used for the output of the SELECT statement. and FETCH are used for dynamically defined SELECT statements.Using a Cursor You are now ready to retrieve the SELECT statements results. /*Display . On the FETCH statement. OPEN. The DECLARE statement for the example statement is: EXEC SQL DECLARE C1 CURSOR FOR S1. EXEC SQL FETCH C1 USING DESCRIPTOR :SQLDA. and the result table is evaluated. Therefore. using different values for LASTNAME. 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. PHONENO FROM CORPDATA. 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. In the example. This SQL statement is used to not only open a cursor. Denotes that the returned value was truncated because the storage area furnished was not large enough. Using Parameter Markers In the example we are using. and SQLNAME)? v Do you want an indicator variable? Chapter 10. unlike those previously described. The descriptor name that you specify with this statement must identify an SQLDA that contains a valid description of those host variables. That is. you need to determine: v How many ? parameter markers are there? v What are the data types and attributes of these parameters markers (SQLTYPE. SQLDAID. Note: Unless HOLD is specified. Specifically.) Therefore. you can substitute the values contained in specific host variables for the parameter markers included in the WHERE clause of the SELECT statement. SQLRES. but to replace each parameter marker with the value of the corresponding host variable. and SQLNAME can be left blank (SQLNAME (SQLCCSID in REXX) can be set if a specific CCSID is needed. When you use the SQLDA for input to the OPEN statement with the USING DESCRIPTOR clause. you need to use the OPEN statement with the USING DESCRIPTOR clause. it is not used as output from a DESCRIBE statement. it was: WHERE LASTNAME = 'PARKER' If you want to run the same SELECT statement several times. is not used to return information on data items that are part of a SELECT list. your application cannot know the number or types of the parameters until run time.EMPLOYEE WHERE LASTNAME = ? When your parameters are not predictable. not all of its fields have to be filled in. and by using a USING DESCRIPTOR on the OPEN statement. which must be designed to place appropriate values into the necessary fields of the SQLDA. when you use this method for replacing parameter markers with host variable values. To code such a program.0 <0 >0 Denotes that the returned value is not null. The indicator variable contains the length before truncation. the SELECT statement that was dynamically run had predictable parameters (input host variables) in the WHERE clause. Dynamic SQL Applications 213 . This SQLDA. but as input to the OPEN statement. Denotes that the returned value is null. dynamic cursors are closed during COMMIT or ROLLBACK. you can use an SQL statement such as PREPARE or EXECUTE (as described in “Using the PREPARE and EXECUTE Statements” on page 200) like this: SELECT WORKDEPT. You can arrange to receive this information at the time your application is run. SQLLEN. 2. Set SQLN and SQLD to the number of ? parameter markers. This is not applicable in REXX. Allocate storage to hold the input values (the ? values).) If your application uses parameter markers.In addition. 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. Read a statement into the DSTRING varying-length character string host variable. Allocate an SQLDA of that size. and they are in a CCSID other than the job default CCSID. g. e. If graphic variables are used and they have a CCSID other than the associated DBCS CCSID for the job CCSID. 5. you may want to determine what category of statement it is. and indicators. set SQLNAME (SQLCCSID in REXX) accordingly. The statement can then be processed normally. d. Determine the data types. lengths. you can write code to look for the SELECT keyword. set the SQLNAME (SQLCCSID in REXX) to that CCSID. SQLN is not applicable in REXX. Determine the number of ? parameter markers. f. 3. Set these values. b. h. Set SQLDATA and SQLIND (if applicable) for each ? parameter marker. your program has to: 1. Set SQLDABC equal to SQLN*LENGTH(SQLVAR) + 16. if the routine is to handle both SELECT and non SELECT statements. If character variables are used. For each ? parameter marker: a. c. This is not applicable in REXX. Set SQLTYPE and SQLLEN. (Alternatively. 4. 214 DB2 UDB for AS/400 SQL Programming V4R4 . 6. instead of coding an actual department number in a WHERE clause. such as tables or views. then name the host variables with an INTO clause.EMPLOYEE table. Note: By using a host variable instead of a literal value in an SQL statement. you give the application program the flexibility it needs to process different rows in a table or view. For example. 1999 215 . Host variables are commonly used in SQL statements in these ways: 1. Host variables may not be used to identify SQL objects. For example. the values are put into data items defined by your program and specified with the INTO clause of a SELECT INTO or FETCH statement. The INTO clause names one or more host variables that you want to contain column values returned by SQL. the set of values for the columns of a row). For example: © Copyright IBM Corp. except in the DESCRIBE TABLE statement. and WORKDEPT column values from rows in the CORPDATA. or to replace a literal value in an expression. usually as the source or target for the value of a column. For example. 2.EMPLOYEE WHERE EMPNO = :EMPID END-EXEC. Common Concepts and Rules for Using SQL with Host Languages This chapter describes some concepts and rules that are common to using SQL statements in a host language that involve: v Using host variables in SQL statements v Handling SQL error and return codes v Handling exception conditions with the WHENEVER statement Using Host Variables in SQL Statements When your program retrieves data. 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. you can retrieve the name of the employee whose number is 000110 with: MOVE '000110' TO EMPID. The data items are called host variables. The host variable and column must be data type compatible. you can use a host variable set to the department number you are currently interested in. EXEC SQL SELECT LASTNAME INTO :PGM-LASTNAME FROM CORPDATA. if you have defined a field called EMPID that contains an employee number. A host structure array is an array of host structures used in the multiple-row FETCH and blocked INSERT statements. A host variable is a field in your program that is specified in an SQL statement. LASTNAME. In a WHERE clause: You can use a host variable to specify a value in the predicate of a search condition. 1997. You could define a host variable in your program to hold each column. A host structure is a group of host variables used as the source or target for a set of selected values (for example. suppose you are retrieving the EMPNO.Chapter 11. 3. 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. Your program can return a set of column values intermixed with host variable values and literal constants. :CBLNAME. SALARY + :RAISE INTO :PROCESS. The results are: PROCESS A PERSON-NAME LUTZ EMP-SAL 29840 EMP-RAISE EMP-TTL 4476 34316 4. and CALL statements. EXEC SQL SELECT "A". Assignment Rules SQL column values are set to (or assigned to) host variables during the running of FETCH and SELECT INTO statements. :EMP-TTL FROM CORPDATA. character and DBCS graphic parameters are compatible with UCS-2 parameters if conversion is supported. and CBLDEPT receives the value from WORKDEPT. All numeric values are compatible. you are not restricted to the column names of tables and views. WORKDEPT INTO :CBLEMPNO. For example: MOVE '000220' TO PERSON. :RAISE. UPDATE. As a value in a SELECT clause: When specifying a list of items in the SELECT clause. :EMP-RAISE. LASTNAME. if conversion is supported between the CCSIDs. All character and DBCS graphic strings are compatible with UCS-2 graphic columns for assignment operations. 216 DB2 UDB for AS/400 SQL Programming V4R4 . see the DB2 UDB for AS/400 SQL Reference book. Strings cannot be assigned to numeric columns or numeric host variables. SQL column values are set from (or assigned from) host variables during the running of INSERT. v All character and DBCS graphic strings are compatible with UCS-2 graphic columns if conversion is supported between the CCSIDs. Conversions are performed by SQL whenever necessary.EXEC SQL SELECT EMPNO. LASTNAME. For the CALL statement. v A null value cannot be assigned to a host variable that does not have an associated indicator variable. :PERSON-NAME. All graphic strings are compatible if the CCSIDs are compatible. SALARY.EMPLOYEE WHERE EMPNO = :PERSON END-EXEC.EMPLOYEE WHERE EMPNO = :EMPID END-EXEC. In this example. CBLNAME receives the value from LASTNAME. the host variable CBLEMPNO receives the value from EMPNO. :EMP-SAL. As a value in other clauses of an SQL statement: The SET clause in an UPDATE statement The VALUES clause in an INSERT statement The CALL statement For more information on these statements. :CBLDEPT FROM CORPDATA. The result. The rules for CCSIDs are as follows: v If the CCSID of the source matches the CCSID of the target. SQLWARN0 and SQLWARN1 (in the SQLCA) are set to W. The insert or update value of a timestamp column must be a timestamp or a string representation of a timestamp. the string is truncated on the right by the necessary number of characters. MIXED data. is still a valid MIXED character string. times are only compatible with times or string representations of times. a character column. a DBCS-open or DBCS-either column or variable. If this occurs. However.) v When a MIXED character result column is assigned to a MIXED column. Chapter 11. 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. the string is padded on the right with the necessary number of blanks. a character column. 8. the length of the string value must not be greater than the length attribute of the column. The insert or update value of a time column must be a time or a string representation of a time. v When the value of a result column is assigned to a fixed-length host variable or when the value of a host variable is assigned to a fixed-length CHAR result column and the length of the string value is less than the length attribute of the target. DBCS data. a character column. therefore. See DECLARE VARIABLE in the DB2 UDB for AS/400 SQL Reference book. Rules for CCSIDs CCSIDs must be considered when you assign one character or graphic value to another. The insert or update value of a date column must be a date or a string representation of a date. A timestamp can be assigned only to a timestamp column. A time can be assigned only to a time column. This includes the assignment of host variables. the value of the MIXED character result column must be a valid MIXED character string. (Trailing blanks are normally included in the length of the string. or a character variable 8. or a character variable. The database manager uses a common set of system services for converting SBCS data. and timestamps are only compatible with timestamps or string representations of timestamps. or a character variable. or the DECLARE VARIABLE statement is used and a MIXED CCSID or the FOR MIXED DATA clause is specified. the value is assigned without conversion.v Different types of date/time values are not compatible. Dates are only compatible with dates or string representations of dates. a DBCS-open or DBCS-either column or variable. Common Concepts and Rules for Using SQL with Host Languages 217 . DBCS-open variables are also declared if the job CCSID indicates MIXED data. v When the value of a result column is assigned to a host variable and the string value of the result column is longer than the length attribute of the host variable. v When a MIXED character result column is truncated because the length of the host variable into which it was being assigned was less than the length of the string. the shift-in character at the end of the string is preserved. A date can be assigned only to a date column. and graphic data. Rules for String Assignment Rules regarding character string assignment are: v When a string is assigned to a column. a DBCS-open or DBCS-either column or variable. for string assignment trailing blanks are not included in the length of the string. – When a floating-point number is converted to decimal or numeric. or *ISO date formats. to the precision and scale of the target. Rules for Date. in the fractional part of the number. In ILE RPG. the temporary result has a precision of 11 and a scale of 0. the temporary result has a precision of 5 and a scale of 0. the fractional part of a number is truncated. If necessary. 218 DB2 UDB for AS/400 SQL Programming V4R4 . The host variable must be a fixed or variable-length character string variable with a length of at least 10 bytes for *USA. if necessary. Leading zeros are not omitted from any part of the date representation.v If the sub-type for the source or target is BIT. A double-precision floating point field can only contain 16 decimal digits. v If conversion is defined and needed. the value is not assigned and an error message is issued. the host variable can also be a date variable. or binary column or host variable. the value is assigned without conversion. A single-precision floating-point field can only contain seven decimal digits. Any whole part of a number that contains more than 16 digits is altered due to rounding. 8 bytes for *MDY. the number is first converted to a temporary decimal or numeric number and then converted. v If conversion is not defined between specific CCSIDs. does not fit into the target host variable or column. *JIS. For more information on CCSIDs. Rules for Numeric Assignment Rules regarding numeric assignment are: v The whole part of a number may be altered when converting it to floating-point. numeric. *DMY. see the International Application Development book. the string is padded on the right with blanks. The necessary number of leading zeros is added or deleted. or *YMD date formats. or the necessary number of trailing digits is eliminated. Time. to the precision and scale of the target. If the number. v The whole part of a number is never truncated. If the length is greater than 10. – When a halfword binary integer (SMALLINT) with 0 scale is converted to decimal or numeric. the date is converted to the string representation specified by the DATFMT and DATSEP parameters of the CRTSQLxxx command. v Whenever a decimal. if necessary. v If the value is either null or an empty string. numeric. Any whole part of a number that contains more than seven digits is altered due to rounding. v When a binary or floating-point number is assigned to a decimal or numeric column or host variable. the source value is converted to the CCSID of the target before the assignment is performed. the number is converted. *EUR. the necessary number of trailing zeros is added. or binary number is assigned to a decimal. as converted. a negative SQLCODE is returned. or 6 bytes for the *JUL date format. the temporary result has a precision of 31 and the maximum scale that allows the whole part of the number to be represented without loss of either significance or accuracy. – When a fullword binary integer (INTEGER) is converted to decimal or numeric. and Timestamp Assignment When a date is assigned to a host variable. the value is assigned without conversion. and if an indicator variable is specified.EMPLOYEE WHERE EDLEVEL < 18 END-EXEC. When the database manager returns a null value. Common Concepts and Rules for Using SQL with Host Languages 219 . v If you do not use an indicator variable and the result column is a null value. the host variable is padded on the right with blanks.When a time is assigned to a host variable. the timestamp is converted to its string representation. If the length of the host variable is greater than the string representation of the time. 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. You specify an indicator variable (preceded by a colon) immediately after the host variable or immediately after the keyword INDICATOR. SQL sets the indicator variable to −2. you can test the indicator variable. the length of the host variable must be at least 8 bytes if seconds are to be included. For example: EXEC SQL SELECT COUNT(*). v If the *HMS. the host variable will be set to the default value for the result column. the host variable does not include all the digits of the microseconds. the length of the host variable must not be less than 8. a negative SQLCODE is returned. In ILE RPG. AVG(SALARY) INTO :PLICNT. You can then test INDNULL to see if it contains a negative value. *EUR. Leading zeros are not omitted from any part. Leading zeros are not omitted. or *JIS format is used. When a timestamp is assigned to a host variable. the host variable can also be a time variable. the time is converted to the string representation by the TIMFMT and TIMSEP parameters of the CRTSQLxxx command. you know SQL returned a null value. SQLWARN0 and SQLWARN1 (in the SQLCA) are set to W. When the database manager returns a value from a result column. and 5 bytes if only hours and minutes are needed. the indicator variable contains a positive integer that specifies the original length of the string. If it does. it is set to the actual number of seconds truncated. Chapter 11. v If the *USA format is used. SQL puts a -1 in the indicator variable. :PLISAL:INDNULL FROM CORPDATA. If the value of the indicator variable is less than zero. The host variable must be a fixed or variable-length character string variable with a length of at least 19 bytes. If truncation occurs. You can also use an indicator variable to verify that a retrieved string value has not been truncated. In ILE RPG. If the length is greater than 26. The host variable must be a fixed or variable-length character string variable. the string is padded on the right with blanks. In this case. v If the value for the result column causes a data mapping error. the host variable can also be a timestamp variable. you know the value of the results column is null. If the length is less than 26. *ISO. SQL checks the indicator variable (if it exists). you must use a corresponding structure for the indicator variables to determine which (if any) selected column values are null..Always test for NULL in a column by using the IS NULL predicate. you can specify that a value be put in a column (using an INSERT or UPDATE statement). When processing UPDATE or INSERT statements.EMPLOYEE WHERE EDLEVEL>:EDUC-LEVEL END-EXEC. SALIND is an array containing 3 values. MOVE 20 TO EDUC-LEVEL.. To provide the capability to set a column to a null value.. The result of this example will select no rows. for example. MIN-SAL) is not changed for the selected row. . you can add an indicator structure name to the host structure name. in COBOL: 01 SAL-REC. you can write the following statement: 220 DB2 UDB for AS/400 SQL Programming V4R4 . For example. If it contains a value greater than -1. 01 SALTABLE. 10 MIN-SAL PIC S9(6)V99 USAGE COMP-3. the associated host variable contains a value for the column. the column value is set to null. If. EXEC SQL SELECT MIN(SALARY). For example. 02 SALIND PIC S9999 USAGE COMP-4 OCCURS 3 TIMES.. then the corresponding host variable in the host structure (that is. If it contains a negative value. In this example. 10 AVG-SAL PIC S9(6)V99 USAGE COMP-3. 01 EDUC-LEVEL PIC S9999 COMP-4. EXEC SQL. In the above example. 10 MAX-SAL PIC S9(6)V99 USAGE COMP-3. . AVG(SALARY). Used to Set Null Values You can use an indicator variable to set a null value in a column. This allows SQL to notify your program about each null value returned to a host variable in the host structure.. Therefore.. SQL selects the column values of the row into a host structure. Used with Host Structures You can also specify an indicator structure (defined as an array of halfword integer variables) to support a host structure. each of which can be tested for a negative value. If the results column values returned to a host structure can be null. For example: WHERE expression IS NULL Do not test for NULL in this way: MOVE -1 TO HUIND. but you may not be sure that the value was specified with the input data. SALIND(1) contains a negative value.WHERE column-name = :HUI :HUIND The EQUAL predicate will always be evaluated as false when it compares a null value. MAX(SALARY) INTO :SAL-REC:SALIND FROM CORPDATA. The main purpose for SQLSTATE is to provide common return codes for common return conditions among the different IBM relational database systems. the SQLCODE is a positive number and SUBSTR(SQLSTATE. as follows: MOVE -1 TO PHONEIND. to tell SQL that NEWPHONE contains a null value. the SQLCODE returned to your program is zero. The return codes indicate the success or failure of the running of your statement. the SQLCODE is a negative number and SUBSTR(SQLSTATE.1. Especially important are the following SQLCA fields: SQLCODE SQLSTATE SQLERRD(3) SQLWARN0 Return code. your program will continue to the next statement. see the DB2 UDB for AS/400 SQL Reference book. If your SQL statement is processed without encountering an error or warning condition. Otherwise. Continuing to run after an error can produce unpredictable results.1. one of the SQL warning flags (SQLWARN1) indicates truncation. the SQLCODE is zero and the SQLSTATE is '00000'. or '02'. SQLSTATEs are particularly useful when handling problems with distributed database operations. or deleted by SQL. at least one of the SQL warning flags (SQLWARN1 through SQLWARNA) is set. The number of rows updated.EXEC SQL UPDATE CORPDATA. '01'. Note: There are situations when a zero SQLCODE is returned to your program and the result might not be satisfactory. Because the SQLCA is a valuable problem-diagnosis tool. if a value was truncated as a result of running your program. set PHONEIND to zero by preceding the statement with: MOVE 0 to PHONEIND. SQL places a return code in the SQLCODE and SQLSTATE fields. When NEWPHONE contains other than a null value. In this case. Common Concepts and Rules for Using SQL with Host Languages 221 . Chapter 11. set PHONEIND to a negative value.EMPLOYEE SET PHONENO = :NEWPHONE:PHONEIND WHERE EMPNO = :EMPID END-EXEC. However. Attention: If you do not test for negative SQLCODEs or specify a WHENEVER SQLERROR statement. the SQLSTATE is not '00000'. For more information. inserted. Handling SQL Error Return Codes When an SQL statement is processed in your program. Return code. If SQL encounters an exception but valid condition while processing your statement.2) is '01' or '02'.2) is not '00'. If SQL encounters an error while processing the statement. If set to W. it is a good idea to include in your application programs the instructions necessary to display some of the information contained in the SQLCA. For example. the first WHENEVER statement applies to all subsequent SQL statements in the source program until another WHENEVER statement is specified.For more information about the SQLCA. The WHENEVER statement allows you to specify what you want to do whenever a general condition is true. Specify NOT FOUND to indicate what you want done when an SQLCODE of +100 and a SQLSTATE of '02000' is returned because: v After a single-row SELECT is issued or after the first FETCH is issued for a cursor. see Appendix B.2) > ’02’). if the value of a column was truncated when it was moved into a host variable.1. or warning exists as a result of running an SQL statement. An exception condition handling subroutine (part of your program) can then examine the SQLCODE or SQLSTATE field to take an action specific to the error or exception situation. v After a subsequent FETCH. Note: The WHENEVER statement is not allowed in REXX procedures. or branch to another area in your program if an error.1. “SQL Communication Area” in the DB2 UDB for AS/400 SQL Reference book. NOT FOUND 222 DB2 UDB for AS/400 SQL Programming V4R4 . no more rows satisfying the cursor select-statement are left to retrieve. Handling Exception Conditions with the WHENEVER Statement The WHENEVER statement causes SQL to check the SQLSTATE and SQLCODE and continue processing your program. see Chapter 17. You can specify more than one WHENEVER statement for the same condition. SQLERROR Specify SQLERROR to indicate what you want done when an error code is returned as the result of an SQL statement (SQLCODE < 0) (SUBSTR(SQLSTATE. The WHENEVER statement looks like this: EXEC SQL WHENEVER condition action END-EXEC. Coding SQL Statements in REXX Applications.2) =’01’). For information on handling exception conditions in REXX. For a listing of DB2 UDB for AS/400 SQLCODEs and SQLSTATEs. see Appendix B. exception. When you do this. There are three conditions you can specify: SQLWARNING Specify SQLWARNING to indicate what you want done when SQLWARN0 = W or SQLCODE contains a positive value other than 100 (SUBSTR(SQLSTATE. For example. Note: SQLWARN0 could be set for several different reasons. your program might not regard this as an error. the data the program specifies does not exist. . the WHENEVER statement must precede the first SQL statement it is to affect. you might want to examine the SQLCODE or SQLSTATE value after each SQL statement is run and call a subroutine. This causes your program to branch to an area in the program. If the WHENEVER follows the SQL statement. GO TO statement: v Must be a section name or an unqualified paragraph name in COBOL v Is a label in PL/I and C v Is the label of a TAG in RPG For example. However. The WHENEVER statement does not provide a CALL to a subroutine option.. no row meets the search condition. In other words. a DELETE. You can also specify the action you want taken: CONTINUE GO TO label This causes your program to continue to the next statement. Common Concepts and Rules for Using SQL with Host Languages 223 . Note: A WHENEVER statement affects all subsequent source SQL statements until another WHENEVER is encountered. regardless of the path the program takes. Because of this.. if there is only one) are governed by the first WHENEVER statement. you expect that SQL will eventually be unable to find another row when the FETCH statement is issued. 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. The WHENEVER . rather than use a WHENEVER statement. or an INSERT. To prepare for this situation.. the branch is not taken on the basis of the value of the SQLCODE and SQLSTATE set by that SQL statement. if your program checks the SQLCODE or SQLSTATE directly. Chapter 11. For this reason. specify a WHENEVER NOT FOUND GO TO .v After an UPDATE. all SQL statements coded between two WHENEVER statements (or following the first. The label for that area may be preceded with a colon. if you are retrieving rows using a cursor. the check must be done after the SQL statement is run. 224 DB2 UDB for AS/400 SQL Programming V4R4 . Chapter 12. The SQLCODE. SQLSTATE. }. C program refers to ILE C for AS/400 programs. long sqlcode. 1999 225 . #define SQLCODE sqlca. Defining the SQL Communications Area A C or C++ program that contains SQL statements must include one or both of the following: v An SQLCODE variable declared as long SQLCODE v An SQLSTATE variable declared as char SQLSTATE[6] Or. A detailed sample C program. and SQLCA variables must appear before any executable statements.sqlwarn[2] #define SQLWARN3 sqlca. unsigned char sqlerrp[8].sqlwarn[0] #define SQLWARN1 sqlca. unsigned char sqlstate[5].sqlwarn[3] © Copyright IBM Corp. Using the SQL INCLUDE statement requests the inclusion of a standard declaration: EXEC SQL INCLUDE SQLCA . v An SQLCA (which contains an SQLCODE and SQLSTATE variable). You can code the SQLCA in a C or C++ program either directly or by using the SQL INCLUDE statement. This chapter also defines the requirements for host structures and host variables. Coding SQL Statements in C and C++ Applications This chapter describes the unique application and coding requirements for embedding SQL statements in a C or C++ program. The scope of the declaration must include the scope of all SQL statements in the program. long sqlcabc. showing how SQL statements can be used. Sample Programs Using DB2 UDB for AS/400 Statements. The SQLCODE and SQLSTATE values are set by the database manager after each SQL statement is executed. A standard declaration includes both a structure definition and a static data area named 'sqlca'.sqlcode #define SQLWARN0 sqlca. is provided in Appendix C. 1997. unsigned char sqlwarn[11]. The included C and C++ source statements for the SQLCA are: #ifndef SQLCODE struct sqlca { unsigned char sqlcaid[8]. An application can check the SQLCODE or SQLSTATE value to determine whether the last SQL statement was successful.sqlwarn[1] #define SQLWARN2 sqlca. unsigned char sqlerrmc[70]. long sqlerrd[6]. C++ program refers to ILE C++ programs or programs that are created with the VisualAge C++ for AS/400 compiler. short sqlerrml. struct sqlvar { short sqltype. A standard declaration includes only a structure definition with the name ’sqlda’.sqlwarn[10] #define SQLSTATE sqlca.sqlwarn[5] #define SQLWARN6 sqlca. When a declare for SQLSTATE is found in the program and the precompiler provides the SQLCA. unsigned char *sqldata.USING DESCRIPTOR descriptor-name Unlike the SQLCA.USING DESCRIPTOR descriptor-name FETCH. Because of these lengths. short sqld. Using the SQL INCLUDE statement requests the inclusion of a standard SQLDA declaration: EXEC SQL INCLUDE SQLDA.#define SQLWARN4 sqlca. long sqldabc.sqlwarn[9] #define SQLWARNA sqlca. C and C++ declarations that are included for the SQLDA are: #ifndef SQLDASIZE struct sqlda { unsigned char sqldaid[8]. Defining SQL Descriptor Areas The following statements require an SQLDA: EXECUTE.sqlwarn[7] #define SQLWARN8 sqlca. SQLCADE replaces SQLCODE. You can code an SQLDA in a C or C++ program either directly or by using the SQL INCLUDE statement.. and an SQLDA can have any valid name. Note: Many SQL error messages contain message data that is of varying length. struct sqlname { 226 DB2 UDB for AS/400 SQL Programming V4R4 .. “SQL Communication Area” in the DB2 UDB for AS/400 SQL Reference book... short sqllen. SQLSTOTE replaces SQLSTATE.sqlwarn[6] #define SQLWARN7 sqlca. The lengths of these data fields are embedded in the value of the SQLCA sqlerrmc field.. see Appendix B. When a declare for SQLCODE is found in the program and the precompiler provides the SQLCA. printing the value of sqlerrmc from a C or C++ program might give unpredictable results.USING DESCRIPTOR descriptor-name DESCRIBE statement-name INTO descriptor-name DESCRIBE TABLE host-variable INTO descriptor-name PREPARE statement-name INTO descriptor-name CALL..sqlwarn[8] #define SQLWARN9 sqlca. short sqln. more than one SQLDA can be in the program.USING DESCRIPTOR descriptor-name OPEN. For more information on SQLCA. short *sqlind..sqlwarn[4] #define SQLWARN5 sqlca.sqlstate #endif struct sqlca sqlca.. This is because you will not know in advance how many or what type of variables to allocate in order to receive the results of the SELECT. The type casting is only necessary for the EXECUTE.h> EXEC SQL INCLUDE SQLDA. struct sqlda *mydaptr. and FETCH statements where the application program is passing the address of the host variables in the program. For example. mydaptr->sqln = 20. just as you would for a host variable that was declared as a pointer. if you declared a pointer to an SQLDA called mydaptr. short numvars = 20. To avoid compiler errors. Dynamic SQL Applications. see the DB2 UDB for AS/400 SQL Reference book. When you have declared an SQLDA as a pointer. Embedding SQL Statements An SQL statement can be placed wherever a C or C++ statement that can be run can be placed. the SQLDASIZE macro is used to allocate storage for an SQLDA with 20 SQLVAR elements. OPEN. #include <stdlib. #define SQLDASIZE(n) (sizeof(struct sqlda) + (n-1)* sizeof(struct sqlvar)) #endif short length. 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. With dynamic SQL. SQLDA declarations can appear wherever a structure definition is allowed.} sqlvar[1]. CALL. Coding SQL Statements in C and C++ Applications 227 . Chapter 12. mydaptr = (struct sqlda *) malloc(SQLDASIZE(numvars)). . In the following example. unsigned char data[30]. your program can develop and then run SQL statements while the program is running. This helps 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. Dynamic SQL is an advanced programming technique described in Chapter 10. you must reference it exactly as declared when you use it in an SQL statement. } sqlname. For more information on the SQLDA. 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). Normal C scope rules apply. you would use it in a PREPARE statement as: EXEC SQL PREPARE mysname INTO :*mydaptr FROM :mysqlstring. . The remaining part of the SQL statement can be on more than one line.. 228 DB2 UDB for AS/400 SQL Programming V4R4 ..4..6... 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... Continuation for SQL Statements SQL statements can be contained on one or more lines. C.... assume the margins are 5 and 75.... Including Code You can include SQL statements..1...+. You can use single-line comments (comments that start with //) in C++.8 EXEC SQL SELECT * FROM GRAPHTAB WHERE GRAPHCOL = G'<AABBCCDD> <EEFFGGHHIIJJKK>'....... Comments In addition to using SQL comments (--). You cannot nest comments..2.........3...+...)..+..*/) within embedded SQL statements whenever a blank is allowed.....*.....+....8 EXEC SQL SELECT * FROM GRAPHTAB WHERE GRAPHCOL = G'<AABBCCDDEEFFGGHH> <IIJJKK>'..... The backslash (\) can be used to continue a string constant or delimited identifier.(........). *... This SQL statement has a valid graphic constant of G’<AABBCCDDEEFFGGHHIIJJKK>’. then the shift characters located at the left and right margin are removed....1. v If you are not using the default margins of 1 and 80..5. The EXEC SQL keywords must be on one line.5.....+.... you can include C comments (/*.. The redundant shifts at the margin are removed.+. *...7. or C++ statements by embedding the following SQL statement in the source code: EXEC SQL INCLUDE member-name..+.3..+. 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 .. except between the keywords EXEC and SQL. This SQL statement has a valid graphic constant of G’<AABBCCDDEEFFGGHHIIJJKK>’. but you cannot use them in C. Comments can span any number of lines.6. Constants containing DBCS data may be continued across multiple lines in two ways: v If the character at the right margin of the continued line is a shift-in and the character at the left margin of the continuation line is a shift-out. You can split an SQL statement wherever a blank can appear....+.+....+... For this example...+.4.. it is possible to place the shift characters outside of the margins.2.Each SQL statement must begin with EXEC SQL and end with a semicolon (.......+.7. Names You can use any valid C or C++ variable name for a host variable. The C NUL is a single character that compares equal to 0. It is subject to the following restrictions: Do not use host variable names or external entry names that begin with 'SQL'. and a null statement (just a semicolon). Coding SQL Statements in C and C++ Applications 229 . CRTSQLCPPI. The C and C++ languages have a null character (NUL). NULLs and NULs C. Statement Labels Executable SQL statements can be preceded with a label. For more information about CRTSQLCI. The following trigraph sequences are supported within host variable declarations: v ??( left bracket v ??) right bracket v ??< left brace v ??> right brace v ??= pound v ??/ backslash Chapter 12. Trigraphs Some characters from the C and C++ character set are not available on all keyboards. C++. DB2 UDB for AS/400 CL Command Descriptions. but for different meanings.Margins You must code SQL statements within the margins that are specified by the MARGINS parameter on the CRTSQLCI. the SQL precompiler does not recognize the SQL statement. Preprocessor Sequence You must run the SQL preprocessor before the C or C++ preprocessor. If EXEC SQL does not start within the specified margins. a null pointer (NULL). and SQL use the word null. or CVTSQLCPP command. These names are reserved for the database manager. You can enter these characters into a C or C++ source program by using a sequence of three characters that is called a trigraph. 'RDI'. CRTSQLCPPI. The length of host variable names is limited to 64. see Appendix D. and CVTSQLCPP. You cannot use C or C++ preprocessor directives within SQL statements. or 'DSN' in any combination of uppercase or lowercase letters. 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. Using Host Variables All host variables used in SQL statements must be explicitly declared.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. 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. 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. even if the host variables are in different blocks or procedures. In C++. A host variable used in an SQL statement must be declared prior to the first use of the host variable in an SQL 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. 230 DB2 UDB for AS/400 SQL Programming V4R4 . If a BEGIN DECLARE SECTION and END DECLARE SECTION are specified. The names of host variables must be unique within the program. all host variable declarations used in SQL statements must be between the BEGIN DECLARE SECTION and the END DECLARE SECTION statements. Numeric Host Variables The following figure shows the syntax for valid numeric host variable declarations. Host variables cannot be union elements. Declaring Host Variables The C and C++ precompilers recognize only a subset of valid C and C++ declarations as valid host variable declarations. All host variables within an SQL statement must be preceded by a colon (:). In C. An SQL statement that uses a host variable must be within the scope of the statement in which the variable was declared. h must be included. the header file decimal. Precision may be in the range from 1 to 31. Character Host Variables There are three valid forms for character host variables: v Single-character form v NUL-terminated character form v VARCHAR structured form All character types are treated as unsigned.Numeric auto extern static const volatile float double decimal ( precision . Chapter 12. scale signed long short int ) . Precision and scale must be integer constants. If using the decimal data type. variable-name = expression . Scale may be in the range from 0 to the precision. variable-name [ 1 ] = expression . Notes: 1. 2. Coding SQL Statements in C and C++ Applications 231 . Single-Character Form char auto extern static const volatile unsigned signed . The length must be an integer constant that is greater than 1 and not greater than 32741. the following actions are taken: v The data is truncated v The last character is the NUL-terminator v SQLWARN1 is set to ’W’ 3. or CVTSQLCPP command. then the following actions are taken: – The data is returned. Output host variables are padded with blanks. The following applies to output host variables. variable-name [ length ] = expression . Notes: 1. v If the host variable is large enough to contain the data and the NUL-terminator. 2. then the following actions are taken: – The data is returned – A NUL-terminator is not returned – SQLWARN1 is set to ’N’ v If the host variable is not large enough to contain the data. 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. If the output host variable is too small to contain both the data and the NUL-terminator. or CVTSQLCPP command.NUL-Terminated Character Form char auto extern static const volatile unsigned signed . the input variables do not need to contain the NUL-terminator. If the *NOCNULRQD option is specified on the CRTSQLCI. the following actions are taken: – The data is truncated – A NUL-terminator is not returned – SQLWARN1 is set to ’W’ 232 DB2 UDB for AS/400 SQL Programming V4R4 . and the last character is the NUL-terminator. If the *CNULRQD option is specified on the CRTSQLCI. CRTSQLCPPI. the input host variables must contain the NUL-terminator. CRTSQLCPPI. /* valid declaration of host variable vstring */ struct VARCHAR { short len. Graphic host variables There are three valid forms for graphic host variables: v Single-graphic form v NUL-terminated graphic form v VARGRAPHIC structured form Chapter 12. Example: EXEC SQL BEGIN DECLARE SECTION. Coding SQL Statements in C and C++ Applications 233 . } . unsigned signed char var-2 [ length ] . Notes: 1. char s[10]. The struct tag can be used to define other data areas. The VARCHAR structured form should be used for bit data that may contain the NULL character. but these cannot be used as host variables. variable-name = { expression .VARCHAR Structured Form struct auto extern static const volatile _Packed tag { short signed int var-1 . 4. /* invalid declaration of host variable wstring */ struct VARCHAR wstring. The VARCHAR structured form will not be ended using the nul-terminator. 3. } vstring. expression } . length must be an integer constant that is greater than 0 and not greater than 32740. var-1 and var-2 must be simple variable references and cannot be used individually as integer and character host variables. 2. length must be an integer constant that is greater than 1 and not greater than 16371. CRTSQLCPPI. but is not padded with DBCS blanks – The graphic NUL-terminator immediately follows the data 234 DB2 UDB for AS/400 SQL Programming V4R4 . Output host variables are padded with DBCS blanks. the following actions are taken: v The data is truncated v The last character is the graphic NUL-terminator v SQLWARN1 is set to ’W’ If the *NOCNULRQD option is specified on the CRTSQLCI.Single-Graphic Form wchar_t auto extern static const volatile . Notes: 1. then input host variables must contain the graphic NUL-terminator (/0/0). or CVTSQLCPP command. CRTSQLCPPI. variable-name = expression . variable-name [ length ] = expression . The following is true for output host variables. NUL-Terminated Graphic Form wchar_t auto extern static const volatile . or CVTSQLCPP command. If the *CNULRQD option is specified on the CRTSQLCI. v If the host variable is large enough to contain the data and the graphic NUL-terminator. If the output host variable is too small to contain both the data and the NUL-terminator. 2. the input host variables do not need to contain the graphic NUL-terminator. the following actions are taken: – The data is returned. and the last character is the graphic NUL-terminator. Coding SQL Statements in C and C++ Applications 235 . } vstring. wchar_t s[10]. 3.v If the host variable is large enough to contain the data but not the graphic NUL-terminator. var-1 and var-2 must be simple variable references and cannot be used as host variables. wchar_t var-2 [ length ] . variable-name = { int var-1 . but these cannot be used as host variables. 2. the following actions are taken: – The data is truncated – A graphic NUL-terminator is not returned – SQLWARN1 is set to ’W’ VARGRAPHIC Structured Form struct auto extern static const volatile _Packed tag { short signed . } . the following actions are taken: – The data is returned – A graphic NUL-terminator is not returned – SQLWARN1 is set to ’N’ v If the host variable is not large enough to contain the data. The struct tag can be used to define other data areas. Example: EXEC SQL BEGIN DECLARE SECTION. /* valid declaration of host variable graphic string */ struct VARGRAPH { short len. expression } Notes: 1. Chapter 12. /* invalid declaration of host variable wstring */ struct VARGRAPH wstring. length must be an integer constant that is greater than 0 and not greater than 16370. expression . init-len.640 3. If a DBCLOB is initialized. 8. 10. K. BLOB Example 236 DB2 UDB for AS/400 SQL Programming V4R4 . 11. must be a numeric constant (that is. it cannot include K.| | | | | LOB Host Variables LOB Host Variable SQL TYPE IS auto extern static const volatile BLOB CLOB DBCLOB | | ( lob-length K M ) | | . DBCLOB. CCSID processing for LOB Host Variables will be the same as the processing for other character and graphic host variable types. it is the user’s responsibility to prefix the string with an ’L’ (indicating a wide-character string). 7. If the LOB is not initialized within the declaration. 1 <= lob-length <= 15. 6. M can be in mixed case.766 bytes. The SQL TYPE IS clause is needed in order to distinguish the three LOB-types from each other so that type-checking and function resolution can be carried out for LOB-type host variables that are passed to functions. The maximum length allowed for the initialization string is 32. with the same rules and restrictions as for pointers to other host variable types. then no initialization will be done within the precompiler generated code. LOB Host Variables can be declared in host structures and host structure arrays.864. BLOB. 13. variable-name = = = = { init-len. 9. Pointers to LOB Host Variables can be declared. 5. The initialization length. M. 2. that is. For DBCLOB.320 4. For BLOB and CLOB. | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Notes: 1.″init-data″ } SQL_BLOB_INIT(″init-data″) SQL_CLOB_INIT(″init-data″) SQL_DBCLOB_INIT(″init-data″) . The precompiler generates a structure tag which can be used to cast to the host variables type. A length for the LOB must be specified. 1 <= lob-length <= 7. the following declaration is not permitted SQL TYPE IS BLOB my_blob. 12.728. SQL TYPE IS. or G). CLOB. Results in the generation of the following structure: auto struct var1_t { unsigned long length. } my_dbclob. var2 = {10. || | | | | | | | Notes: 1. CLOB Example The following declaration: auto SQL TYPE IS CLOB(128K) var1. Results in the generation of the following structure: static struct my_blob_t { unsigned long length. char data[131072]. CLOB_LOCATOR. LOB Locators can be declared in host structures and host structure arrays. LOB Locators LOB Locator SQL TYPE IS auto extern static const volatile BLOB_LOCATOR CLOB_LOCATOR DBCLOB_LOCATOR | | . } my_blob=SQL_BLOB_INIT("my_data"). "data2data2"}. BLOB_LOCATOR. Chapter 12. 2. DBCLOB Example The following declaration: auto SQL TYPE IS DBCLOB(128K) my_dbclob. } var1. Coding SQL Statements in C and C++ Applications 237 . DBCLOB_LOCATOR can be in mixed case. 3. Other types of initialization will have no meaning. wchar_t data[131072]. "data2data2"}. variable-name = init-value .| | | | | | | | | | | | | | | | | | | | | | | | | | | | | The following declaration: static SQL TYPE IS BLOB(128K) my_blob=SQL_BLOB_INIT("mydata"). Results in the generation of the following structure: auto struct my_dbclob_t { unsigned long length. var2 = {10. init-value permits the initialization of pointer locator variables. char data[131072]. SQL TYPE IS. 2. variable-name = init-value . with the same rules and restrictions as for pointers to other host variable types. | | | | | | | | | | | | | | | | | | | | | | Notes: 1. data_length. LOB File Reference Variables LOB File Reference Variable SQL TYPE IS auto extern static const volatile BLOB_FILE CLOB_FILE DBCLOB_FILE | | . DBCLOB_FILE can be in mixed case. with the same rules and restrictions as for pointers to other host variable types. Results in the generation of the following structure: static struct unsigned unsigned unsigned } my_file. file_options. The pre-compiler will generate declarations for the following file option constants: v SQL_FILE_READ (2) v SQL_FILE_CREATE (8) 238 DB2 UDB for AS/400 SQL Programming V4R4 . 3. Pointers to LOB File Reference Variables can be declared. BLOB_FILE. CLOB Locator Example The following declaration: static SQL TYPE IS CLOB_LOCATOR my_locator. Pointers to LOB Locators can be declared. CLOB_FILE. LOB File Reference Variables can be declared as part of a host structure. BLOB and DBCLOB locators have similar syntax.| | | | | | | | | | | | | 4. BLOB and DBCLOB file reference variables have similar syntax. name[255]. SQL TYPE IS. Results in the generation of the following structure: static long int unsigned my_locator. { long long long char name_length. CLOB File Reference Example The following declaration: static SQL TYPE IS CLOB_FILE my_file. .employee where empno=:pemp1. you can refer to it in an SQL statement instead of listing the several host variables (that is. in the above host structure example. You can qualify a host variable with a structure name (for example.EMPLOYEE with: struct { char empno[7]. which requires another structure. } b_st. char c2.. but only for a two-level structure. char lastname_text[15].) A structure cannot contain an intermediate level structure..field). 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. char workdept[4]. } firstname. you can define a host structure. b_st is the name of a host structure consisting of the elementary items c1 and c2. two varying-length string elements are included in the structure: firstname and lastname.| | | v SQL_FILE_OVERWRITE (16) v SQL_FILE_APPEND (32) Using Host Structures In C and C++ programs.. } pemp1.. Coding SQL Statements in C and C++ Applications 239 . Notice that in the declaration of pemp1. Host structures have a maximum of two levels. you can retrieve all column values from selected rows of the table CORPDATA. In this example. struct char midint. In the previous example.. the names of the host variables that make up the host structure). } lastname. strcpy("000220". Host structures are limited to two levels. struct { short int firstname_len. structure. the a_st cannot be referred to in SQL. char firstname_text[12]. For example: struct { struct { char c1. For example.empno). (For example. exec sql select * into :pemp1 from corpdata. .empno. a_st could not be used as a host variable or referred to in an SQL statement. A host structure name can be a group name whose subordinate levels name elementary C or C++ variables. You can use the structure name as a shorthand notation for a list of scalars.pemp1. even though the host structure might itself occur within a multilevel structure. { short int lastname_len.. which is a named set of elementary C or C++ variables. An exception is the declaration of a varying-length string.. } a_st. Chapter 12.. wchar_t var-5 [ . } . variable-name = expression .Host Structure Declarations The following figure shows the valid syntax for host structure declarations. length ] . var-2 [ length ] scale int var-1 ) . varchar-structure: struct tag { signed short int var-3 . } wchar_t var-7 [ Note: 240 DB2 UDB for AS/400 SQL Programming V4R4 . { signed length ] short int . long signed short varchar-structure vargraphic-structure . signed unsigned char var-4 [ length ] . float double decimal ( precision . char signed unsigned . } vargraphic-structure: struct tag var-6 . Host Structures struct auto extern static const volatile _Packed tag { . Another structure is not needed if a varying-length character string or a varying-length graphic string is not used. v b_array may only be used on the blocked forms of FETCH and INSERT statements. struct { _Packed struct{ char c1_var[20]. Note: Dimension must be an integer constant between 1 and 32767. you can define a host structure array that has the dimension attribute. Host Structure Indicator Array short auto extern static const volatile signed int . A structure of a short int followed by either a char or wchar_t array is always interpreted by the SQL C and C++ compilers as either a VARCHAR or VARGRAPHIC structure. short c2_var. and graphic host variables. } a_struct. Chapter 12. Coding SQL Statements in C and C++ Applications 241 . Host Structure Indicator Array The following figure shows the valid syntax for host structure indicator array declarations. In this example. } b_array[10].1. Using Arrays of Host Structures In C and C++ programs. even though the array might occur within a multiple-level structure. Host structure arrays have a maximum of two levels. character. For details on declaring numeric. and graphic host variables. character host variables. variable-name [ dimension ] = expression . the following are true: v All of the members in b_array must be valid variable declarations. v b_array is the name of an array of host structures containing the members c1_var and c2_var. see the notes under numeric host variables. v The _Packed attribute must be specified for the struct tag. 2. Host Structure Array The following figure shows the valid syntax for host structure array declarations. . char middle_initial. struct { short inds[4]. v A structure cannot contain an intermediate level structure. EXEC SQL DECLARE C1 CURSOR FOR SELECT SUBSTR(FIRSTNME.. EXEC SQL FETCH C1 FOR 10 ROWS INTO :employee_rec:employee_inds.. 242 DB2 UDB for AS/400 SQL Programming V4R4 .1).EMPLOYEE. } lastname. } employee_rec[10]. MIDINIT. . LASTNAME.. EXEC SQL OPEN C1.1.v c1_var and c2_var are not valid host variables in any SQL statement. _Packed struct {short lastname_len. you can retrieve 10 rows from the cursor with: _Packed struct {char first_initial. For example. char lastname_data[15]. double total_salary.. SALARY+BONUS+COMM FROM CORPDATA. } employee_inds[10]. and graphic host variables. see the notes under numeric-host variables. float double decimal ( precision . Chapter 12. long signed short varchar-structure vargraphic-structure . length ] . 2. For details on declaring numeric. Coding SQL Statements in C and C++ Applications 243 . but these cannot be used as host variables. varchar-structure: _Packed struct tag { signed short int var-3 . character-host. character. and graphic-host variables. signed unsigned char var-4 [ length ] . The struct tag can be used to define other data areas. variable-name [ dimension ] = expression . wchar_t var-5 [ . var-2 [ length ] scale int var-1 ) . } short int var-6 . } vargraphic-structure: _Packed struct tag wchar_t var-7 [ length ] { signed . char signed unsigned .Host Structure Array _Packed auto extern static const volatile struct tag { . Notes: 1. } . } .3. in which case they are required. Notes: 1. but they cannot be used as host variables. Using Pointer Data Types You can also declare host variables that are pointers to the supported C and C++ data types. The struct tag can be used to define other data areas. /* /* /* /* /* /* 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. then that host variable must be declared with asterisks followed by a host variable. For example: 244 DB2 UDB for AS/400 SQL Programming V4R4 . char(*mychara)[20] struct { short mylen. Dimension must be an integer constant between 1 and 32767. 2. } *myvarchar. char *mychar. If the parentheses were not used. Host Structure Array Indicator Structure struct auto extern static const volatile _Packed tag { short signed int var-1 [ dimension-1 ] . char mydata[30]. The following examples are all valid: short *mynum. long **mynumptr. variable-name [ dimension-2 ] = expression . dimension-1 and dimension-2 must both be integer constants between 1 and 32767. Host Structure Array Indicator Structure The following figure shows the valid syntax for host structure array indicator structure declarations. you would be declaring an array of pointers rather than the desired pointer to an array. */ */ */ */ */ */ Note: Parentheses are only allowed when declaring a pointer to a NUL-terminated character array. with the following restrictions: v If a host variable is declared as a pointer. v The maximum length of a host variable name is affected by the number of asterisks specified. v Pointers to structures are not usable as host variables except for variable character structures. For the conversion options. The required elements are: v Include name v Externally described file name v Format name or a list of format names v Options v Conversion options The library name. Unions declared using the typedef union created by the #pragma mapinc and #include directive cannot be used as host variables in SQL statements. These options may be specified in any order except that both D and p can not be specified. Coding SQL Statements in C and C++ Applications 245 . such as a SELECT: EXEC SQL SELECT name INTO :*mychara FROM mytable. char mychar. char *a[10]. v SQL requires that all specified storage for based host variables be allocated. union name. v Only the asterisk can be used as an operator over a host variable name. unpredictable results can occur.char (*a)[10]. Also. Using ILE C for AS/400 External File Descriptions You can use the C or C++ #pragma mapinc directive with the #include directive to include external file descriptions in your program. conversion options. Chapter 12. For example. with the exception of pointers to NUL-terminated character arrays. p. that host variable must be referenced exactly as declared. If the storage is not allocated. /* ptr to char array of 20 bytes */ However. the parentheses are not allowed when the host variable is referenced in an SQL statement. output. When used with SQL. only a particular format of the #pragma mapinc directive is recognized by the SQL precompiler. pointer fields in structures are not usable as host variables. /* This declaration is valid /* But this one is invalid */ */ v When a host variable is referenced within an SQL statement. and 1BYTE_CHAR. Structures that contain the typedef structure cannot be used in SQL statements. z. _P. Although typedef statements coded by the user are not recognized by the precompiler. and prefix name are optional. If all of the required elements are not specified. /* pointer to a null-terminated char array */ /* pointer to an array of pointers */ v If a host variable is declared as a pointer. For example. the supported values are D. the precompiler ignores the directive and does not generate host variable structures. as these asterisks are considered part of the name. the following declaration required parentheses: char (*mychara)[20]. the second declaration below would be invalid: char *mychar. and key values for the options parameter. both. then no other host variable can be declared with that same name within the same source file. the members of the unions can be used. those created by the #pragma mapinc and #include directives are recognized. the structure declared using the typedef can be used. SQL supports input. C or C++ Declarations Mapped to Typical SQL Data Types C or C++ Data Type short int long int decimal(p. Determining Equivalent SQL and C or C++ Data Types The precompiler determines the base SQLTYPE and SQLLEN of host variables based on the following table.To retrieve the definition of the sample table DEPARTMENT described in Appendix A. the generated host variable will have the UCS-2 CCSID assigned to it. binary (with non-zero scale fields). a date host variable can only compared against a DATE column or a character string which is a valid representation of a date."CORPDATA/DEPARTMENT(*ALL)". TIME. DEPTNAME. These field names can be used as host variables in SQL statements. and TIMESTAMP column. By using the extended program model (EPM) routines. For more information. Note: DATE. A host structure named Dept_Structure is defined with the following elements: DEPTNO. If a host variable appears with an indicator variable. MGRNO. If the GRAPHIC or VARGRAPHIC column has a UCS-2 CCSID. and ADMRDEPT. the SQLTYPE is the base SQLTYPE plus one.s) FLOAT (single precision) FLOAT (double precision) CHAR(1) VARCHAR (length 1) VARCHAR (length) 456 length VARCHAR(length) 468 1 GRAPHIC(1) 246 DB2 UDB for AS/400 SQL Programming V4R4 .s) float double single-character form NUL-terminated character form VARCHAR structured form where length < 255 VARCHAR structure form where length > 254 single-graphic form SQLTYPE of Host Variable 500 496 484 480 480 452 460 448 SQLLEN of Host Variable 2 4 p in byte 1. DB2 UDB for AS/400 Sample Tables. Although zoned. For example. TIME. and optionally decimal are mapped to character fields in ILE C for AS/400. you can code the following: #pragma mapinc ("dept". SQL will treat these fields as numeric."both") #include "dept" CORPDATA_DEPARTMENT_DEPARTMENT_both_t Dept_Structure. Table 24. s in byte 2 4 8 1 length length SQL Data Type SMALLINT INTEGER DECIMAL (p. They are treated by SQL with the same comparison and assignment rules as a DATE. see the ILE C for AS/400 Language Reference book. you can manipulate these fields to convert zoned and packed decimal data. and TIMESTAMP columns generate character host variable definitions. 1) VARGRAPHIC (length) VARGRAPHIC (length) VARGRAPHIC 464 structured form where length < 128 VARGRAPHIC 472 structured form where length > 127 length You can use the following table to determine the C or C++ data type that is equivalent to a given SQL data type.s) or nonzero scale binary FLOAT (single precision) FLOAT (double precision) CHAR(1) CHAR(n) VARCHAR(n) No exact equivalent float double single-character form No exact equivalent NUL-terminated character form If n>1.s) C or C++ Data Type short int long int decimal(p. VARCHAR structured form BLOB CLOB GRAPHIC (1) GRAPHIC (n) None None single-graphic form No exact equivalent If n > 1. use VARCHAR structured form. n is a positive integer. Use decimal(p. The maximum value of n is 32740. use NUL-terminated graphic form. SQL Data Types Mapped to Typical C or C++ Declarations SQL Data Type SMALLINT INTEGER DECIMAL(p.s) p is a positive integer from 1 to 31.Table 24. Coding SQL Statements in C and C++ Applications 247 . and s is a positive integer from 0 to 31. Use SQL TYPE IS to declare a CLOB in C or C++. The maximum value of n is 32740. Table 25. use NUL-terminated character form If data can contain character NULs (\0). Use SQL TYPE IS to declare a BLOB in C or C++. Allow at least n+1 to accommodate the NUL-terminator. Chapter 12.s). C or C++ Declarations Mapped to Typical SQL Data Types (continued) C or C++ Data Type NUL-terminated single-graphic form SQLTYPE of Host Variable 400 SQLLEN of Host Variable length length SQL Data Type VARGRAPHIC (length . Notes NUMERIC(p. 8 to include seconds. *ISO. If the format is *MDY. allow at least 6 characters. *JIS. The maximum value of n is 16370. Allow at least n + 1 to accommodate the NUL-terminator. or *EUR. VARGRAPHIC structured form DBCLOB DATE None NUL-terminated character form n is a positive integer. Allow at least 19 characters. If the format is *USA. n is a positive integer. If n is less than 27. or *DMY. To include microseconds at full precision. Allow at least 7 characters (9 to include seconds) to accommodate the NUL-terminator. or *DMY. allow at least 10 characters. If the format is *JUL. allow at least 7 characters to accommodate the NUL-terminator. Allow at least 6 characters. If the format is *JUL. Allow at least 20 characters (27 to include microseconds at full precision) to accommodate the NUL-terminator. SQL Data Types Mapped to Typical C or C++ Declarations (continued) SQL Data Type VARGRAPHIC(n) C or C++ Data Type NUL-terminated graphic form Notes If data can contain graphic NUL values (/0/0). *JIS. If the number of characters is less than 26. allow at least 9 characters to accommodate the NUL-terminator. *ISO. allow at least 8 characters. *YMD. VARCHAR structured form TIME NUL-terminated character form VARCHAR structured form TIMESTAMP NUL-terminated character form VARCHAR structured form 248 DB2 UDB for AS/400 SQL Programming V4R4 . Use SQL TYPE IS to declare a DBCLOB in C or C++. *YMD. or *EUR. The maximum value of n is 16370. truncation occurs on the microseconds part. If the format is *MDY.Table 25. truncation occurs on the microseconds part. allow 26 characters. allow at least 11 characters to accommodate the NUL-terminator. use VARGRAPHIC structured form. If the format is *USA. C and C++ use quotation marks to delimit string constants and apostrophes to delimit character constants. :Bgn :BgnInd. SQL does not have this distinction. Coding SQL Statements in C and C++ Applications 249 . On assignment to a column. The declarations of the two can be mixed in any way that seems appropriate to you. char ClsCd[8]. :End :EndInd. :Day :DayInd. C++. a negative indicator variable is used to indicate that a null value should be assigned. EndInd. char Bgn[9]. EXEC SQL END DECLARE SECTION. Example: Given the statement: EXEC SQL FETCH CLS_CURSOR INTO :ClsCd. Character data in SQL is distinct from integer data. DayInd. Using Indicator Variables An indicator variable is a two-byte integer (short int). BgnInd.Table 25. Variables can be declared as follows: EXEC SQL BEGIN DECLARE SECTION. Chapter 12. short Day. See DB2 UDB for AS/400 SQL Reference book for more information on the use of indicator variables. but uses quotation marks for delimited identifiers and uses apostrophes to delimit character string constants. char End[9]. SQL Data Types Mapped to Typical C or C++ Declarations (continued) SQL Data Type DATALINK C or C++ Data Type Not supported Notes Notes on C and C++ Variable Declaration and Usage Apostrophes and quotation marks have different meanings in C. Indicator variables are declared in the same way as host variables. and SQL. On retrieval. You can also specify an indicator structure (defined as an array of halfword integer variables) to support a host structure. an indicator variable is used to show if its associated host variable has been assigned a null value. 250 DB2 UDB for AS/400 SQL Programming V4R4 . This chapter describes the unique application and coding requirements for embedding SQL statements in a COBOL program. Defining the SQL Communications Area A COBOL program that contains SQL statements must include one or both of the following: v An SQLCODE variable declared as PICTURE S9(9) BINARY. The DB2 UDB Query Manager and SQL Development Kit licensed program only supports the COBOL for AS/400 and ILE COBOL for AS/400 languages. 1999 PIC X(8). The SQLCODE and SQLSTATE values are set by the database manager after each SQL statement is executed. PICTURE S9(9) COMP-4. X. The SQLCA can be coded in a COBOL program either directly or by using the SQL INCLUDE statement. An application can check the SQLCODE or SQLSTATE value to determine whether the last SQL statement was successful. PIC S9(9) BINARY. PIC X(8). Sample Programs Using DB2 UDB for AS/400 Statements. A detailed sample COBOL program. the SQL COBOL precompiler includes COBOL source statements for the SQLCA: 01 SQLCA. The SQLCODE.Chapter 13. X. PIC S9(4) BINARY. Using the SQL INCLUDE statement requests the inclusion of a standard declaration: EXEC SQL INCLUDE SQLCA END-EXEC. 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. 10 SQLWARN0 10 SQLWARN1 10 SQLWARN2 10 SQLWARN3 10 SQLWARN4 10 SQLWARN5 10 SQLWARN6 10 SQLWARN7 © Copyright IBM Corp. X. 1997. OCCURS 6 TIMES PIC S9(9) BINARY. v An SQLSTATE variable declared as PICTURE X(5) Or. PIC PIC PIC PIC PIC PIC PIC PIC X. PIC X(70). Requirements for host structures and host variables are defined. or PICTURE S9(9) COMP. v An SQLCA (which contains an SQLCODE and SQLSTATE variable). 05 SQLCAID 05 SQLCABC 05 SQLCODE 05 SQLERRM. Coding SQL Statements in COBOL Applications The AS/400 system supports more than one COBOL compiler. PIC S9(9) BINARY. is provided in Appendix C. 251 . X. X. showing how SQL statements can be used. X. X. SQLSTATE. When you use the INCLUDE statement. 49 SQLERRML 49 SQLERRMC 05 SQLERRP 05 SQLERRD 05 SQLWARN. USING DESCRIPTOR descriptor-name OPEN. The SQLDA can have any valid name. INCLUDE SQLDA Declarations for COBOL SQLDA declarations must appear in the WORKING-STORAGE SECTION or LINKAGE SECTION of your program and can be placed wherever a record 252 DB2 UDB for AS/400 SQL Programming V4R4 . Figure 10. SQLSTATE is replaced with SQLSTOTE when a declare for SQLSTATE is found in the program and the SQLCA is provided by the precompiler. the SQLCA is declared using the GLOBAL clause. there can be more than one SQLDA in a program. An SQLDA can be coded in a COBOL program directly or added with the INCLUDE statement. X.USING DESCRIPTOR descriptor-name DESCRIBE statement-name INTO descriptor-name DESCRIBE TABLE host-variable INTO descriptor-name PREPARE statement-name INTO descriptor-name Unlike the SQLCA. For more information on SQLCA. 10 SQLNAME. The COBOL declarations included for the SQLDA are: 1 SQLDA. 10 SQLIND POINTER. 15 SQLSCALE PIC X.. Using the SQL INCLUDE statement requests the inclusion of a standard SQLDA declaration: EXEC SQL INCLUDE SQLDA END-EXEC. 05 SQLVAR OCCURS 0 TO 409 TIMES DEPENDING ON SQLD.. 05 SQLDAID PIC X(8).USING DESCRIPTOR descriptor-name FETCH. “SQL Communication Area” in the DB2 UDB for AS/400 SQL Reference book. X(5). Defining SQL Descriptor Areas The following statements require an SQLDA: EXECUTE. 05 SQLN PIC S9(4) BINARY. For ILE COBOL for AS/400. 10 SQLRES PIC X(12).. 15 SQLPRECISION PIC X. X.. 10 SQLDATA POINTER. 10 SQLLEN PIC S9(4) BINARY. 05 SQLD PIC S9(4) BINARY. 05 SQLDABC PIC S9(9) BINARY.10 SQLWARN8 10 SQLWARN9 10 SQLWARNA 05 SQLSTATE PIC PIC PIC PIC X. see Appendix B. 10 FILLER REDEFINES SQLLEN.. SQLCODE is replaced with SQLCADE when a declare for SQLCODE is found in the program and the SQLCA is provided by the precompiler. 10 SQLTYPE PIC S9(4) BINARY.USING DESCRIPTOR descriptor-name CALL... 49 SQLNAMEL PIC S9(4) BINARY. 49 SQLNAMEC PIC X(30).. your program can develop and then run SQL statements while the program is running. Dynamic SQL is an advanced programming technique described in Chapter 10. 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. but the remainder of the statement can appear on the next and subsequent lines. Embedding SQL Statements SQL statements can be coded in COBOL program sections as follows: SQL Statement BEGIN DECLARE SECTION END DECLARE SECTION DECLARE VARIABLE DECLARE STATEMENT INCLUDE SQLCA INCLUDE SQLDA INCLUDE member-name Other WORKING-STORAGE SECTION or LINKAGE SECTION DATA DIVISION or PROCEDURE DIVISION PROCEDURE DIVISION Program Section WORKING-STORAGE SECTION or LINKAGE SECTION Each SQL statement in a COBOL program must begin with EXEC SQL and end with END-EXEC. The EXEC SQL keywords must appear all on one line. For ILE COBOL for AS/400.description entry can be specified in those sections. 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. you can include COBOL comment lines (* or / in column 7) within embedded SQL statements except between the keywords EXEC and SQL. With dynamic SQL. For more information. COBOL debugging lines (D in column 7) are treated as comment lines by the precompiler. Coding SQL Statements in COBOL Applications 253 . Dynamic SQL Applications. Chapter 13. except that EXEC SQL must be specified within one line. Comments In addition to SQL comments (--). refer to the DB2 UDB for AS/400 SQL Reference book. Continuation for SQL Statements The line continuation rules for SQL statements are the same as those for other COBOL statements. A SELECT statement with a variable SELECT list (that is. If the SQL statement appears between two COBOL statements. the SQLDA is declared using the GLOBAL clause. the period is optional and might not be appropriate. 3...6. options that affect the syntax of the COBOL source such as APOST and QUOTE 254 DB2 UDB for AS/400 SQL Programming V4R4 .. 'RDI'. the first nonblank character in the next line must be either an apostrophe or a quotation mark.+..1.. Therefore...4... the SQL precompiler itself does not recognize the PROCESS statement.... 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.+.5...+. This SQL statement has a valid graphic constant of G’<AABBCCDDEEFFGGHHIIJJKK>’..If you continue a string constant from one line to the next.. COBOL Compile-Time Options The COBOL PROCESS statement can be used to specify the compile-time options for the COBOL compiler.. COBOL COPY statements cannot be used to include SQL statements or declarations of COBOL host variables that are referenced in SQL statements...... 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'.. Sequence Numbers The source statements generated by the SQL precompiler are generated with the same sequence number as the SQL statement.2.... or 'DSN'.... the SQL precompiler will not recognize the statement.+. *.. The redundant shifts are removed..+..+.....7... 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..+. These names are reserved for the database manager.... 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...8 EXEC SQL SELECT * FROM GRAPHTAB WHERE GRAPHCOL = G'<AABB> '<CCDDEEFFGGHHIIJJKK>' END-EXEC. Margins Code SQL statements in columns 12 through 72... Although the PROCESS statement will be recognized by the COBOL compiler when it is called by the precompiler to create the program. before column 12). If EXEC SQL starts before the specified margin (that is. Chapter 13. The COBOL statements that are used to define the host variables should be preceded by a BEGIN DECLARE SECTION statement and followed by an END DECLARE SECTION statement. Numeric Host Variables The following figure shows the syntax for valid integer host variable declarations. All host variables within an SQL statement must be preceded by a colon (:). Declaring Host Variables The COBOL precompiler only recognizes a subset of valid COBOL declarations as valid host variable declarations. Multiple source programs The SQL COBOL precompiler does not support precompiling multiple source programs separated with the PROCESS statement. Instead *APOST and *QUOTE should be specified in the OPTION parameter of the CRTSQLCBL and CRTSQLCBLI commands. blanks must precede and follow a minus sign. To accommodate using dashes within a COBOL host variable name.should not be specified in the PROCESS statement. all host variable declarations used in SQL statements must be between the BEGIN DECLARE SECTION and the END DECLARE SECTION statements. Coding SQL Statements in COBOL Applications 255 . Host variables cannot be records or elements. A host variable used in an SQL statement must be declared prior to the first use of the host variable in an SQL statement. If a BEGIN DECLARE SECTION and END DECLARE SECTION are specified. Statement Labels Executable SQL statements in the PROCEDURE DIVISION can be preceded by a paragraph name. Using Host Variables All host variables used in SQL statements must be explicitly declared. 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. because COMPUTATIONAL-3 and COMP-3 are IBM extensions that are not supported in 256 DB2 UDB for AS/400 SQL Programming V4R4 . A portable application should code BINARY.. because COMPUTATIONAL-4 and COMP-4 are IBM extensions that are not supported in ISO/ANSI COBOL.INTEGER and SMALLINT 01 77 level-1 variable-name PICTURE PIC picture-string IS USAGE IS BINARY COMPUTATIONAL-4 COMP-4 . 2. VALUE IS numeric-constant Notes: 1. COMPUTATIONAL-3. BINARY. The picture-string associated with these types must have the form S9(i)V9(d) (or S9. COMPUTATIONAL-4. The following figure shows the syntax for valid decimal host variable declarations. and COMP-4 are equivalent. i + d must be less than or equal to 9. level-1 indicates a COBOL level between 2 and 48. PACKED-DECIMAL. VALUE IS numeric-constant Notes: 1.. A portable application should code PACKED-DECIMAL. with i and d instances of 9).9.9V9. DECIMAL 01 77 level-1 variable-name PICTURE PIC picture-string IS USAGE IS PACKED-DECIMAL COMPUTATIONAL-3 COMP-3 COMPUTATIONAL COMP ... and COMP-3 are equivalent. In the COBOL for AS/400 program. with i and d instances of 9). VALUE IS numeric-constant display clause: SIGN DISPLAY IS LEADING SEPARATE CHARACTER Notes: 1. the picture-string associated with these types must have the form S9(i)V9(d) (or S9.. i + d must be less than or equal to 18..9. 2. Therefore...9. The picture strings associated with these and the data types they represent are product specific... level-1 indicates a COBOL level between 2 and 48. Numeric 01 77 level-1 variable-name PICTURE PIC picture-string IS USAGE IS DISPLAY display clause .9V9. Floating Point Host Variables The following figure shows the syntax for valid floating point host variable declarations.9. The picture-string associated with these types must have the form S9(i)V9(d) (or S9. i + d must be less than or equal to 18.9V9. Chapter 13.9V9. The following figure shows the syntax for valid numeric host variable declarations. i + d must be less than or equal to 18. 3.ISO/ANS COBOL. with i and d instances of 9). Floating point host variables are only supported for ILE COBOL for AS/400. COMPUTATIONAL and COMP are equivalent... COMP and COMPUTATIONAL should not be used in a portable application... with i and d instances of 9). level-1 indicates a COBOL level between 2 and 48. Coding SQL Statements in COBOL Applications 257 . The picture-string associated with SIGN LEADING SEPARATE and DISPLAY must have the form S9(i)V9(d) (or S9.. 2.. 258 DB2 UDB for AS/400 SQL Programming V4R4 .. COMPUTATIONAL-1 and COMP-1 are equivalent..X. Notes: 1. with m instance of X) with 1 ≤ m ≤ 32 766. Character Host Variables There are two valid forms of character host variables: v Fixed-Length Strings v Varying-Length Strings Fixed-Length Character Strings 01 77 level-1 variable-name PICTURE PIC picture-string IS DISPLAY USAGE IS VALUE IS string-constant . 2. COMPUTATIONAL-2 and COMP-2 are equivalent. level-1 indicates a COBOL level between 2 and 48. 2. level-1 indicates a COBOL level between 2 and 48. The picture string associated with these forms must be X(m) (or XXX. VALUE IS numeric-constant Notes: 1.Floating-point 01 77 level-1 variable-name USAGE IS COMPUTATIONAL-1 COMP-1 COMPUTATIONAL-2 COMP-2 . .. The picture-string-1 associated with these forms must be S9(m) or S9. or XX. There are two valid forms of graphic host variables: v Fixed-Length Graphic Strings v Varying-Length Graphic Strings Chapter 13. var-1 and var-2 cannot be used as host variables.. m must be from 1 to 4. Coding SQL Statements in COBOL Applications 259 .X. with m instances of X.Varying-Length Character Strings 01 level-1 variable-name . The picture-string-2 associated with these forms must be either X(m). 4. 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. 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.. and with 1 ≤ m ≤ 32 740. 2. VALUE IS numeric-constant 49 var-2 PICTURE PIC picture-string-2 IS USAGE IS DISPLAY . 49 var-1 PICTURE PIC picture-string-1 IS USAGE IS BINARY COMPUTATIONAL-4 COMP-4 . 3. VALUE IS string-constant Notes: 1. level-1 indicates a COBOL level between 2 and 48.9 with m instances of 9. Graphic Host Variables Graphic host variables are only supported in ILE COBOL for AS/400. 9 with m instances of 9. m must be from 1 to 4.Fixed-Length Graphic Strings 01 77 level-1 variable-name PICTURE PIC picture-string IS DISPLAY-1 USAGE IS VALUE IS string-constant .. 2. Notes: 1..G. with m instance of G) or N(m) (or NNN. 49 var-1 PICTURE PIC picture-string-1 IS USAGE IS BINARY COMPUTATIONAL-4 COMP-4 . The picture-string-1 associated with these forms must be S9(m) or S9.N. with m instance of N) with 1 ≤ m ≤ 16 383. The picture string associated with these forms must be G(m) (or GGG... Varying-Length Graphic Strings 01 level-1 variable-name . VALUE IS numeric-constant 49 var-2 PICTURE PIC picture-string-2 IS USAGE IS DISPLAY-1 .. level-1 indicates a COBOL level between 2 and 48. 260 DB2 UDB for AS/400 SQL Programming V4R4 . VALUE IS string-constant Notes: 1.. 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. LOB Host Variables can be declared in host structures. var-1 and var-2 cannot be used as host variables. 49 MY-CLOB-LENGTH PIC 9(9) BINARY. 49 MY-CLOB-DATA PIC X(16384).N with m instances of N. BLOB Example The following declaration: 01 MY-BLOB SQL TYPE IS BLOB(16384). 1 <= lob-length <= 15. || | | | | | | | | | | | | | | | | | | | | Notes: 1. For DBCLOB. Results in the generation of the following structure: 01 MY-CLOB. | | | | | | LOB Host Variables LOB host variables are only supported in ILE COBOL for AS/400. 3. Coding SQL Statements in COBOL Applications 261 . 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. 49 MY-BLOB-DATA PIC X(16384)..640 2.. 49 MY-BLOB-LENGTH PIC 9(9) BINARY. N(m). CLOB Example The following declaration: 01 MY-CLOB SQL TYPE IS CLOB(16384). and with 1 ≤ m ≤ 16 370. 2. 4. DBCLOB can be in mixed case. BLOB. The picture-string-2 associated with these forms must be G(m).. SQL TYPE IS.728. or NN.G with m instances of G. Results in the generation of the following structure: 01 MY-BLOB. For BLOB and CLOB.. Chapter 13. level-1 indicates a COBOL level between 2 and 48.864. GG. 1 <= lob-length <= 7. 4.320 3. CLOB. LOB Host Variables 01 variable-name USAGE IS SQL TYPE IS BLOB CLOB DBCLOB | | ( lob-length K M ) . 3. 2. CLOB and DBCLOB locators have similar syntax. 49 MY-DBCLOB-LENGTH PIC 9(9) BINARY. 49 MY-DBCLOB-DATA PIC G(8192) DISPLAY-1. LOB Locators LOB locators are only supported in ILE COBOL for AS/400. SQL TYPE IS. LOB Locators can be declared as a part of a host structure.| | | | | | | | | | | | | DBCLOB Example The following declaration: 01MY-DBCLOB SQL TYPE IS DBCLOB(8192). | | | | | | | | | | | | | | | | Notes: 1. 262 DB2 UDB for AS/400 SQL Programming V4R4 . BLOB-LOCATOR. CLOB-LOCATOR. Results in the generation of the following structure: 01 MY-DBCLOB. LOB File Reference Variables LOB variables are only supported in ILE COBOL for AS/400. BLOB Example The following declaration: 01 MY-LOCATOR SQL TYPE IS BLOB_LOCATOR. Results in the generation of the following structure: 01 MY-LOCATOR PIC 9(9) BINARY. DBCLOB-LOCATOR can be in mixed case. LOB Locator 01 variable-name USAGE IS | | SQL TYPE IS BLOB-LOCATOR CLOB-LOCATOR DBCLOB-LOCATOR . LOB Locators cannot be initialized in the SQL TYPE IS statement. BLOB Example The following declaration: 01 MY-FILE SQL TYPE IS BLOB-FILE. 49 MY-FILE-DATA-LENGTH PIC S9(9) COMP-5. LOB File Reference Variables can be declared as part of a host structure. DBCLOB-FILE can be in mixed case. 49 MY-FILE-NAME PIC X(255). and timestamp host variable declarations. Datetime Host Variable 01 77 level-1 variable-name FORMAT OF DATE TIME TIMESTAMP IS | | || | format-options Chapter 13. Datetime host variables are supported only for ILE COBOL for AS/400. 49 MY-FILE-NAME-LENGTH PIC S9(9) COMP-5. Coding SQL Statements in COBOL Applications 263 . Results in the generation of the following structure: 01 MY-FILE. 2. The pre-compiler will generate declarations for the following file option constants: v SQL-FILE-READ (2) v SQL-FILE-CREATE (8) v SQL-FILE-OVERWRITE (16) v SQL-FILE-APPEND (32) Datetime Host Variables The following figure shows the syntax for valid date. SQL TYPE IS. CLOB-FILE. 49 MY-FILE-FILE-OPTIONS PIC S9(9) COMP-5.| | | | LOB File Reference Variable 01 variable-name USAGE IS SQL TYPE IS BLOB-FILE CLOB-FILE DBCLOB-FILE | | || | | | | | | | | | | | | | | | | | | | | | | | | | | | . Notes: 1. time. CLOB and DBCLOB file reference variables have similar syntax. BLOB-FILE. MOVE "000220" TO EMPNO. 2.. PIC X(12). Using Host Structures A host structure is a named set of host variables that is defined in your program’s DATA DIVISION.| | | | | | Notes: 1. An exception is the declaration of a varying-length character string.. you can refer to it in an SQL statement instead of listing the several host variables (that is. ..EMPLOYEE with: 01 PEMPL. specify B.. A host structure name can be a group name whose subordinate levels name basic data items. See the ILE COBOL for AS/400 Reference. you can retrieve all column values from selected rows of the table CORPDATA. level-1 indicates a COBOL level between 2 and 48. which requires another level that must be level 49. even though the host structure might itself occur within a multilevel structure. 03 C2 PICTURE . PIC X(3). 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. B is the name of a host structure consisting of the basic items C1 and C2. PL/I style). 49 LASTNAME-LEN 49 LASTNAME-TEXT 10 WORKDEPT . When writing an SQL statement using a qualified host variable name (for example. For example. to identify a field within a structure). PIC X(15). EXEC SQL SELECT * PIC X(6).C1 rather than C1 OF B or C1 IN B. Host structures have a maximum of two levels. For example: 01 A 02 B 03 C1 PICTURE . SC09-2539-01 book for details. PIC X(1). PIC S9(4) USAGE BINARY. For example.. the names of the data items that comprise the host structure). PIC S9(4) USAGE BINARY.. you cannot use this technique for writing qualified names in COBOL statements.. In this example. use the name of the structure followed by a period and the name of the field (that is. format-options indicates valid datetime options that are supported by the COBOL compiler. 264 DB2 UDB for AS/400 SQL Programming V4R4 . However. 10 EMPNO 10 FIRSTNME. PL/I style applies only to qualified names within SQL statements. 49 FIRSTNME-LEN 49 FIRSTNME-TEXT 10 MIDINIT 10 LASTNAME.. Chapter 13.INTO :PEMPL FROM CORPDATA. Coding SQL Statements in COBOL Applications 265 .EMPLOYEE WHERE EMPNO = :EMPNO END-EXEC. Notice that in the declaration of PEMPL. two varying-length string elements are included in the structure: FIRSTNME and LASTNAME. Host Structure The following figure shows the syntax for the valid host structure. vargraphic-string . level-2 var-1 PICTURE picture-string PIC IS floating-point . . varchar-string .Host Structure level-1 variable-name . . usage-clause . floating-point: COMPUTATIONAL-1 COMP-1 COMPUTATIONAL-2 COMP-2 VALUE IS constant USAGE IS usage-clause: BINARY COMPUTATIONAL-4 COMP-4 PACKED-DECIMAL COMPUTATIONAL-3 COMP-3 COMPUTATIONAL COMP DISPLAY display-clause DISPLAY-1 VALUE IS constant USAGE IS display-clause: SIGN DISPLAY IS LEADING SEPARATE CHARACTER 266 DB2 UDB for AS/400 SQL Programming V4R4 . datetime . VALUE IS numeric-constant 49 var-3 PICTURE PIC BINARY COMPUTATIONAL-4 COMP-4 picture-string-2 IS DISPLAY-1 USAGE IS VALUE IS constant datetime: variable-name FORMAT OF DATE TIME TIMESTAMP format-options IS Notes: 1. 4. level-1 indicates a COBOL level between 1 and 47. VALUE IS numeric-constant 49 var-3 PICTURE PIC BINARY COMPUTATIONAL-4 COMP-4 picture-string-2 IS DISPLAY USAGE IS VALUE IS constant vargraphic-string: 49 var-2 PICTURE PIC picture-string-1 IS USAGE IS . Chapter 13. Graphic host variables and floating-point host variables are only supported for ILE COBOL for AS/400. see the notes under numeric-host variables. Coding SQL Statements in COBOL Applications 267 . See the ILE COBOL for AS/400 Reference. For details on declaring numeric. level-2 indicates a COBOL level between 2 and 48 where level-2 > level-1. SC09-2539-01 book for details. 3. and graphic host variables. character. and graphic-host variables. 2.Host Structure (continued) varchar-string: 49 var-2 PICTURE PIC picture-string-1 IS USAGE IS . character-host variables. 5. format-options indicates valid datetime options that are supported by the COBOL compiler. A portable application should code BINARY. A structure cannot contain an intermediate level structure. because COMPUTATIONAL-4 and COMP-4 are IBM extensions that are not supported in ISO/ANSI COBOL. BINARY. 3. Host structure arrays have a maximum of two levels. COMPUTATIONAL-4. Dimension must be an integer between 1 and 32767. even though the host structure can occur within a multiple level structure. Using Host Structure Arrays A host structure array is a named set of host variables that is defined in the program’s Data Division and has an OCCURS clause. VALUE IS constant Notes: 1. 268 DB2 UDB for AS/400 SQL Programming V4R4 . A varying-length string requires another level. v The SYNCHRONIZED attribute must not be specified. v B-ARRAY is the name of an array of host structures containing items C1-VAR and C2-VAR. and COMP-4 are equivalent. with i instances of 9).. level 49. i must be less than or equal to 4. 2.9. In v v v these examples. the following are true: All members in B-ARRAY must be valid.. B-ARRAY cannot be qualified. The picture-string associated with these types must have the form S9(i) (or S9. level-1 must be an integer between 2 and 48. Host Structure Indicator Array level-1 variable-name PICTURE PIC picture-string IS USAGE IS BINARY COMPUTATIONAL-4 COMP-4 OCCURS dimension TIMES .Host Structure Indicator Array The following figure shows the syntax for valid indicator array declarations. A host structure array name can be a group name whose subordinate levels name basic data items. v C1-VAR and C2-VAR are not valid host variables in any SQL statement. B-ARRAY can only be used on the blocked form of the FETCH and INSERT statements. 02 IND-ARRAY OCCURS 10 TIMES. . 03 C2-VAR PIC S9(4). EXEC SQL DECLARE C1 CURSOR FOR SELECT * FROM CORPDATA. Coding SQL Statements in COBOL Applications 269 . 05 INDS PIC S9(4) BINARY OCCURS 4 TIMES.. 05 ADMRDEPT PIC X(3).DEPARTMENT table. 05 MGRNO PIC X(6). 49 DEPTNAME-LEN PIC S9(4) BINARY. 01 TABLE-2. 05 DEPTNO PIC X(3).01 A-STRUCT.. use the following example: 01 TABLE-1. 05 DEPTNAME.. EXEC SQL FETCH C1 FOR 10 ROWS INTO :DEPT :IND-ARRAY END-EXEC. To retrieve 10 rows from the CORPDATA. . 02 DEPT OCCURS 10 TIMES. 03 C1-VAR PIC X(20). Chapter 13. 49 DEPTNAME-TEXT PIC X(29)..DEPARTMENT END-EXEC.. 02 B-ARRAY OCCURS 10 TIMES. Host Structure Array The following figures show the syntax for valid host structure array declarations.. . . floating-point: COMPUTATIONAL-1 COMP-1 COMPUTATIONAL-2 COMP-2 VALUE IS constant USAGE IS usage-clause: BINARY COMPUTATIONAL-4 COMP-4 PACKED-DECIMAL COMPUTATIONAL-3 COMP-3 COMPUTATIONAL COMP DISPLAY display-clause DISPLAY-1 VALUE IS constant USAGE IS display-clause: SIGN DISPLAY IS LEADING SEPARATE CHARACTER 270 DB2 UDB for AS/400 SQL Programming V4R4 . datetime . usage-clause . level-2 var-1 PICTURE picture-string-1 PIC IS floating-point . vargraphic-string . varchar-string .Host Structure Array level-1 variable-name OCCURS dimension TIMES . 6. VALUE IS numeric-constant 49 var-3 PICTURE PIC BINARY COMPUTATIONAL-4 COMP-4 picture-string-3 IS DISPLAY USAGE IS VALUE IS constant vargraphic-string: 49 var-2 PICTURE PIC picture-string-2 IS USAGE IS . character-host variables. Dimension must be an integer constant between 1 and 32767. Graphic host variables and floating-point host variables are only supported for ILE COBOL for AS/400. 5. 3. see the notes under numeric-host variables.Host Structure Array (continued) varchar-string: 49 var-2 PICTURE PIC picture-string-2 IS USAGE IS . 4. Coding SQL Statements in COBOL Applications 271 . level-2 indicates a COBOL level between 3 and 48 where level-2 > level-1. level-1 indicates a COBOL level between 2 and 47. 2. and graphic host variables. character. format-options indicates valid datetime options that are supported by the COBOL compiler. and graphic-host variables. For details on declaring numeric. See the ILE COBOL for AS/400 Reference. Chapter 13. SC09-2539-01 book for details. VALUE IS numeric-constant 49 var-3 PICTURE PIC BINARY COMPUTATIONAL-4 COMP-4 picture-string-3 IS DISPLAY-1 USAGE IS VALUE IS constant datetime: variable-name FORMAT OF DATE TIME TIMESTAMP format-options IS Notes: 1. COPY DDSR-format-name. 3. COPY DDS-ALL-FORMATS. with i instances of 9). level-1 indicates a COBOL level between 2 and 48. and COPY DDSR-ALLFORMATS to retrieve host variables from the file definitions. COPY DD-ALL-FORMATS. DB2 UDB for AS/400 Sample Tables.9. COPY DDS-format-name. 4. COPY DDS-ALL-FORMATS OF DEPARTMENT. The picture-string associated with these types must have the form S9(i) (or S9. and COMP-4 are equivalent. A portable application should code BINARY. COPY DDR-format-name. Var-1 is compared against the format name and the field name. You must place the COPY DDx-format statement within a COBOL host structure. If the REPLACING option is specified. | | | | | A host structure named DEPARTMENT-STRUCTURE is defined with an 05 level field named DEPARTMENT-RECORD that contains four 06 level fields named 272 DB2 UDB for AS/400 SQL Programming V4R4 . level-2 var-1 PICTURE PIC picture-string IS USAGE IS BINARY COMPUTATIONAL-4 COMP-4 VALUE IS constant . BINARY. If they are equal. COPY DDR-ALL-FORMATS. Notes: 1. 2. COMPUTATIONAL-4. you can code the following: 01 DEPARTMENT-STRUCTURE. To retrieve the definition of the sample table DEPARTMENT described in Appendix A. Dimension must be an integer constant between 1 and 32767.Host Array Indicator Structure This figure shows the valid syntax for host structure array indicators. var-2 is used as the new name. i must be less than or equal to 4. only complete name replacing is done. Note: You cannot retrieve host variables from file definitions that have field names which are COBOL reserved words. level-2 indicates a COBOL level between 3 and 48 where level-2 > level-1. Host Structure Array Indicator Structure level-1 variable-name OCCURS dimension TIMES .. Using External File Descriptions SQL uses the COPY DD-format-name.. because COMPUTATIONAL-4 and COMP-4 are IBM extensions that are not supported in ISO/ANSI COBOL. see the COBOL/400 User’s Guide book and the ILE COBOL for AS/400 Reference book. Chapter 13. EXEC SQL FETCH C1 FOR 10 ROWS INTO :DEPARTMENT END-EXEC. Note: DATE. a date host variable can only be compared against a DATE column or a character string which is a valid representation of a date. These field names can be used as host variables in SQL statements. For example. COPY DDS-ALL-FORMATS OF DEPARTMENT. the structure cannot be used as a host structure array. TIME. TIME.DEPARTMENT END EXEC. If the file contains fields that are generated as FILLER. and TIMESTAMP columns will generate character host variable definitions that are treated by SQL with the same comparison and assignment rules as the DATE. If the GRAPHIC or VARGRAPHIC column has a UCS-2 CCSID. DEPTNAME. EXEC SQL OPEN C1 END-EXEC. if INDARA was not specified and the file contains indicators. 04 DEPT-ARRAY OCCURS 10 TIMES. The structure cannot contain any additional declares at the 05 level. : EXEC SQL DECLARE C1 CURSOR FOR SELECT * FROM CORPDATA. the generated host variable will have the UCS-2 CCSID assigned to it. Using External File Descriptions for Host Structure Arrays Because COBOL creates an extra level when including externally described data. The indicator area is included in the generated structure and causes the storage for records to not be contiguous. or TIMESTAMP column. For example. the following shows how to use COPY–DDS to generate a host structure array and fetch 10 rows into the host structure array: 01 DEPT. For more information on the COBOL COPY verb. MGRNO. SQL considers these GRAPHIC and VARGRAPHIC variables. Although GRAPHIC and VARGRAPHIC are mapped to character variables in COBOL for AS/400. the OCCURS clause must be placed on the preceding 04 level. and ADMRDEPT. Coding SQL Statements in COBOL Applications 273 .DEPTNO. the declaration cannot be used as a host structure array. For device files. d in NUMERIC(i+d. d in No exact byte 2 equivalent use DECIMAL(i+d.d) i+d in byte 1.d) or NUMERIC (i+d. COBOL Declarations Mapped to Typical SQL Data Types COBOL Data Type S9(i)V9(d) COMP-3 or S9(i)V9(d) COMP or S9(i)V9(d) PACKED-DECIMAL S9(i)V9(d) DISPLAY SIGN LEADING SEPARATE SQLTYPE of Host Variable 484 SQLLEN of Host Variable SQL Data Type i+d in byte 1.d) byte 2 i+d in byte 1.d) or NUMERIC (i+d.d) or NUMERIC (i+d. d in No exact byte 2 equivalent use DECIMAL(i+d. the SQLTYPE is the base SQLTYPE plus one. d in No exact byte 2 equivalent use DECIMAL(i+d. If a host variable appears with an indicator variable.d) byte 2 2 4 SMALLINT INTEGER 504 S9(i)V9(d)DISPLAY S9(i) BINARY or S9(i) COMP-4 where i is from 1 to 4 S9(i) BINARY or S9(i) COMP-4 where i is from 5 to 9 S9(i)V9(d) BINARY or S9(i)V9(d) COMP-4 where i+d ≤ 4 488 500 496 500 i+d in byte 1.d) i+d in byte 1.Determining Equivalent SQL and COBOL Data Types The precompiler determines the base SQLTYPE and SQLLEN of host variables based on the following table. Table 26. d in DECIMAL(i+d.d) 4 8 m m m m m m FLOAT(single precision) FLOAT(double precision) CHAR(m) VARCHAR(m) VARCHAR(m) GRAPHIC(m) VARGRAPHIC(m) VARGRAPHIC(m) DATE TIME 26 TIMESTAMP S9(i)V9(d) BINARY or S9(i)V9(d) COMP-4 where 4 < i+d ≤ 9 496 COMP-1 COMP-2 Fixed-length character data Varying-length character data where m < 255 Varying-length character data where m > 254 Fixed-length graphic data Varying-length graphic data where m < 128 Varying-length graphic data where m > 127 480 480 452 448 456 468 464 472 384 388 392 | | | DATE TIME TIMESTAMP 274 DB2 UDB for AS/400 SQL Programming V4R4 . Use SQL TYPE IS to declare a CLOB. allow at least 8 characters. *JIS. Table 27. Fixed-length character string If the format is *USA.The following table can be used to determine the COBOL data type that is equivalent to a given SQL data type. If s=0. Coding SQL Statements in COBOL Applications 275 . allow at least 6 characters. Not supported for COBOL for AS/400. For ILE COBOL for AS/400. *DMY. COMP-2 for ILE COBOL for AS/400. DATE or DATE (for ILE COBOL for AS/400) Chapter 13. Varying-length graphic string for ILE COBOL for AS/400. NUMERIC(p. Not supported for COBOL for AS/400. 0<=s<=p<=18. For ILE COBOL for AS/400. Fixed-length character string Varying-length character string None 32766≥n≥1 32740≥n≥1 Use SQL TYPE IS to declare a BLOB.s) FLOAT(single precision) FLOAT(double precision) CHAR(n) VARCHAR(n) BLOB CLOB None GRAPHIC(n) Fixed-length graphic string for 16383≥n≥1 ILE COBOL for AS/400. Notes m is from 1 to 4 m is from 5 to 9 p is precision. or *ISO. use SV9(s). If the format is *JUL. If the format is *YMD. use SV9(s). If s=p. For ILE COBOL for AS/400. p is precision. *EUR. Not supported for COBOL for AS/400. or *MDY. use S9(p) or S9(p)V. 0<=s<=p<=18. allow at least 10 characters. Not supported for COBOL for AS/400. s is scale. Not supported for COBOL for AS/400. Not supported for COBOL for AS/400. SQL Data Types Mapped to Typical COBOL Declarations SQL Data Type SMALLINT INTEGER DECIMAL(p. If s=0. Not supported for COBOL for AS/400.s) COBOL Data Type S9(m) COMP-4 S9(m) COMP-4 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 If p<19: S9(p-s)V9(s) DISPLAY If p>18: Not supported COMP-1 for ILE COBOL for AS/400. If s=p. s is scale. use S9(p) or S9(p)V. None 16370≥n≥1 VARGRAPHIC(n) DBCLOB Use SQL TYPE IS to declare a DBCLOB. an indicator variable is used to show whether its associated host variable has been assigned a null value. Ensure that the size of numbers in your application is within the declared number of digits. and the declarations of the two can be mixed in any way that seems appropriate to the programmer. However. On retrieval. On assignment to a column. 8 to include seconds. The COBOL declarations for SMALLINT and INTEGER data types are expressed as a number of decimal digits. You can also specify an indicator structure (defined as an array of halfword integer variables) to support a host structure. where m is from 1 to 4). SQL Data Types Mapped to Typical COBOL Declarations (continued) SQL Data Type TIME COBOL Data Type Fixed-length character string Notes Allow at least 6 characters. To include microseconds at full precision. Indicator variables are declared in the same way as host variables. If n is less than 26. or TIME (for ILE COBOL for AS/400) TIMESTAMP n must be at least 19. a negative indicator variable is used to indicate that a null value should be assigned. However. this can cause data truncation or size errors when COBOL statements are being run. Unpredictable results may occur when a structure contains levels defined below a FILLER item. Fixed-length character string or TIMESTAMP (for ILE COBOL for AS/400) DATALINK Not supported Notes on COBOL Variable Declaration and Usage Any level 77 data description entry can be followed by one or more REDEFINES entries. the names in these entries cannot be used in SQL statements. Using Indicator Variables An indicator variable is a two-byte integer (PIC S9(m) USAGE BINARY. truncation occurs on the microseconds part.Table 27. n must be 26. 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. See DB2 UDB for AS/400 SQL Reference for more information on the use of indicator variables. Example: Given the statement: 276 DB2 UDB for AS/400 SQL Programming V4R4 . Coding SQL Statements in COBOL Applications 277 . :NUMDAY :NUMDAY-IND. 77 CLS-CD PIC X(7). :ENDCLS :ENDCLS-IND END-EXEC. The variables can be declared as follows: EXEC SQL BEGIN DECLARE SECTION END-EXEC. Chapter 13. 77 BGN-IND PIC S9(4) BINARY. 77 NUMDAY PIC S9(4) BINARY. :BGN :BGN-IND. 77 ENDCLS PIC X(8). 77 NUMDAY-IND PIC S9(4) BINARY. 77 BGN PIC X(8). EXEC SQL END DECLARE SECTION END-EXEC. 77 ENDCLS-IND PIC S9(4) BINARY.EXEC SQL FETCH CLS_CURSOR INTO :CLS-CD. 278 DB2 UDB for AS/400 SQL Programming V4R4 . Sample Programs Using DB2 UDB for AS/400 Statements. 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). v An SQLCA (which contains an SQLCODE and SQLSTATE variable). CHAR(1). SQLSTATE. © Copyright IBM Corp. The included PL/I source statements for the SQLCA are: DCL 1 SQLCA. 1999 279 . FIXED(31) BINARY. CHAR(8). CHAR(1). Coding SQL Statements in PL/I Applications This chapter describes the unique application and coding requirements for embedding SQL statements in an AS/400 PL/I program. FIXED(31) BINARY. CHAR(1). The SQLCODE and SQLSTATE values are set by the database manager after each SQL statement is executed. Defining the SQL Communications Area A PL/I program that contains SQL statements must include one or both of the following: v An SQLCODE variable declared as FIXED BINARY(31) v An SQLSTATE variable declared as CHAR(5) Or. 2 SQLCAID 2 SQLCABC 2 SQLCODE 2 SQLERRM 2 SQLERRP 2 SQLERRD(6) 2 SQLWARN. CHAR(1). is provided in Appendix C.Chapter 14. CHAR(5). and SQLCA variables must include the scope of all SQL statements in the program. Using the SQL INCLUDE statement requests the inclusion of a standard SQLCA declaration: EXEC SQL INCLUDE SQLCA . CHAR(70) VAR. The scope of the SQLCODE. The SQLCA can be coded in a PL/I program either directly or by using the SQL INCLUDE statement. CHAR(1). CHAR(1). An application can check the SQLCODE or SQLSTATE value to determine whether the last SQL statement was successful. CHAR(1). CHAR(1). CHAR(1). showing how SQL statements can be used. 1997. CHAR(1). FIXED(31) BINARY. CHAR(1). Requirements for host structures and host variables are defined. A detailed sample PL/I program. USING DESCRIPTOR descriptor-name DESCRIBE statement-name INTO descriptor-name DESCRIBE TABLE host-variable INTO descriptor-name PREPARE statement-name INTO descriptor-name Unlike the SQLCA. For more information on SQLCA. 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. and an SQLDA can have any valid name.USING DESCRIPTOR descriptor-name OPEN. a list of the data to be returned as part of the query) that runs dynamically requires an SQL descriptor area (SQLDA). For more information on SQLDA. An SQLDA can be coded in a PL/I program either program directly or by using the SQL INCLUDE statement. 3 SQLTYPE FIXED(15) BINARY. see Appendix B. your program can develop and then run SQL statements while the program is running. 2 SQLDAID CHAR(8). Embedding SQL Statements The first statement of the PL/I program must be a PROCEDURE statement. “SQL Communication Area” in the DB2 UDB for AS/400 SQL Reference book..SQLCODE is replaced with SQLCADE when a declare for SQLCODE is found in the program and the SQLCA is provided by the precompiler. 2 SQLN FIXED(15) BINARY. 2 SQLDABC FIXED(31) BINARY.USING DESCRIPTOR descriptor-name FETCH. A SELECT statement with a variable SELECT list (that is. 2 SQLD FIXED(15) BINARY.... Dynamic SQL Applications.. 3 SQLLEN FIXED(15) BINARY. Defining SQL Descriptor Areas The following statements require an SQLDA: EXECUTE. 3 SQLNAME CHAR(30) VAR. 3 SQLIND PTR. Dynamic SQL is an advanced programming technique described in Chapter 10. there can be more than one SQLDA in a program. DCL SQLDAPTR PTR. 3 SQLDATA PTR.. 3 SQLRES CHAR(12). With dynamic SQL. see the DB2 UDB for AS/400 SQL Reference book. SQLSTATE is replaced with SQLSTOTE when a declare for SQLSTATE is found in the program and the SQLCA is provided by the precompiler.. 280 DB2 UDB for AS/400 SQL Programming V4R4 . Using the SQL INCLUDE statement requests the inclusion of a standard SQLDA declaration: EXEC SQL INCLUDE SQLDA . The included PL/I source statements for the SQLDA are: DCL 1 SQLDA BASED(SQLDAPTR).USING DESCRIPTOR descriptor-name CALL.. 2 SQLVAR(99). ).3.+..... see Appendix D... Coding SQL Statements in PL/I Applications 281 ....+. Margins Code SQL statements within the margins specified by the MARGINS parameter on the CRTSQLPLI command.... Constants containing DBCS data can be continued across multiple lines by placing the shift-in and shift-out characters outside of the margins..SQL statements can be coded in a PL/I program wherever executable statements can appear. Continuation for SQL Statements The line continuation rules for SQL statements are the same as those for other PL/I statements..*/) in embedded SQL statements wherever a blank is allowed. If EXEC SQL does not start within the specified margins. Each SQL statement in a PL/I program must begin with EXEC SQL and end with a semicolon (.+.... For more information about the CRTSQLPLI command.. 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 . except between the keywords EXEC and SQL.. DB2 UDB for AS/400 CL Command Descriptions.. The key words EXEC SQL must appear all on one line. you can include PL/I comments (/*... Chapter 14.4..+.. 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 .)....... This SQL statement has a valid graphic constant of G’<AABBCCDDEEFFGGHHIIJJKK>’. EXEC SQL SELECT * FROM GRAPHTAB WHERE GRAPHCOL = G'<AABBCCDD> <EEFFGGHHIIJJKK>'..+..1. No PL/I preprocessor directives are permitted within SQL statements... except that EXEC SQL must be specified within one line. *(. Comments In addition to SQL comments (--).+. This example assumes margins of 2 and 72.. the SQL precompiler will not recognize the SQL statement.5....+....7.6.. PL/I %INCLUDE statements cannot be used to include SQL statements or declarations of PL/I host variables that are referenced in SQL statements. but the remainder of the statement can appear on the next and subsequent lines..2. 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. Using Host Variables All host variables used in SQL statements must be explicitly declared. it must be followed by a PL/I element-locator-expression. Host variables must be scalar variables. These restrictions are: v A declaration with the EXTERNAL scope attribute and the STATIC storage attribute must also have the INITIAL storage attribute. the alignment. if ignored. can have a label prefix. there are some restrictions on their use that. and storage attributes are ignored. Only the names and data attributes of the variables are used by the precompilers. Statement Labels All executable SQL statements. all host variable declarations used in SQL statements must be between the BEGIN DECLARE SECTION and the END DECLARE SECTION statements. 'RDI'. Even though alignment. 282 DB2 UDB for AS/400 SQL Programming V4R4 . An SQL statement that uses a host variable must be within the scope of the statement in which the variable was declared. and storage are ignored. The names of host variables must be unique within the program. All host variables within an SQL statement must be preceded by a colon (:). scope. The PL/I statements that are used to define the host variables should be preceded by a BEGIN DECLARE SECTION statement and followed by an END DECLARE SECTION statement. They cannot be elements of an array. These names are reserved for the database manager. scope.Names Any valid PL/I 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'. If a BEGIN DECLARE SECTION and END DECLARE SECTION are specified. v If the BASED storage attribute is coded. even if the host variables are in different blocks or procedures. or 'DSN'. may result in problems when compiling PL/I source code that is created by the precompiler. like PL/I statements. Declaring Host Variables The PL/I precompilers only recognize a subset of valid PL/I declarations as valid host variable declarations. Numeric DECLARE DCL variable-name . scale) can be specified in any order.Numeric-Host Variables The following figure shows the syntax for valid scalar numeric-host variable declarations. The optional V indicates the implied decimal point. 2.. A picture-string in the form ’S9.R’ indicates a numeric host variable. or DEC) and (FIXED or FLOAT) and (precision. Chapter 14. Character-Host Variables The following figure shows the syntax for valid scalar character-host variables.9V9. Coding SQL Statements in PL/I Applications 283 ... The S is required..9’ indicates a sign leading separate host variable. The optional V indicates the implied decimal point. (BINARY. 3. ( variable-name ) BINARY BIN FIXED ( precision ) FLOAT ( precision ) DECIMAL DEC FIXED ( precision .9V9... DECIMAL. BIN. The R is required.. A picture-string in the form ’9.scale FLOAT ( precision ) ) PICTURE picture-string . Alignment and/or Scope and/or Storage Notes: 1.. Alignment and/or Scope and/or Storage Notes: 1. Length must be an integer constant not greater than 32766 if VARYING or VAR is not specified.766 3. LOB Host Variables can be declared in host structures. SQL TYPE IS. For BLOB and CLOB. ( variable-name ) SQL TYPE IS BLOB CLOB | | | | | | | | | | | | | | ( lob-length K ) . ( variable-name ) CHARACTER CHAR ( length ) VARYING VAR . The SQL TYPE IS clause is needed in order to distinguish the three LOB-types from each other so that type-checking and function resolution can be carried out for LOB-type host variables that are passed to functions. If VARYING or VAR is specified. LOB DECLARE DCL variable-name . 1 <= lob-length <= 32. 4. Alignment and/or Scope and/or Storage Notes: 1. 284 DB2 UDB for AS/400 SQL Programming V4R4 .Character DECLARE DCL variable-name . CLOB can be in mixed case. length must be a constant no greater than 32740. BLOB. 2. 2. | | | | | | LOB Host Variables The following figure shows the syntax for valid LOB host variables. | | | | | | | | | | | | | | | | | | | | BLOB Example: The following declaration: DCL MY_BLOB SQL TYPE IS BLOB(16384); Results in the generation of the following structure: DCL 1 MY_BLOB, 3 MY_BLOB_LENGTH BINARY FIXED (31), 3 MY_BLOB_DATA CHARACTER (16384); CLOB Example: The following declaration: DCL MY_CLOB SQL TYPE IS CLOB(16384); Results in the generation of the following structure: DCL 1 MY_CLOB, 3 MY_CLOB_LENGTH BINARY FIXED (31), 3 MY_CLOB_DATA CHARACTER (16384); LOB Locators The following figure shows the syntax for valid LOB locators. LOB locator DECLARE DCL variable-name , ( variable-name ) | | SQL TYPE IS BLOB_LOCATOR CLOB_LOCATOR DBCLOB_LOCATOR | | || | | | | | | | | | | ; Alignment and/or Scope and/or Storage Notes: 1. SQL TYPE IS, BLOB_LOCATOR, CLOB_LOCATOR, DBCLOB_LOCATOR can be in mixed case. 2. LOB Locators can be declared as part of a host structure. CLOB Example: The following declaration: DCL MY_LOCATOR SQL TYPE IS CLOB_LOCATOR; Results in the generation of the following structure: DCL MY_LOCATOR BINARY FIXED(32); Chapter 14. Coding SQL Statements in PL/I Applications 285 | | | | | | | BLOB and DBCLOB locators have similar syntax. LOB File Reference Variables The following figure shows the syntax for valid LOB file reference variables. LOB file reference variable DECLARE DCL variable-name , ( variable-name ) | | SQL TYPE IS BLOB_FILE CLOB_FILE DBCLOB_FILE | | | | | | | | | | | | | | | | | | | | | | | | | ; Alignment and/or Scope and/or Storage Notes: 1. SQL TYPE IS, BLOB_LOCATOR, CLOB_LOCATOR, DBCLOB_LOCATOR can be in mixed case. 2. LOB File Reference Variables can be declared as part of a host structure. CLOB Example: The following declaration: DCL MY_FILE SQL TYPE IS CLOB_FILE; Results in the generation of the following structure: DCL 1 MY_FILE, 3 MY_FILE_NAME_LENGTH BINARY FIXED(32), 3 MY_FILE_DATA_LENGTH BINARY FIXED(32), 3 MY_FILE_FILE_OPTIONS BINARY FIXED(32), 3 MY_FILE_NAME CHAR(255); BLOB and DBCLOB locators have similar syntax. The pre-compiler will generate declarations for the following file option constants: v SQL_FILE_READ (2) v SQL_FILE_CREATE (8) v SQL_FILE_OVERWRITE (16) v SQL_FILE_APPEND (32) Using Host Structures In PL/I programs, you can define a host structure, which is a named set of elementary PL/I variables. A host structure name can be a group name whose subordinate levels name elementary PL/I variables. For example: 286 DB2 UDB for AS/400 SQL Programming V4R4 DCL 1 A, 2 B, 3 C1 CHAR(...), 3 C2 CHAR(...); In this example, B is the name of a host structure consisting of the elementary items C1 and C2. You can use the structure name as shorthand notation for a list of scalars. You can qualify a host variable with a structure name (for example, STRUCTURE.FIELD). Host structures are limited to two levels. (For example, in the above host structure example, the A cannot be referred to in SQL.) A structure cannot contain an intermediate level structure. In the previous example, A could not be used as a host variable or referred to in an SQL statement. However, B is the first level structure. B can be referred to in an SQL statement. A host structure for SQL data is two levels deep and can be thought of as a named set of host variables. After the host structure is defined, you can refer to it in an SQL statement instead of listing the several host variables (that is, the names of the host variables that make up the host structure). For example, you can retrieve all column values from selected rows of the table CORPDATA.EMPLOYEE with: DCL 1 PEMPL, 5 EMPNO CHAR(6), 5 FIRSTNME CHAR(12) VAR, 5 MIDINIT CHAR(1), 5 LASTNAME CHAR(15) VAR, 5 WORKDEPT CHAR(3); ... EMPID = '000220'; ... EXEC SQL SELECT * INTO :PEMPL FROM CORPDATA.EMPLOYEE WHERE EMPNO = :EMPID; Host Structures The following figure shows the syntax for valid host structure declarations. Chapter 14. Coding SQL Statements in PL/I Applications 287 Host Structures DECLARE 1 variable-name DCL level-1 variable-name , , level-2 var-1 , ( var-2 ) data-types ; , Scope and/or storage data-types: BINARY BIN DECIMAL DEC FIXED FLOAT FIXED ( FLOAT ( precision ) UNALIGNED PICTURE picture-string CHARACTER CHAR ( length ) VARYING VAR ALIGNED ( precision ) precision , scale UNALIGNED ) 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. Host Structure Indicator Arrays The following figure shows the syntax for valid indicator arrays. 288 DB2 UDB for AS/400 SQL Programming V4R4 Host Structure Indicator Array DECLARE DCL variable-name ( dimension ) , ( variable-name ( dimension ) ) BINARY BIN FIXED ( precision ) ; Alignment and/or scope and/or storage Note: Dimension must be an integer constant between 1 and 32766. Using Host Structure Arrays In PL/I programs, you can define a host structure array. In these examples, the following are true: v B_ARRAY is the name of a host structure array that contains the items C1_VAR and C2_VAR. v B_ARRAY cannot be qualified. v B_ARRAY can only be used with the blocked forms of the FETCH and INSERT statements. v All items in B_ARRAY must be valid host variables. v C1_VAR and C2_VAR are not valid host variables in any SQL statement. A structure cannot contain an intermediate level structure. A_STRUCT cannot contain the dimension attribute. DCL 1 A_STRUCT, 2 B_ARRAY(10), 3 C1_VAR CHAR(20), 3 C2_FIXED BIN(15) UNALIGNED; To retrieve 10 rows from the CORPDATA.DEPARTMENT table, do the following: DCL 1 DEPT(10), 5 DEPTPNO CHAR(3), 5 DEPTNAME CHAR(29) VAR, 5 MGRNO CHAR(6), 5 ADMRDEPT CHAR (3); DCL 1 IND_ARRAY(10), 5 INDS(4) FIXED BIN(15); EXEC SQL DECLARE C1 CURSOR FOR SELECT * FROM CORPDATA.DEPARTMENT; EXEC SQL FETCH C1 FOR 10 ROWS INTO :DEPT :IND_ARRAY; Chapter 14. Coding SQL Statements in PL/I Applications 289 Host Structure Array The following syntax diagram shows the syntax for valid structure array declarations. Host Structure Array DECLARE 1 variable-name ( dimension ) DCL level-1 variable-name , , level-2 var-1 , ( var-2 ) data-types ; , Scope and/or storage data-types: BINARY BIN DECIMAL DEC FIXED FLOAT FIXED ( FLOAT UNALIGNED ( precision ) precision ) , 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. Host Structure Array Indicator The following figure shows the syntax diagram for valid host structure array indicator structure declarations. 290 DB2 UDB for AS/400 SQL Programming V4R4 Host Structure Array Indicator Structure DECLARE 1 variable-name ( dimension ) DCL level-1 variable-name , level-2 identifier ( dimension-2 ) BINARY BIN , Scope and/or storage FIXED ( precision ) ; Notes: 1. Level-1 indicates that there is an intermediate level structure. 2. Level-1 must be an integer constant between 1 and 254. 3. Level-2 must be an integer constant between 2 and 255. 4. Dimension-1 and dimension-2 must be integer constants between 1 and 32767. Using External File Descriptions You can use the PL/I %INCLUDE directive to include the definitions of externally described files in a source program. When used with SQL, only a particular format of the %INCLUDE directive is recognized by the SQL precompiler. That directive format must have the following three elements or parameter values, otherwise the precompiler ignores the directive. The required elements are file name, format name, and element type. There are two optional elements supported by the SQL precompiler: prefix name and COMMA. The structure is ended normally by the last data element of the record or key structure. However, if in the %INCLUDE directive the COMMA element is specified, then the structure is not ended. For more information about the %INCLUDE directive, see the PL/I Reference Summary book, SX09-1290, and the PL/I User’s Guide and Reference book, SC09-1825. To include the definition of the sample table DEPARTMENT described in Appendix A. DB2 UDB for AS/400 Sample Tables, you can code: DCL 1 TDEPT_STRUCTURE, %INCLUDE DEPARTMENT(DEPARTMENT,RECORD); In the above example, a host structure named TDEPT_STRUCTURE would be defined having four fields. The fields would be DEPTNO, DEPTNAME, MGRNO, and ADMRDEPT. For device files, if INDARA was not specified and the file contains indicators, the declaration cannot be used as a host structure array. The indicator area is included in the generated structure and causes the storage to not be contiguous. DCL : 1 DEPT_REC(10), %INCLUDE DEPARTMENT(DEPARTMENT,RECORD); EXEC SQL DECLARE C1 CURSOR FOR SELECT * FROM CORPDATA.DEPARTMENT; EXEC SQL OPEN C1; Chapter 14. Coding SQL Statements in PL/I Applications 291 EXEC SQL FETCH C1 FOR 10 ROWS INTO :DEPT_REC; Note: DATE, TIME, and TIMESTAMP columns will generate host variable definitions that are treated by SQL with the same comparison and assignment rules as a DATE, TIME, and TIMESTAMP column. For example, a date host variable can only be compared with a DATE column or a character string that is a valid representation of a date. Although decimal and zoned fields with precision greater than 15 and binary with nonzero scale fields are mapped to character field variables in PL/I, SQL considers these fields to be numeric. Although GRAPHIC and VARGRAPHIC are mapped to character variables in PL/I, SQL considers these to be GRAPHIC and VARGRAPHIC host variables. If the GRAPHIC or VARGRAPHIC column has a UCS-2 CCSID, the generated host variable will have the UCS-2 CCSID assigned to it. Determining Equivalent SQL and PL/I Data Types The precompiler determines the base SQLTYPE and SQLLEN of host variables based on the following table. If a host variable appears with an indicator variable, the SQLTYPE is the base SQLTYPE plus one. Table 28. PL/I Declarations Mapped to Typical SQL Data Types PL/I Data Type BIN FIXED(p) where p is in the range 1 to 15 BIN FIXED(p) where p is in the range 16 to 31 DEC FIXED(p,s) BIN FLOAT(p) p is in the range 1 to 24 BIN FLOAT(p) p is in the range 25 to 53 SQLTYPE of Host Variable 500 496 484 480 480 SQLLEN of Host Variable SQL Data Type 2 4 p in byte 1, s in byte 2 4 8 4 8 p in byte 1, s in byte 2 p in byte 1, s in byte 2 n n n SMALLINT INTEGER DECIMAL(p,s) FLOAT (single precision) FLOAT (double precision) FLOAT (single precision) FLOAT (double precision) NUMERIC (p,s) No exact equivalent, use NUMERIC(p,s). CHAR(n) VARCHAR(n) VARCHAR(n) DEC FLOAT(m) m is in the range 1 480 to 7 DEC FLOAT(m) m is in the range 8 480 to 16 PICTURE picture string (numeric) PICTURE picture string (sign leading separate) CHAR(n) CHAR(n) VARYING where n <255 CHAR(n) varying where n > 254 488 504 452 448 456 292 DB2 UDB for AS/400 SQL Programming V4R4 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 SMALLINT INTEGER DECIMAL(p,s) or NUMERIC(p,s) PL/I Equivalent BIN FIXED(p) BIN FIXED(p) DEC FIXED(p) or DEC FIXED(p,s) or PICTURE picture-string Explanatory Notes p is a positive integer from 1 to 15. p is a positive integer from 16 to 31. s (the scale factor) and p (the precision) are positive integers. p is a positive integer from 1 to 31. s is a positive integer from 0 to p. p is a positive integer from 1 to 24. m is a positive integer from 1 to 7. FLOAT (single precision) BIN FLOAT(p) or DEC FLOAT(m) FLOAT (double precision) BIN FLOAT(p) or DEC FLOAT(m) p is a positive integer from 25 to 53. m is a positive integer from 8 to 16. CHAR(n) VARCHAR(n) BLOB CLOB GRAPHIC(n) VARGRAPHIC(n) DBCLOB DATE CHAR(n) CHAR(n) VAR None None Not supported Not supported None CHAR(n) n is a positive integer from 1 to 32766. n is a positive integer from 1 to 32740. Use SQL TYPE IS to declare a BLOB. Use SQL TYPE IS to declare a CLOB. Not supported. Not supported. Use SQL TYPE IS to declare a DBCLOB. If the format is *USA, *JIS, *EUR, or *ISO, n must be at least 10 characters. If the format is *YMD, *DMY, or *MDY, n must be at least 8 characters. If the format is *JUL, n must be at least 6 characters. TIME CHAR(n) n must be at least 6; to include seconds, n must be at least 8. n must be at least 19. To include microseconds at full precision, n must be 26; if n is less than 26, truncation occurs on the microseconds part. TIMESTAMP CHAR(n) Chapter 14. Coding SQL Statements in PL/I Applications 293 Table 29. SQL Data Types Mapped to Typical PL/I Declarations (continued) SQL Data Type DATALINK PL/I Equivalent Not supported Explanatory Notes Not supported Using Indicator Variables An indicator variable is a two-byte integer (BIN FIXED(p), where p is 1 to 15). You can also specify an indicator structure (defined as an array of halfword integer variables) to support a host structure. On retrieval, an indicator variable is used to show whether its associated host variable has been assigned a null value. On assignment to a column, a negative indicator variable is used to indicate that a null value should be assigned. See DB2 UDB for AS/400 SQL Reference book for more information about using indicator variables. Indicator variables are declared in the same way as host variables and the declarations of the two can be mixed in any way that seems appropriate to the programmer. Example: Given the statement: EXEC SQL FETCH CLS_CURSOR INTO :CLS_CD, :DAY :DAY_IND, :BGN :BGN_IND, :END :END_IND; Variables can be declared as follows: EXEC SQL BEGIN DECLARE SECTION; DCL CLS_CD CHAR(7); DCL DAY BIN FIXED(15); DCL BGN CHAR(8); DCL END CHAR(8); DCL (DAY_IND, BGN_IND, END_IND) EXEC SQL END DECLARE SECTION; BIN FIXED(15); Differences in PL/I Because of Structure Parameter Passing Techniques The PL/I precompiler attempts to use the structure parameter passing technique, if possible. This structure parameter passing technique provides better performance for most PL/I programs using SQL. The precompiler generates code where each host variable is a separate parameter when the following conditions are true: v A PL/I %INCLUDE compiler directive is found that copies external text into the source program. v The data length of the host variables referred to in the statement is greater than 32703. Because SQL uses 64 bytes of the structure, 32703 + 64 = 32767, the maximum length of a data structure. v The PL/I precompiler estimates that it could possibly exceed the PL/I limit for user-defined names. v A sign leading separate host variable is found in the host variable list for the SQL statement. 294 DB2 UDB for AS/400 SQL Programming V4R4 For more information on the structure parameter passing technique, see “Improving Performance by Using Structure Parameter Passing Techniques” on page 472. Chapter 14. Coding SQL Statements in PL/I Applications 295 296 DB2 UDB for AS/400 SQL Programming V4R4 Chapter 15. Coding SQL Statements in RPG for AS/400 Applications The RPG for AS/400 licensed program supports both RPG II and RPG III programs. SQL statements can only be used in RPG III programs. RPG II and AutoReport are NOT supported. All referrals to RPG in this guide apply to RPG III or ILE RPG only. This chapter describes the unique application and coding requirements for embedding SQL statements in a RPG for AS/400 program. Requirements for host variables are defined. A detailed sample RPG for AS/400 program, showing how SQL statements can be used, is provided in Appendix C. Sample Programs Using DB2 UDB for AS/400 Statements. Defining the SQL Communications Area The SQL precompiler automatically places the SQLCA in the input specifications of the RPG for AS/400 program prior to the first calculation specification. INCLUDE SQLCA should not be coded in the source program. If the source program specifies INCLUDE SQLCA, the statement will be accepted, but it is redundant. The SQLCA, as defined for RPG for AS/400: ISQLCA DS I* SQL Communications area I I I I I I I I I I I I I I I I I I I I I I I I I I I* End of SQLCA 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 B B B B B B B B B 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 them in the extension specification. SQLERR is defined as character with SQLER1 through 6 used as the names of the elements. © Copyright IBM Corp. 1997, 1999 297 See the DB2 UDB for AS/400 SQL Reference book for more information. Defining SQL Descriptor Areas The following statements require an SQLDA: EXECUTE...USING DESCRIPTOR descriptor-name FETCH...USING DESCRIPTOR descriptor-name OPEN...USING DESCRIPTOR descriptor-name CALL...USING DESCRIPTOR descriptor-name DESCRIBE statement-name INTO descriptor-name DESCRIBE TABLE host-variable INTO descriptor-name PREPARE statement-name INTO descriptor-name Unlike the SQLCA, there can be more than one SQLDA in a program and an SQLDA can have any valid name. Dynamic SQL is an advanced programming technique described in Chapter 10. 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. Because the SQLDA uses pointer variables which are not supported by RPG for AS/400, an INCLUDE SQLDA statement cannot be specified in an RPG for AS/400 program. An SQLDA must be set up by a C, COBOL, PL/I, or ILE RPG program and passed to the RPG program in order to use it. Embedding SQL Statements SQL statements coded in an RPG for AS/400 program must be placed in the calculation section. This requires that a C be placed in position 6. SQL statements can be placed in detail calculations, in total calculations, or in an RPG for AS/400 subroutine. The SQL statements are executed based on the logic of the RPG for AS/400 statements. The keywords EXEC SQL indicate the beginning of an SQL statement. EXEC SQL must occupy positions 8 through 16 of the source statement, preceded by a / in position 7. The SQL statement may start in position 17 and continue through position 74. The keyword END-EXEC ends the SQL statement. END-EXEC must occupy positions 8 through 16 of the source statement, preceded by a slash (/) in position 7. Positions 17 through 74 must be blank. Both uppercase and lowercase letters are acceptable in SQL statements. Example An UPDATE statement coded in an RPG for AS/400 program might be coded as follows: 298 DB2 UDB for AS/400 SQL Programming V4R4 *...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. Continuation for SQL Statements When additional records are needed to contain the SQL statement, positions 9 through 74 can be used. Position 7 must be a + (plus sign), and position 8 must be blank. Constants containing DBCS data can be continued across multiple lines by placing the shift-in character in position 75 of the continued line and placing the shift-out character in position 8 of the continuation line. This SQL statement has a valid graphic constant of G’<AABBCCDDEEFFGGHHIIJJKK>’. *...1....+....2....+....3....+....4....+....5....+....6....+....7....+....8 C/EXEC SQL SELECT * FROM GRAPHTAB WHERE GRAPHCOL = G'<AABB> C+<CCDDEEFFGGHHIIJJKK>' C/END-EXEC Including Code 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. 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. Chapter 15. Coding SQL Statements in RPG for AS/400 Applications 299 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. Using Host Variables | | All host variables used in SQL statements must be explicitly declared. LOB host variables are not supported in RPG for AS/400. SQL embedded in 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. Declaring Host Variables The SQL RPG for AS/400 precompiler only recognizes a subset of RPG for AS/400 declarations as valid host variable declarations. All variables defined in RPG for AS/400 can be used in SQL statements, except for the following: Indicator field names (*INxx) Tables UDATE UDAY UMONTH UYEAR Look-ahead fields Named constants Fields used as host variables are passed to SQL, using the CALL/PARM functions of RPG for AS/400. If a field cannot be used in the result field of the PARM, it cannot be used as a host variable. Using Host Structures The RPG for AS/400 data structure name can be used as a host structure name if subfields exist in the data structure. The use of the data structure name in an SQL statement implies the list of subfield names making up the data structure. When subfields are not present for the data structure, then the data structure name is a host variable of character type. This allows character variables larger than 256, because data structures can be up to 9999. 300 DB2 UDB for AS/400 SQL Programming V4R4 In the following example, BIGCHR is an RPG for AS/400 data structure without subfields. SQL treats any referrals to BIGCHR as a character string with a length of 642. *...1....+....2....+....3....+....4....+....5....+....6....+....7...* IBIGCHR DS 642 In the next example, PEMPL is the name of the host structure consisting of the subfields EMPNO, FIRSTN, MIDINT, LASTNAME, and DEPTNO. The referral to PEMPL uses the subfields. For example, the first column of EMPLOYEE is placed in EMPNO, the second column is placed in FIRSTN, and so on. *...1....+....2....+....3....+....4....+....5....+....6....+....7. ..* IPEMPL DS I 01 06 EMPNO I 07 18 FIRSTN I 19 19 MIDINT I 20 34 LASTNA I 35 37 DEPTNO C MOVE '000220' EMPNO ... ... C/EXEC SQL C+ SELECT * INTO :PEMPL C+ FROM CORPDATA.EMPLOYEE C+ WHERE EMPNO = :EMPNO C/END-EXEC When writing an SQL statement, referrals to subfields can be qualified. Use the name of the data structure, followed by a period and the name of the subfield. For example, PEMPL.MIDINT is the same as specifying only MIDINT. Using Host Structure Arrays A host structure array is defined as an occurrence data structure. An occurrence data structure can be used on the SQL FETCH statement when fetching multiple rows. In these examples, the following are true: v All items in BARRAY must be valid host variables. v All items in BARRAY must be contiguous. The first FROM position must be 1 and there cannot be overlaps in the TO and FROM positions. v For all statements other than the multiple-row FETCH and blocked INSERT, if an occurrence data structure is used, the current occurrence is used. For the multiple-row FETCH and blocked INSERT, the occurrence is set to 1. *...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 Chapter 15. Coding SQL Statements in RPG for AS/400 Applications 301 ... 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 Using External File Descriptions The SQL precompiler processes the RPG for AS/400 source in much the same manner as the ILE RPG for AS/400 compiler. This means that the precompiler processes the /COPY statement for definitions of host variables. Field definitions for externally described files are obtained and renamed, if different names are specified. The external definition form of the data structure can be used to obtain a copy of the column names to be used as host variables. In the following example, the sample table DEPARTMENT is used as a file in an ILE RPG for AS/400 program. The SQL precompiler retrieves the field (column) definitions for DEPARTMENT for use as host variables. *...1....+....2....+....3....+....4....+....5....+....6....+....7....* FTDEPT IP E DISK F TDEPT KRENAMEDEPTREC IDEPTREC I DEPTNAME DEPTN I ADMRDEPT ADMRD Note: Code an F-spec for a file in your RPG program only if you use RPG 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. *...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. 302 DB2 UDB for AS/400 SQL Programming V4R4 ... For device files.+. In the following example.. A multiple-row FETCH statement is then used to retrieve 10 rows into the host structure array......* ITDEPT E DSDEPARTMENT 10 I DEPARTMENT DEPTN I ADMRDEPT ADMRD ..6.5..... C/EXEC SQL C+ DECLARE C1 CURSOR FOR C+ SELECT * C+ FROM CORPDATA... the generated host variable will have the UCS-2 CCSID assigned to it. If the GRAPHIC or VARGRAPHIC column has a UCS-2 CCSID.+.4... The indicator area is included in the structure that is generated and would cause the storage to not be contiguous. *. Table 30... External File Description Considerations for Host Structure Arrays If the file contains floating-point fields.Although GRAPHIC and VARGRAPHIC columns are mapped to character variables in RPG for AS/400...3.. SQL considers these GRAPHIC and VARGRAPHIC variables.. If a host variable appears with an indicator variable.. it cannot be used as a host structure array.+.+...2.. if INDARA was not specified and the file contains indicators. RPG for AS/400 Declarations Mapped to Typical SQL Data Types RPG for AS/400 Data Type Data Structure subfield Data structure (without subfields) Input field Calculation result field Data Structure subfield Other RPG for AS/400 Coding Length = n where n ≤ 256 Length = n where n ≤ 9999 Length = n where n ≤ 256 Length = n where n ≤ 256 Length = 2 SQLTYPE of SQLLEN of Host Variable Host Variable 452 452 n n SQL Data Type CHAR(n) CHAR(n) Col 43 blank n/a Col 52 blank n/a blank n/a B blank blank 0 452 452 500 n n 2 CHAR(n) CHAR(n) SMALLINT Chapter 15.. the DEPARTMENT table is included in the RPG for AS/400 program and is used to declare a host structure array....1.. the SQLTYPE is the base SQLTYPE plus one...DEPARTMENT C/END-EXEC ...+. the declaration is not used as a host structure array.. Coding SQL Statements in RPG for AS/400 Applications 303 . C/EXEC SQL C+ FETCH C1 FOR 10 ROWS INTO :TDEPT C/END-EXEC Determining Equivalent SQL and RPG for AS/400 Data Types The precompiler determines the base SQLTYPE and SQLLEN of host variables based on the following table.. s) where p = n and s = column 52 NUMERIC(p.s) where p = n and s = column 52 DECIMAL(p.s) where p=4 if n=2 or 9 if n=4 and s = column 52 DECIMAL(p. Subfield of a data structure. B in position 43.s) where p = n*2-1 and s = column 52 DECIMAL(p. length must be 2 and 0 in position 52 of the subfield specification.Table 30. s in byte 2 Input field blank 0 to 9 Length = n where n is 1 to 30 484 p in byte 1. length must be 4 and 0 in position 52 of the subfield specification.s) where p = n*2-1 and s = column 52 DECIMAL(p. Notes INTEGER 304 DB2 UDB for AS/400 SQL Programming V4R4 . s in byte 2 The following table can be used to determine the RPG for AS/400 data type that is equivalent to a given SQL data type. s in byte 2 Input field P 0 to 9 Length = n where n is 1 to 16 484 p in byte 1.s) where p = n and s = column 52 Col 43 B B Col 52 0 1-4 B 1-9 Length = 4 496 4 P 0 to 9 Length = n where n is 1 to 16 484 p in byte 1. s in byte 2 Calculation result field n/a 0 to 9 Length = n where n is 1 to 30 484 p in byte 1.s) where s=column 52 DECIMAL(9. SQL Data Types Mapped to Typical RPG for AS/400 Declarations SQL Data Type SMALLINT RPG for AS/400 Data Type Subfield of a data structure. s in byte 2 Input field B 0 to 4 if n Length = 2 or 4 = 2. B in position 43. s in byte 2 Data Structure subfield blank 0 to 9 Length = n where n is 1 to 30 488 p in byte 1. Table 31. RPG for AS/400 Declarations Mapped to Typical SQL Data Types (continued) RPG for AS/400 Data Type Data Structure subfield Data Structure subfield Data Structure subfield Data Structure subfield Other RPG for AS/400 Coding Length = 4 Length = 2 SQLTYPE of SQLLEN of Host Variable Host Variable 496 500 4 2 SQL Data Type INTEGER DECIMAL(4.s) where s=column 52 DECIMAL(p. 0 to 9 if n = 4 484 p in byte 1. If the format is *YMD. Notes Maximum length of 16 (precision 30) and maximum scale of 9. the length must be at least 10. Not supported Not supported Not supported Not supported Not supported If the format is *USA. OR Defined as numeric and not a subfield of a data structure. OR Field defined without decimal places. NUMERIC Subfield of the data structure. OR Field defined without decimal places. Blank in position 52 of the subfield specification. DATALINK Not supported Not supported Chapter 15. No exact equivalent Maximum length of 30 (precision 30) and maximum scale of 9. Use one of the alternative numeric data types described above. the length must be at least 8. n can be from 1 to 256. truncation occurs on the microseconds part. Blank in positions 43 and 52 of the specification. OR Calculation result field defined without decimal places. Length must be at least 6. If length is less than 26. P in position 43 and 0 through 9 in position 52 of the subfield specification. length must be at least 8. *DMY. Coding SQL Statements in RPG for AS/400 Applications 305 . Blank in position 43 and 0 through 9 in position 52 of the subfield No exact equivalent No exact equivalent Subfield of a data structure or input field. Use a character host variable large enough to contain the largest expected VARCHAR value. CHAR(n) VARCHAR(n) Data structure name with no subfields in the data structure. or *ISO. or *MDY. TIME Subfield of a data structure. OR Field defined without decimal places. Use one of the alternative numeric data types described above. FLOAT (single precision) FLOAT (double precision) CHAR(n) n can be from 1 to 9999. the length must be at least 6. To include microseconds at full precision. TIMESTAMP Subfield of a data structure. Blank in position 52 of the subfield specification. Blank in position 52 of the subfield specification. If the format is *JUL. length must be 26. BLOB CLOB GRAPHIC(n) VARGRAPHIC(n) DBCLOB DATE Not supported Not supported Not supported Not supported Not supported Subfield of a data structure.Table 31. Length must be at least 19. to include seconds. *JIS. SQL Data Types Mapped to Typical RPG for AS/400 Declarations (continued) SQL Data Type DECIMAL RPG for AS/400 Data Type Subfield of a data structure. *EUR. ....+......1..+. an indicator variable is used to show whether its associated host variable has been assigned a null value..3. C+ :DAY :DAYIND... Data is aligned to the implied decimal point when SQL operations are performed.+..........* C/EXEC SQL FETCH CLS_CURSOR INTO :CLSCD.Notes on RPG for AS/400 Variable Declaration and Usage Assignment rules RPG for AS/400 associates precision and scale with all numeric types.+.. assuming the data is in packed format.6....+..+.1.+... C+ :END :ENDIND C/END-EXEC variables can be declared as follows: *.. An indicator structure can be defined by declaring the variable as an array with an element length of 4.6.+...... Example Given the statement: *..7.+.....+..2........ Using Indicator Variables An indicator variable is a two-byte integer (see the entry for the SMALLINT SQL data type in Table 30 on page 303).. a negative indicator variable is used to indicate that a null value should be assigned....... This means that operations involving binary variables include an implicit conversion to packed format before the operation is performed (and back to binary... RPG for AS/400 defines numeric operations.* 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 306 DB2 UDB for AS/400 SQL Programming V4R4 ...+..4..2....7. Indicator variables are declared in the same way as host variables and the declarations of the two can be mixed in any way that seems appropriate to the programmer.4... on assignment to a column.. See the DB2 UDB for AS/400 SQL Referencefor more information on the use of indicator variables.+....3.5....5. On retrieval...0 and declaring the array name as a subfield of a data structure with B in position 43.. if necessary).. C+ :BGN :BGNIND.... v An indicator is specified on the statement where the length of the indexed indicator name plus the required index value is greater than six characters. The SQL precompiler allocates static storage used by SQL run time to manage the internal SQLDAs properly. An RPG for AS/400 program containing SQL statements that is called by a program that also contains SQL statements. If an RPG for AS/400 program containing SQL is called from another program which also contains SQL.1″ requires seven characters). Subfields cannot be defined with a length greater than 256. Ending a Called RPG for AS/400 Program Correctly SQL run time builds and maintains data areas (internal SQLDAs) for each SQL statement which contains host variables. Setting the LR indicator on causes the static storage to be re-initialized the next time the RPG for AS/400 program is run. This allows the internal SQLDAs to be used again and reduces the total run time. thus causing a performance degradation. This can happen when a data structure without subfields is used as a host variable. The precompiler generates code where each host variable is a separate parameter when the following conditions are true: v The data length of the host variables. These internal SQLDAs are built the first time the statement is run and then reused on subsequent executions of the statement to increase performance.Differences in RPG for AS/400 Because of Structure Parameter Passing Techniques The SQL RPG for AS/400 precompiler attempts to use the structure parameter passing technique. the RPG for AS/400 program should not set the Last Record (LR) indicator on. if possible. Chapter 15. The internal SQLDAs can be reused as long as there is at least one SQL program active. v The length of a host variable is greater than 256. Re-initializing the static storage causes the internal SQLDAs to be rebuilt. should be ended one of two ways: v By the RETRN statement v By setting the RT indicator on. 9935 + 64 = 9999. The precompiler must generate an assignment statement for the indicator with the indicator name in the result field that is limited to six characters (″INDIC. For more information on the structure parameter passing technique. see “Improving Performance by Using Structure Parameter Passing Techniques” on page 472. Because SQL uses 64 bytes of the structure. referred to in the statement. is greater than 9935. and its length exceeds 256. Coding SQL Statements in RPG for AS/400 Applications 307 . the maximum length of a data structure. 308 DB2 UDB for AS/400 SQL Programming V4R4 . If the source program specifies INCLUDE SQLCA. The standard SQLCA names were changed to a length of 6 for RPG for AS/400. Coding SQL Statements in ILE RPG for AS/400 Applications This chapter describes the unique application and coding requirements for embedding SQL statements in an ILE RPG for AS/400 program. 1997. The SQLCA defined for the ILE RPG for AS/400 has added the field SQLERRD which is defined as an array of six integers. Defining the SQL Communications Area The SQL precompiler automatically places the SQLCA in the definition specifications of the ILE RPG for AS/400 program prior to the first calculation specification. The SQLCA. 1999 309 . as defined for ILE RPG for AS/400: D* SQL Communications area D SQLCA DS D SQLAID 1 8A D SQLABC 9 12B D SQLCOD 13 16B D SQLERL 17 18B D SQLERM 19 88A D SQLERP 89 96A D SQLERRD 97 120B D SQLERR 97 120A D SQLER1 97 100B D SQLER2 101 104B D SQLER3 105 108B D SQLER4 109 112B D SQLER5 113 116B D SQLER6 117 120B D SQLWRN 121 131A D SQLWN0 121 121A D SQLWN1 122 122A D SQLWN2 123 123A D SQLWN3 124 124A D SQLWN4 125 125A D SQLWN5 126 126A D SQLWN6 127 127A D SQLWN7 128 128A D SQLWN8 129 129A D SQLWN9 130 130A D SQLWNA 131 131A D SQLSTT 132 136A D* End of SQLCA 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 coding requirements for host variables are defined. To maintain compatibility with RPG for AS/400 programs which are converted to ILE RPG for AS/400. © Copyright IBM Corp. SQLERRD is defined to overlay the SQLERR definition. INCLUDE SQLCA should not be coded in the source program. the statement will be accepted.Chapter 16. the names for the SQLCA will remain as used with RPG for AS/400. but it is redundant. .+.+.8. SQL_NUM must be defined as a numeric constant with the dimension required for SQL_VAR.........4...+..7..USING DESCRIPTOR descriptor-name DESCRIBE statement-name INTO descriptor-name DESCRIBE TABLE host-variable INTO descriptor-name PREPARE statement-name INTO descriptor-name Unlike the SQLCA..... 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....Defining SQL Descriptor Areas The following statements require an SQLDA: EXECUTE. An INCLUDE SQLDA statement can be specified in an ILE RPG for AS/400 program..USING DESCRIPTOR descriptor-name CALL.. Dynamic SQL is an advanced programming technique described in the SQL programmers guide. D* SQL Descriptor area D SQLDA DS D SQLDAID 1 D SQLDABC 9 D SQLN 13 D SQLD 15 D SQL_VAR D 17 D 19 D 21 D 33 D 49 D 65 D 67 D* D SQLVAR DS D SQLTYPE 1 D SQLLEN 3 D SQLRES 5 D SQLDATA 17 D SQLIND 33 D SQLNAMELEN 49 D SQLNAME 51 D* End of SQLDA 8A 12B 14B 16B 80A 18B 20B 32A 48* 64* 66B 96A 0 0 0 0 0 DIM(SQL_NUM) 0 2B 0 4B 0 16A 32* 48* 50B 0 80A The user is responsible for the definition of SQL_NUM..5..+. With dynamic SQL.... your program can develop and then run SQL statements while the program is running.... a list of the data to be returned as part of the query) that runs dynamically requires an SQL descriptor area (SQLDA)..+.....2. A SELECT statement with a variable SELECT list (that is.USING DESCRIPTOR descriptor-name FETCH...USING DESCRIPTOR descriptor-name OPEN.6. The format of the statement is: *.+. there can be more than one SQLDA in a program and an SQLDA can have any valid name....... C/EXEC SQL INCLUDE SQLDA C/END-EXEC The INCLUDE SQLDA generates the following data structure..+. 310 DB2 UDB for AS/400 SQL Programming V4R4 ..3......1... 6. When the SQLDA field descriptions are to be referenced the user does a MOVEA of SQL_VAR.4..+.. SQL statements can be placed in detail calculations. and position 8 must be blank. The second data structure is used to setup/reference the part of the SQLDA which contains the field descriptions.Since ILE RPG for AS/400 does not support structures within arrays.7.. 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..8.. The keyword END-EXEC ends the SQL statement.. EXEC SQL must occupy positions 8 through 16 of the source statement.. The SQL statement may start in position 17 and continue through position 80.+.. ILE RPG for AS/400 comments can be included within SQL statements wherever SQL allows a blank character. in total calculations... C/EXEC SQL UPDATE DEPARTMENT C+ SET MANAGER = :MGRNUM C+ WHERE DEPTNO = :INTDEP C/END-EXEC Comments In addition to SQL comments (--).. This requires that a C be placed in position 6.+.... place an asterisk (*) in position 7... END-EXEC must occupy positions 8 through 16 of the source statement...+. The SQL statements are executed based on the logic of the RPG statements. Embedding SQL Statements SQL statements coded in an ILE RPG for AS/400 program must be placed in the calculation section..+.. Both uppercase and lowercase letters are acceptable in SQL statements.+.. preceded by a / in position 7...2... Continuation for SQL Statements When additional records are needed to contain the SQL statement. the INCLUDE SQLDA generates two data structures. To embed an ILE RPG for AS/400 comment within the SQL statement..n where n is the number of the field in the SQLDA.n to SQLVAR where n is the number of the field description to be processed. Position 7 must be a + (plus sign).1..... Positions 17 through 80 must be blank. preceded by a slash (/) in position 7. Example An UPDATE statement coded in an ILE RPG for AS/400 program might be coded as follows: *. This is repeated until all the field descriptions are set.5.3.+.. or in an RPG subroutines...... Position 80 of the continued line is concatenated with position 9 of the continuation line.... positions 9 through 80 can be used.... Chapter 16. Coding SQL Statements in ILE RPG for AS/400 Applications 311 . The keywords EXEC SQL indicate the beginning of an SQL statement... WHENEVER Statement The target for the GOTO clause must be the label of the TAG statement.6... The length of host variable names is limited to 64......1... For *SEQSRC. 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'.. Code the TAG statement on the line preceding EXEC SQL.8 C/EXEC SQL INCLUDE member-name C/END-EXEC The RPG /COPY statement can be used to include SQL statements or RPG specifications..4..... 'SQL'... 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: *..+.+..+... When *NOSEQSRC is specified.. These names are reserved for the database manager....3. In this example the SQL statement has a valid graphic constant of G’<AABBCCDDEEFFGGHHIIJJKK>’...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....+.+....+....+.. the sequence number from the input source member is used... The scope rules for the GOTO/TAG must be observed..+.......... or 'DSN'.... the sequence numbers start at 000001 and are incremented by 1..5..8.6.+.5..+.1..... Using Host Variables All host variables used in SQL statements must be explicitly declared.3... 'RDI'.....+..2.. *. 312 DB2 UDB for AS/400 SQL Programming V4R4 .2..4....+... 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..7.7.....+....+.... Statement Labels A TAG statement can precede any SQL statement..... If any date value is outside of this range. *EUR. or *JUL). Date and time host variables are always assigned to corresponding date and time subfields in the structures generated by the SQL precompiler. TIMFMT. Fields used as host variables are passed to SQL. even if the host variables are in different procedures. If a field cannot be used in the result field of the PARM. or *JIS. using the CALL/PARM functions of ILE RPG for AS/400. If the DATFMT parameter value is a system format (*MDY. All host variables within an SQL statement must be preceded by a colon (:). Do not put these statements in the source program. Coding SQL Statements in ILE RPG for AS/400 Applications 313 . *USA. All variables defined in ILE RPG for AS/400 can be used in SQL statements. *DMY. it cannot be used as a host variable.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. The generated date and time subfields are declared using the format and separator specified by the DATFMT. The names of host variables must be unique within the program. and TIMSEP parameters on the CRTSQLRPGI command. then the DATFMT on the precompile must be specified as one of the IBM SQL formats of *ISO. An SQL statement that uses a host variable must be within the scope of the statement in which the variable was declared. except for the following: Pointer Tables UDATE UDAY UMONTH UYEAR Look-ahead fields Named constants Multiple dimension arrays Definitions requiring the resolution of *SIZE or *ELEM Definitions requiring the resolution of constants unless the constant is used in OCCURS or DIM. DATSEP. Conversion from the user declared host variable format to the precompile specified format occurs on assignment to and from the SQL generated structure. Declaring Host Variables The SQL ILE RPG for AS/400 precompiler only recognizes a subset of valid ILE RPG for AS/400 declarations as valid host variable declarations. then all input and output host variables must contain date values within the range 1940-2039. *YMD. Chapter 16. Using Host Structures The ILE RPG for AS/400 data structure name can be used as a host structure name if subfields exist in the data structure..3. Use the name of the data structure.. SQL treats any referrals to BIGCHR as a character string with a length of 642.4...... The following list of items must be considered when using a data structure with multiple row blocking support....+.. An occurrence data structure can be used on the SQL FETCH or INSERT statement when processing multiple rows. The first FROM position must be 1 and there cannot be overlaps in the TO and FROM positions. C MOVE '000220' EMPNO ... and DEPTNO.. While this support does not provide additional function since a field can be defined with a maximum length of 32766 it is required for compatibility with RPG for AS/400 programs..+. For example. This allows character variables larger than 256..7. The use of the data structure name in an SQL statement implies the list of subfield names making up the data structure.3... *.... LASTNAME..+.. the first column of CORPDATA.1... PEMPL..+.. PEMPL is the name of the host structure consisting of the subfields EMPNO. 314 DB2 UDB for AS/400 SQL Programming V4R4 ......+. v All subfields must be valid host variables.... In the following example. then the data structure name is a host variable of character type.. When subfields are not present for the data structure.. Using Host Structure Arrays A host structure array is defined as an occurrence data structure.. the second column is placed in FIRSTN..EMPLOYEE is placed in EMPNO.. v All subfields must be contiguous....EMPLOYEE C+ WHERE EMPNO = :EMPNO C/END-EXEC When writing an SQL statement... For example....+.......2. followed by a period and the name of the subfield.... The referral to PEMPL uses the subfields..6.. BIGCHR is an ILE RPG for AS/400 data structure without subfields..2...5..MIDINT is the same as specifying only MIDINT.... MIDINT....+.1. FIRSTN.6..+. C/EXEC SQL C+ SELECT * INTO :PEMPL C+ FROM CORPDATA. *.7...+......8 DPEMPL DS D EMPNO 01 06A D FIRSTN 07 18A D MIDINT 19 19A D LASTNA 20 34A D DEPTNO 35 37A ..8 DBIGCHR DS 642 In the next example.+.+.5.....+....4..+.... and so on... referrals to subfields can be qualified.+.. . the occurrence is set to 1... C/EXEC SQL C+ DECLARE C1 FOR C+ SELECT * C+ FROM CORPDATA. then the host structure array is not usable. The following example uses a host structure array called DEPT and a blocked FETCH statement to retrieve 10 rows from the DEPARTMENT table.......5... Coding SQL Statements in ILE RPG for AS/400 Applications 315 . if an occurrence data structure is used.. other than the blocked FETCH and blocked INSERT..........2....6.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.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) ... and TIMSEP parameters on the CRTSQLRPGI command.. C/EXEC SQL C+ FETCH C1 FOR 10 ROWS C+ INTO :DEPARTMENT:IND_ARRAY C/END-EXEC Declaring LOB Host Variables | | | | | | | | | | | | | | | LOB Host Variables BLOB Example The following declaration: D MYBLOB S SQLTYPE(BLOB:500) Results in the generation of the following structure: D MYBLOB D MYBLOB_LEN D MYBLOB_DATA DS 10U 500A CLOB Example The following declaration: D MYCLOB S SQLTYPE(CLOB:1000) Results in the generation of the following structure: D MYCLOB D MYCLOB_LEN D MYCLOB_DATA DS 10U 1000A Chapter 16.7.+.+.... the current occurrence is used.+... TIMFMT....+..DEPARTMENT C/END-EXEC ..3.4...+...1.. For the blocked FETCH and blocked INSERT.+.... DATSEP. For all statements..+... *. The external definition form of the data structure can be used to obtain a copy of the column names to be used as host variables. The pre-compiler will generate declarations for the following file option constants: v SQFRD (2) v SQFCRT (8) v SQFOVR (16) v SQFAPP (32) Using External File Descriptions The SQL precompiler processes the ILE RPG for AS/400 source in much the same manner as the ILE RPG for AS/400 compiler.| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | DBCLOB Example The following declaration: D MYDBCLOB S SQLTYPE(DBCLOB:400) Results in the generation of the following structure: D MYDBCLOB D MYDBCLOB_LEN D MYDBCLOB_DATA DS 10U 400G LOB Locators BLOB Example The following declaration: D MYBLOB S SQLTYPE(BLOB_LOCATOR) Results in the generation of the following structure: D MYBLOB S 10U CLOB and DBCLOB locators have similar syntax. Field definitions for externally described files are obtained and renamed. This means that the precompiler processes the /COPY statement for definitions of host variables. LOB File Reference Variables BLOB Example The following declaration: D MYFILE S SQLTYPE(CLOB_FILE) Results in the generation of the following structure: D D D D D MY_FILE MY_FILE_NL MY_FILE_DL MY_FILE_FO MY_FILE_NAME DS 10U 10U 10U 255A BLOB and DBCLOB locators have similar syntax. if different names are specified. 316 DB2 UDB for AS/400 SQL Programming V4R4 . +.+........8 DDEPARTMENT E DS OCCURS(10) .... In the following example. *CVTDT is a compatibility option for the RPG for AS/400 precompiler.......3......+....1..... the sample table is specified as an external data structure...+...7.....5. the declaration is not used as a host structure array............+. The SQL precompiler retrieves the field (column) definitions as subfields of the data structure... and TIMSEP parameters on the CRTSQLRPGI command.4. A blocked FETCH statement is then used to retrieve 10 rows into the host structure array.6.5.. *. the sample table DEPARTMENT is used as a file in an ILE RPG for AS/400 program......+..2..How date and time field definition are retrieved and processed by the SQL precompiler depends on whether *NOCVTDT or *CVTDT is specified on the OPTION parameter of the CRTSQLRPGI command..1.+..+.+.... Subfield names can be used as host variable names.7....6.3....+..3. the generated host variable will have the UCS-2 CCSID assigned to it...+..+.+..+.4. *.... In the following example. the DEPARTMENT table is included in the ILE RPG for AS/400 program and used to declare a host structure array.... If OPTION(*NOCVTDT) is specified and the date and time format and separator of date and time field definitions within the file are not the same as the DATFMT.... then the host structure array is not usable. The indicator area is included in the structure that is generated and would cause the storage to be separated....... TIMFMT.. The example shows that the field names can be renamed if required by the program. If you use only SQL statements to do I/O operations to the file..5....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.. If *CVTDT is specified... then the format and separator is ignored when date and time field definitions are retrieved.7. Coding SQL Statements in ILE RPG for AS/400 Applications 317 ..DEPARTMENT Chapter 16.....1.. *.4. and the data structure name TDEPT can be used as a host structure name. and the precompiler assumes that the variable declarations are date/time host variables in character format.... The SQL precompiler retrieves the field (column) definitions for DEPARTMENT for use as host variables. if INDARA was not specified and the file contains indicators..+...... If *NOCVTDT is specified.+.+...8 FDEPARTMENTIP E DISK RENAME(ORIGREC:DEPTREC) 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.. then date and time field definitions are retrieved including the format and separator.2...+..+..... DATSEP...... you can include the external definition of the file (table) by using an external data structure..+.. External File Description Considerations for Host Structure Arrays For device files..+. In the following example.... C/EXEC SQL C+ DECLARE C1 CURSOR FOR C+ SELECT * C+ FROM CORPDATA..6.2.. VARYING in columns 44-80 Length ≤ 4 Length = 5 Length ≤ 9 and ≥ 5 Length = 10 Length = 2 Length = 4 Length = n where n is 1 to 16 SQLTYPE of Host Variable 452 SQLLEN of Host Variable n SQL Data Type CHAR(n) n/a Calculation result field (pos 69. 42 p in byte 1. VARYING in columns 44-80. ILE RPG for AS/400 Declarations Mapped to Typical SQL Data Types RPG Data Type Data structure (without subfields) D spec Pos D spec Pos 40 41.s) s=col 41.70 = blank) Definition specification Definition specification Definition specification Definition specification Definition specification Definition specification Definition specification Definition specification Definition specification A n/a 452 n CHAR(n) blank 448 n VARCHAR (n) A blank 456 n VARCHAR (n) B I B I B B P 0 0 0 0 1-4 1-9 0 to 30 500 500 496 496 500 496 484 2 2 4 4 2 4 SMALLINT SMALLINT INTEGER INTEGER DECIMAL(4. C/EXEC SQL C+ FETCH C1 FOR 10 ROWS C+ INTO :DEPARTMENT C/END-EXEC Determining Equivalent SQL and RPG Data Types The precompiler will determine the base SQLTYPE and SQLLEN of host variables according to the following table..C/END-EXEC . length=n where n > 254. 42 DECIMAL(9. 42 4 8 FLOAT (single precision) FLOAT (double precision) Definition specification Definition specification F F blank blank Length = 4 Length = 8 480 480 318 DB2 UDB for AS/400 SQL Programming V4R4 . the SQLTYPE is the base SQLTYPE plus one. s in DECIMAL(p. If a host variable appears with an indicator variable.42 Other RPG Coding blank blank Length = n where n ≤ 32766 Length = n where n ≤ 32766 (pos 59-63) length=n where n is 1 to 254. Table 32.s) s=col 41..s) byte 2 where p = n*2-1 and s = pos 41. 8. 65 p in byte 1. 48 p in byte 1. or 10 (pos 37-46) Length = n where n is 8 Length = n where n is 8 (pos 37-46) Length = n where n is 26 384 n T blank 388 n n/a n/a 388 n Z blank 392 n Chapter 16. s in DECIMAL(p.42 Other RPG Coding blank 0 to 30 Length = n where n is 1 to 16 SQLTYPE of Host Variable 484 SQLLEN of Host Variable SQL Data Type p in byte 1. VARYING in columns 44-80.s) byte 2 where p = n and s = pos 41. 42 p in byte 1.s) byte 2 where p = n and s = pos 47. 42 p in byte 1. VARYING in columns 44-80. Coding SQL Statements in ILE RPG for AS/400 Applications 319 . TIMSEP specified in pos 44-80) TIME (format specified in pos 31-34) TIMESTAMP n/a n/a Length = n where n is 1 to 16 (pos 37-46) 484 Input field (pos 36 = blank or S) Input field (pos 36 = B) n/a n/a Length = n where n is 1 to 30 (pos 37-46) Length = n where n is 2 or 4 (pos 37-46) 484 n/a n/a 484 Calculation n/a result field (pos 69. 8 or 10 464 G blank n G blank 472 n D blank 384 n Input field (pos 36 = D) Definition specification Input field (pos 36 = T) Definition specification n/a n/a Length = n where n is 6. 42 m GRAPHIC(m) where m = n/2 m = (TO-FROM-1)/2 VARGRAPHIC (n) VARGRAPHIC (n) DATE (DATFMT. Length = n where n is 6.s) byte 2 where p = n and s = pos 41.s) byte 2 where p=4 if n=2 or 9 if n=4 s = pos 47. s in NUMERIC(p. DATSEP specified in pos 44-80) DATE (format specified in pos 31-34) TIME (TIMFMT.s) byte 2 where p = n*2-1 and s = pos 41. s in DECIMAL(p.Table 32. s in DECIMAL(p. s in DECIMAL(p.s) byte 2 where p = n and s = pos 64. length=n where n > 127. s in DECIMAL(p. ILE RPG for AS/400 Declarations Mapped to Typical SQL Data Types (continued) RPG Data Type Definition specification not a subfield Input field (pos 36 = P) D spec Pos D spec Pos 40 41. 48 p in byte 1. 48 p in byte 1.70 ≠ blank) Data Structure subfield Definition specification Input field (pos 36 = G) Definition specification Definition specification Definition specification blank n/a Length = n where n is 1 to 30 (pos 59-63) Length = n where n is 1 to 30 Length = n where n is 1 to 30 484 0 to 30 488 S 0 to 30 488 n/a n/a Length = n where n is 468 1 to 32766 (pos 37-46) length=n where n is 1 to 127.s) byte 2 where p = n*2-1 and s = pos 47. s in NUMERIC(p. SQL will create the date/time subfield using the DATE/TIME format specified on the CRTSQLRPGI command. OR Definition specification. B in position 40. 3. B in position 40. In the first column the term ″definition specification″ includes data structure subfields unless explicitly stated otherwise. I in position 40. S in position 40 or blank in position 40 for a subfield. INTEGER Definition specification. then length = TO-FROM+1.42 Other RPG Coding n/a n/a Length = n where n is 26 (pos 37-46) SQLTYPE of Host Variable 392 SQLLEN of Host Variable n SQL Data Type TIMESTAMP Notes: 1. ILE RPG for AS/400 Declarations Mapped to Typical SQL Data Types (continued) RPG Data Type Input field (pos 36 = Z) D spec Pos D spec Pos 40 41. or length = 4 if pos 33-39 > 4. F in position 40. DECIMAL Definition specification. Maximum length of 30 (precision 30) and maximum scale of 30. 2. length must be 10 and 0 in position 42. OR Defined as numeric on non-definition specification. Maximum length of 16 (precision 30) and maximum scale of 30. 0 through 30 in position 41. SQL Data Types Mapped to Typical RPG Declarations SQL Data Type SMALLINT RPG Data Type Definition specification. The following table can be used to determine the RPG data type that is equivalent to a given SQL data type.Table 32. OR Definition specification. 0 through 30 in position 41. then length = 2 if pos 33-39 < 5.42. length must be ≤ 4 and 0 in position 42. 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. v FROM (pos 26-32) is blank. length must be 5 and 0 in position 42. length must be 4. I in position 40. NUMERIC Definition specification.42. Definition specification. P in position 40 or blank in position 40 for a non-subfield. Notes FLOAT (single precision) 320 DB2 UDB for AS/400 SQL Programming V4R4 . Table 33. length must be ≤ 9 and ≥ 5 and 0 in position 42. 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. CHAR(n) VARCHAR(n) Data structure name with no subfields n can be from 1 to 32766. in the data structure. the length must be at least 8. Use SQL TYPE IS to declare a BLOB. TIME A character field OR Definition specification with a T in position 40. Use SQL TYPE IS to declare a DBCLOB. n can be from 1 to 32766. to include seconds. n can be from 1 to 16370. the length must be at least 6. *EUR. length must be 8. Not supported A character field OR Definition specification with a D in position 40. Coding SQL Statements in ILE RPG for AS/400 Applications 321 . or *ISO. F in position 40. OR Calculation result field defined without decimal places. Not supported Not supported Definition specification. OR Input field defined with G in position 36. the length must be at least 10. Notes BLOB CLOB GRAPHIC(n) Chapter 16. If the format is *USA. OR Input field defined without decimal places. or *MDY. VARGRAPHIC(n) DBCLOB DATE Definition specification. n can be 1 to 16383. Length must be at least 6. Use SQL TYPE IS to declare a CLOB. If the format is *YMD. OR Input field defined with T in position 36. SQL Data Types Mapped to Typical RPG Declarations (continued) SQL Data Type FLOAT (double precision) CHAR(n) RPG Data Type Definition specification. *JIS. *DMY. If the format is *JUL.42. Definition specification. position 40 and VARYING in positions 44-80. A or blank in positions 40 and blanks in position 41. Definition specification. length must be at least 8. G in position 40.Table 33. OR Input field defined with D in position 36. G in position 40 and VARYING in positions 44-80. A or blank in n can be from 1 to 32740. ..1. length must be at least 26.... Example Given the statement: *.....+.+.. to include microseconds..+. a negative indicator variable is used to indicate that a null value should be assigned...3. C+ :END :ENDIND C/END-EXEC variables can be declared as follows: *.5. SQL Data Types Mapped to Typical RPG Declarations (continued) SQL Data Type TIMESTAMP RPG Data Type A character field OR Definition specification with a Z in position 40..1....6..... On assignment to a column.. Notes on ILE/RPG 400 Variable Declaration and Usage Assignment rules ILE RPG for AS/400 associates precision and scale with all numeric types..5..+..8 C/EXEC SQL FETCH CLS_CURSOR INTO :CLSCD.+. Indicator variables are declared in the same way as host variables and the declarations of the two can be mixed in any way that seems appropriate to the programmer...... OR Input field defined with Z in position 36.0 and specifying the DIM on the definition specification.........2.... This means that operations involving binary variables include an implicit conversion to packed format before the operation is performed (and back to binary.+.8 D CLSCD S 7 D DAY S 2B 0 322 DB2 UDB for AS/400 SQL Programming V4R4 ..7... If length is less than 26..7...+...+...4...... Using Indicator Variables An indicator variable is a binary field with length less then 5 (2 bytes)..+.2..... C+ :BGN :BGNIND.. assuming the data is in packed format.+. An indicator array can be defined by declaring the variable element length of 4.+.......6.Table 33.. C+ :DAY :DAYIND..... DATALINK Not supported Notes Length must be at least 19. truncation occurs on the microsecond part.... See the DB2 UDB for AS/400 SQL Reference book for more information on the use of indicator variables.. Data is aligned to the implied decimal point when SQL operations are performed.3....+.......4.+.. On retrieval.+. if necessary).. ILE RPG for AS/400 defines numeric operations. an indicator variable is used to show if its associated host variable has been assigned a null value. DIND_ARRAY DS OCCURS(10) D INDS 4B 0 DIM(4) .+...3......5..DEPARTMENT C/END-EXEC ... C/EXEC SQL INCLUDE SQLDA C/END-EXEC DDEPARTMENT DS OCCURS(10) D DEPTNO 01 03A D DEPTNM 04 32A D MGRNO 33 38A D ADMRD 39 41A .... C/EXEC SQL C+ FETCH C1 FOR 10 ROWS C+ USING DESCRIPTOR :SQLDA C+ INTO :DEPARTMENT:IND_ARRAY C/END-EXEC Chapter 16....+.+. C* setup number of sqlda entries and length of the sqlda C eval sqld = 4 C eval sqln = 4 C eval sqldabc = 336 C* C* setup the first entry in the sqlda C* C eval sqltype = 453 C eval sqllen = 3 C eval sql_var(1) = sqlvar C* C* setup the second entry in the sqlda C* C eval sqltype = 453 C eval sqllen = 29 C eval sql_var(2) = sqlvar .. C* C* setup the forth entry in the sqlda C* C eval sqltype = 453 C eval sqllen = 3 C eval sql_var(4) = sqlvar .D D D D D DAYIND BGN BGNIND END ENDIND S S S S S 2B 0 8A 2B 0 8 2B 0 SQLDA Example of the SQLDA for a Multiple Row-Area Fetch *.. Coding SQL Statements in ILE RPG for AS/400 Applications 323 ...+..4.. C/EXEC SQL C+ DECLARE C1 FOR C+ SELECT * C+ FROM CORPDATA...8..........+..+........2..6.7.......1.......+. 324 DB2 UDB for AS/400 SQL Programming V4R4 . . These values are set by the database manager after each SQL statement is executed. Error and warning message tokens. The SQL/REXX interface uses the SQLCA in a manner consistent with the typical SQL usage. An INCLUDE SQLCA statement is not required and is not allowed. the SQL/REXX interface maintains the fields of the SQLCA in separate variables rather than in a contiguous data area. At runtime.USING DESCRIPTOR descriptor-name CALL..Chapter 17.. Using the SQL Communications Area The fields that make up the SQL Communications Area (SQLCA) are automatically included by the SQL/REXX interface. Eleven variables (n is a number between 0 and 10) containing warning flags. 1999 325 . and an SQLDA can have any valid name.USING DESCRIPTOR descriptor-name DESCRIBE statement-name INTO descriptor-name DESCRIBE TABLE host-variable INTO descriptor-name Unlike the SQLCA.. Product code and. the REXX interpreter passes statements that it does not understand to the current active command environment for processing. The command environment can be changed to *EXECSQL to send all unknown statements to the database manager in two ways: 1. 1997.. CMDENV parameter on the STRREXPRC CL command 2. Each SQLDA consists of a set of REXX variables with a common stem. Coding SQL Statements in REXX Applications REXX procedures do not have to be preprocessed. The variables that the SQL/REXX interface maintains for the SQLCA are defined as follows: SQLCODE SQLERRMC SQLERRP SQLERRD.USING DESCRIPTOR descriptor-name OPEN. Six variables (n is a number between 1 and 6) containing diagnostic information. where the name of the stem is the descriptor-name from the © Copyright IBM Corp.USING DESCRIPTOR descriptor-name FETCH. An application can check the SQLCODE or SQLSTATE value to determine whether the last SQL statement was successful. The SQLCODE and SQLSTATE fields of the SQLCA contain SQL return codes.. address positional parameter on the ADDRESS REXX command For more information on the STRREXPRC CL command or the ADDRESS REXX command. more than one SQLDA can be in a procedure. the name of the module that returned the error.n SQLSTATE The primary SQL return code.n SQLWARN... The alternate SQL return code. if there is an error. However. Using SQL Descriptor Areas The following statements require an SQLDA: EXECUTE. see the REXX/400 Programmer’s Guide book. SQLLEN If SQLTYPE does not indicate a DECIMAL or NUMERIC data type. The following data types are not allowed: 400/401 404/405 408/409 412/413 460/461 476/477 496/497 500/501 504/505 916/917 920/921 924/925 960/961 964/965 968/969 NUL-terminated graphic string BLOB host variable CLOB host variable DBCLOB host variable NUL-terminated character string PASCAL L-string Large integer (where scale is greater than 0) Small integer (where scale is greater than 0) DISPLAY SIGN LEADING SEPARATE BLOB file reference variables CLOB file reference variables DBCLOB file reference variables BLOB locator CLOB locator DBCLOB locator stem. or a PREPARE INTO statement: stem. an OPEN. See the DB2 UDB for AS/400 SQL Reference book for more information on the SQLDA. the first element is in stem..USING DESCRIPTOR.n.SQLDATA.n. 326 DB2 UDB for AS/400 SQL Programming V4R4 . An INCLUDE SQLDA statement is not required and is not allowed. However.. or a PREPARE INTO statement: stem. a CALL.. The following variables must be provided by the application before an EXECUTE.USING DESCRIPTOR statement.. stem.SQLTYPE An integer representing the data type of the nth element (for example... that is.SQLTYPE). The following variables are returned to the application after a DESCRIBE. The SQL/REXX interface uses the SQLDA in a manner consistent with the typical SQL usage.1.SQLD Number of variable elements that the SQLDA actually contains.SQLNAME The name of the nth column in the result table. The SQL/REXX interface automatically provides the fields of the SQLDA for each unique descriptor name.USING DESCRIPTOR.. the SQL/REXX interface maintains the fields of the SQLDA in separate variables rather than in a contiguous data area. the stem itself must not contain any periods. the maximum length of the data contained in stem.. or a FETCH. They are returned to the application after a DESCRIBE. a DESCRIBE TABLE. This must be a simple stem. a DESCRIBE TABLE.n.n.appropriate SQL statements.USING DESCRIPTOR. For example: EXECSQL “COMMIT” is equivalent to: rexxvar = “COMMIT” EXECSQL rexxvar The command follows normal REXX rules. Coding SQL Statements in REXX Applications 327 .SQLCCSID The CCSID of the nth column of the data. this contains the scale of the number. Each SQL statement in a REXX procedure must begin with EXECSQL (in any combination of uppercase and lowercase letters).. REXX also permits command names to be included within single quotes. or v A REXX variable containing the statement. this contains the precision of the number. this is a negative number.USING DESCRIPTOR statement. and SQLSCALE.SQLLEN. Note that a colon must not precede a REXX variable when it contains an SQL statement.USING DESCRIPTOR or an OPEN..n. followed by either: v The SQL statement enclosed in single or double quotes. SQLPRECISION.SQLSCALE If the type is DECIMAL or NUMERIC..n. or the output value fetched by SQL.SQLLEN. it can optionally be followed by a semicolon (. and they are returned to the application after a FETCH. stem.. For example.n. stem.SQLPRECISION If the data type is DECIMAL or NUMERIC.) to allow a single line to contain more than one REXX statement.n. stem. or a PREPARE INTO statement: stem. for example: 'EXECSQL COMMIT' Chapter 17. SQLLEN. Embedding SQL Statements An SQL statement can be placed anywhere a REXX command can be placed.SQLIND If the input or output value is null.USING DESCRIPTOR statement.. They are not used after a DESCRIBE. The following variables must be provided by the application before an EXECUTE.n. This value is converted to the attributes specified in SQLTYPE.SQLDATA This contains the input value supplied by the application.stem.. a DESCRIBE TABLE. Continuation of SQL Statements The string containing an SQL statement can be split into several strings on several lines. Including Code Unlike the other host languages. 11. they must be the object of a PREPARE and then an EXECUTE. See the DB2 UDB for AS/400 SQL Reference book for more information on the SET OPTION statement. 12. These statements cannot be executed directly if they contain host variables. support is not provided for including externally defined statements. 10 LABEL ON LOCK TABLE OPEN PREPARE RENAME REVOKE ROLLBACK SET OPTION 11 SET PATH SET TRANSACTION SET variable 10 UPDATE 10 VALUES INTO 10 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 END DECLARE SECTION FREE LOCATOR INCLUDE RELEASE SELECT INTO SET CONNECTION SET RESULT SETS WHENEVER12 Comments Neither SQL comments (--) nor REXX comments are allowed in strings representing SQL statements.The SQL/REXX interface supports the following SQL statements: ALTER TABLE CALL 10 CLOSE COMMENT ON COMMIT CREATE ALIAS CREATE COLLECTION CREATE DISTINCT TYPE CREATE FUNCTION CREATE INDEX CREATE PROCEDURE CREATE TABLE CREATE VIEW DECLARE CURSOR 10 DELETE 10 DESCRIBE DESCRIBE TABLE DROP EXECUTE EXECUTE IMMEDIATE FETCH 9 GRANT INSERT 9. 10. according to standard REXX usage. The SET OPTION statement can be used in a REXX procedure to change some of the processing options used for running SQL statements. separated by commas or concatenation operators. 9. The blocked form of this statement is not supported. See “Handling Errors and Warnings” on page 329 for more information. These options include the commitment control level and date format. 328 DB2 UDB for AS/400 SQL Programming V4R4 . Using Host Variables | | | | REXX does not provide for variable declarations. Any of the following may be used instead: v A test of the REXX SQLCODE or SQLSTATE variables after each SQL statement to detect error and warning conditions issued by the database manager. Names Any valid REXX name not ending in a period (. but not warnings. Variable names should not begin with the characters 'SQL'. 'DSN'. and the BEGIN DECLARE SECTION and END DECLARE SECTION statements are not supported. New variables are recognized by their appearance in assignment statements. 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. Each use of the EXECSQL command sets the RC variable to: 0 +10 -10 -100 Statement completed successfully. or 'QRW'. 'RDI'. but not for those issued by the SQL/REXX interface. Chapter 17.) can be used for a host variable. An SQL error occurred An SQL/REXX interface error occurred.Margins There are no special margin rules for the SQL/REXX interface. v A test of the REXX RC variable after each SQL statement to detect error and warning conditions. Coding SQL Statements in REXX Applications 329 . LOB host variables are not supported in REXX. 'RXSQL'. A SQL warning occurred. Handling Errors and Warnings The WHENEVER statement is not supported by the SQL/REXX interface. the term has different meanings in the two languages. there is no declare section. v The SIGNAL ON ERROR and SIGNAL ON FAILURE facilities can be used to detect errors (negative RC values). REXX has a null string (a string of length zero) and a null clause (a clause consisting only of blanks and comments). Nulls Although the term null is used in both REXX and SQL. The name must be 64 characters or less. Therefore. Statement Labels REXX command statements can be labeled as usual. This can be used to detect errors and warnings issued by either the database manager or by the SQL/REXX interface. or to a date. A graphic value can be used as input to a graphic column of any type. which has length n after removing the two delimiters. Determining Data Types of Host Variables in REXX Host Variable Contents Undefined Variable Assumed Data Type Variable for which a value has not been assigned Varying-length character string SQL Type Code None SQL Type Description Data that is not valid was detected.b' causes the contents of x. The data type of input host variables (that is. which cannot be recognized as character. Each remaining pair of characters is the hexadecimal representation of a single character.All host variables within an SQL statement must be preceded by a colon (:). VARCHAR(n) A string with leading and trailing apostrophes (’) or quotation marks (″). or graphic through other rules in this table 448/449 330 DB2 UDB for AS/400 SQL Programming V4R4 . For example: a = 1 b = 2 EXECSQL 'OPEN c1 USING :x. or a string with a leading X or x followed by an apostrophe (’) or quotation mark (″).2 to be passed to SQL. and a trailing apostrophe (’) or quotation mark (″).a. or graphic values.1. Table 34. The string has a length of 2n after removing the X or x and the two delimiters. These rules define either numeric. character. host variables used in a 'USING host variable' clause in an EXECUTE or OPEN statement) is inferred by the database manager at run time from the contents of the variable according to Table 34. Determining Data Types of Input Host Variables All data in REXX is in the form of strings. numeric. or timestamp column. time. The SQL/REXX interface performs substitution in compound variables before passing statements to the database manager. A character value can be used as input to a character column of any type. A numeric value can be used as input to a numeric column of any type. or a string of length n. followed by an apostrophe or quote and a shift-out (x’0E’). A number with neither decimal point nor exponent. The string has a length of 4n after removing the GX and the delimiters. N or n. This is followed by an apostrophe or quote and a shift-out (x’0E’). The string must end with a shift-in (X’0F’) and an apostrophe or quote (whichever the string started with). g. It can have a leading plus or minus sign. Negative values have a leading minus sign. Output values are assigned to host variables as follows: v Character values are assigned without leading and trailing apostrophes. A number that includes a decimal point. Gx. This is followed by n graphic characters. v Graphic values are assigned without a leading G or apostrophe. or a number that does not include a decimal point or an exponent and is greater than 2147483647 or smaller than -2147483647. without a trailing apostrophe. The byte immediately following the leading apostrophe is a X'0E' shift-out. and without shift-out and shift-in characters. v Integer values do not retain any leading zeros. Positive values do not have a leading plus sign. A number that is in scientific or engineering notation (that is. It can Signed integers have a leading plus or minus sign. v Numeric values are translated into strings. 496/497 INTEGER Floating point 480/481 FLOAT Assumed Data Type SQL Type Code SQL Type Description VARGRAPHIC(n) Varying-length graphic string 464/465 Packed decimal 484/485 DECIMAL(m. It can have a leading plus or minus sign. The string must end with a shift-in (X’0F’) and an apostrophe or quote (whichever the string started with). Chapter 17. v A string with a leading GX. Determining Data Types of Host Variables in REXX (continued) Host Variable Contents A string with a leading and trailing apostrophe (’) or quotation marks (″) preceded by: 13 v A string that starts with a G. each 2 characters long.Table 34. m is the total number of digits in the number. v Decimal values retain leading and trailing zeros according to their precision and scale. and the byte immediately preceding the trailing apostrophe is a X'0F' shift-in. 13. n is the number of digits to the left of the decimal point (if any). Negative values have a leading minus sign. or gx. a host variable used in an 'INTO host variable' clause in a FETCH statement). but no exponent. an optional plus or minus sign. and a series of digits). each 2 characters long. followed immediately by an 'E' or 'e'. This is followed by n graphic characters. Coding SQL Statements in REXX Applications 331 . gX. Each remaining group of 4 characters is the hexadecimal representation of a single graphic character.n) The Format of Output Host Variables It is not necessary to determine the data type of an output host variable (that is. and it is passed to SQL as such. with one digit to the left of the decimal place. On the other hand.v Floating-point values are in scientific notation. This is evaluated by the SQL/REXX interface as the string 100. Using Indicator Variables An indicator variable is an integer. an indicator variable is used to show if its associated host variable was assigned a null value. stringvar = “'“100”'” causes REXX to set the variable stringvar to the string of characters '100' (with the apostrophes). On retrieval. a valid value must be specified in the host variable even if its associated indicator variable contains a negative value. The 'E' is in uppercase. and it is passed to SQL as such. Avoiding REXX Conversion To guarantee that a string is not converted to a number or assumed to be of graphic type. strings should be enclosed in the following: "'". On assignment to a column. Unlike other languages. Simply enclosing the string in apostrophes does not work. 332 DB2 UDB for AS/400 SQL Programming V4R4 . a negative indicator variable is used to indicate that a null value should be assigned. For more information on indicator variables see the DB2 UDB for AS/400 SQL Reference book. For example: stringvar = '100' 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. The SQL precompiler scans each statement of the application program source and does the following: v Looks for SQL statements and for the definition of host variable names. The variable names and definitions are used to verify the SQL statements. For more information on any SQL statement. the validation is done at run time. The validation procedure supplies error messages in the output listing that help you correct any errors that occur. 2. the SQL statements are checked for valid table. When the RDB parameter is specified on the CRTSQLxxx commands. v Verifies that each SQL statement is valid and free of syntax errors. v Prepares each SQL statement for compilation in the host language. The tasks described are: v Precompiling v Compiling v Binding v Running Basic Processes of the SQL Precompiler You must precompile and compile an application program containing embedded SQL statements before you can run it. and column names. The actual authority required to process any SQL statement is checked at run time. 1999 333 . 3. 14 Precompiling of such programs is done by the SQL precompiler. an error occurs. SQL statements in a REXX procedure are not precompiled and compiled. © Copyright IBM Corp. Preparing and Running a Program with SQL Statements This chapter describes some of the tasks for preparing and running an application program. If a specified table or view does not exist. For most SQL statements. or you are not authorized to the table or view at the time of the precompile or compile. see the DB2 UDB for AS/400 Database Programming book. and the Data Management book. Overrides are processed when retrieving external definitions. For more information.Chapter 18. Notes: 1. You need some authority (at least *OBJOPR) to any tables or views referred to in the SQL statements in order to validate the SQL statements. the SQL precompiler inserts a comment and a CALL statement to one of the SQL interface modules: – QSQROUTE – QSQLOPEN – QSQLCLSE 14. You can examine the listing after the SQL precompiler completes processing to see if any errors occurred. v Validates the SQL statements using the description in the database. If the table or view does not exist at run time. view. 1997. see the DB2 UDB for AS/400 SQL Reference book. the precompiler accesses the specified relational database to obtain the table and view descriptions. During the precompile. and C++ programs. the precompiler may not correctly identify SQL statements and host variable declarations. However. See the DB2 UDB for AS/400 SQL Reference book for the SET OPTION syntax. the source file must be a mixed CCSID. CI for the ILE C for AS/400 language. PLI. If the host language statements are not syntactically correct. If mixed DBCS constants are specified in the application program source. DECLARE statements). The included member may not contain other precompiler INCLUDE statements. The information is stored internally in a temporary source file member. The xxx in this command refers to the host language indicators: CBL for the COBOL for AS/400 language. When processing SQL INCLUDE statements. There are limits on the forms of source statements that can be passed through the precompiler. CPPI. PLI for the AS/400 PL/I language. and CVTSQLCPP commands. 334 DB2 UDB for AS/400 SQL Programming V4R4 . the SQL precompiler produces no host language statement except a comment. specify either of the following: v OPTION(*SOURCE *XREF) for CRTSQLxxx (where xxx=CBL. To get complete diagnostic information when you precompile. The SQL precompiler assumes that the host language statements are syntactically correct. Source File CCSIDs The SQL precompiler will read the source records by using the CCSID of the source file. CBLI. the include source will be 15. the SQL statements must use the margins that are specified in the MARGINS parameter of the CRTSQLPLI. but can contain both application program and SQL statements. where it is available for use during the bind process. any preprocessor run before the SQL precompile must be able to pass through SQL statements. CRTSQLCPPI. 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 specify many of the precompiler options in the input source member by using the SQL SET OPTION statement. RPGI for the ILE RPG for AS/400 language. CRTSQLCI. The SQL INCLUDE statement causes input to be read from the specified member until it reaches the end of the member. CBLI for the ILE COBOL for AS/400 language. CPPI for the ILE C++/400 language. Another preprocessor may process source statements before the SQL precompiler. C.– QSQLCMIT For some SQL statements (for example. v Produces information about each precompiled SQL statement. or RPGI) or for CVTSQLCPP Input to the Precompiler Application programming statements and embedded SQL statements are the primary input to the SQL precompiler. You can use the SQL INCLUDE statement to get secondary input from the file that is specified by the INCFILE parameter of the CRTSQLxxx 15 and CVTSQLCPP command. RPG for the RPG for AS/400 language. or RPG) v OPTION(*XREF) OUTPUT(*PRINT) for CRTSQLxxx (where xxx=CI. In PL/I. When SQL creates the output source file. SQL expects the not sign (¬) to be located at 'BA'X. The SQL precompiler will process SQL statements using the source CCSID.1. If the source file CCSID is 65535. v Precompiler diagnostics This output supplies diagnostic messages. The data will not be converted when it is written to the printer file. SQL statements have been converted to comments and calls to the SQL runtime. the file can be moved to a permanent library after the precompile if you want to compile at a later time. Output from the Precompiler The following sections describe the various kinds of output supplied by the precompiler. If the include source cannot be converted to the CCSID of the original source file. 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. it uses the CCSID value of the source file as the CCSID value for the new file. 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. v Precompiler cross-reference If *XREF was specified in the OPTION parameter. Preparing and Running a Program with SQL Statements 335 . SQL looked for the not sign (¬) in the location '5F'X in CCSID 37. Listing The output listing is sent to the printer file that is specified by the PRTFILE parameter of the CRTSQLxxx or CVTSQLCPP command.converted to the CCSID of the original source file if necessary. Temporary Source File Members 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 listing shows the precompiler record numbers of SQL statements that contain the referred to host names and column names. This member cannot be changed before being used as input to the compiler. the not sign (¬) is located at 'BA'X in CCSID 500. this output supplies a cross-reference listing. Chapter 18. The default file is QSQLTEMP (QSQLTEMP1 for ILE RPG for AS/400) in the QTEMP library. The output to the printer file will use a CCSID value of 65535. For example. This means that if the CCSID of your source file is 500. or the attempted compile fails. You cannot change the records of the source member. an error will occur. In your precompiler-changed source code. If the precompile uses QSQLTEMP or QSQLTEMP1 in QTEMP. This affects variant characters the most. if the listing option is in effect. showing the precompiler record numbers of statements in error. SQL processes variant characters as if they had a CCSID of 37. Prior to Version 2 Release 1. This means that SQL looks for the not sign (¬) at '5F'X. ...*NONE Package name..... it can be reused on later precompiles... Once it has been created by SQL........... The date the source member was last changed..*ENDPGM Allow blocking.10 Printer file.......*NO Generation level........................... specify OPTION(*XREF) and OUTPUT(*PRINT) on the CRTSQLxxx or CVTSQLCPP command...*USER User Profile........ If the defaults for this command have changed.........................The SQL precompiler uses the CRTSRCPF command to create the output source file............... then the results may be unpredictable............. It is recommended that the user allow SQL to create the output source file....*JOB IBM SQL flagging.....*YES Close SQL cursor.................QTEMP/QSQLTEMP 1 Options.*LIBL/*SRCFILE Commit..........COBOL Program name....CORPDATA/SRC Member...........*NAMING Sort Sequence.*JOB Time format....*LOCAL User ...............*READ Delay PREPARE....65535 2 Source member changed on 04/01/98 10:16:44 CBLTEST1 04/01/98 11:14:21 Page 1 1 2 A list of the options you specified when the SQL precompiler was called.......... Sample Precompiler Output The precompiler output can provide information about your program source...CORPDATA/CBLTEST1 Source file........................ the file’s attributes may be different as well......*CURRENT RDB connect method.......*DUW Default Collection........................... specify the *SOURCE (*SRC) and *XREF options on the OPTION parameter of the CRTSQLxxx command.....*LIBL/QSYSPRT Date format... The format of the precompiler output is: 5769ST1 V4R4M0 990521 Create SQL COBOL Program Source type... If the source file is created by the user..........*JOB Replace.................65535 Job CCSID...............*JOB Date separator............*HMS Time separator .......*PGMLIB/*PGM Dynamic User Profile.........V4R4M0 INCLUDE file.*SRC *XREF *SQL Target release.......*JOB Language ID..... v For ILE precompilers.......... To generate the listing: v For non-ILE precompilers..........*YES Relational database.................CBLTEST1 To source file....... Sample COBOL Precompiler Output Format (Part 1 of 5) 336 DB2 UDB for AS/400 SQL Programming V4R4 ......*NOFLAG ANS flagging............... not the SQL precompiler...........*NONE Text...*CHG Allow copy of data....*SRCMBRTXT Source file CCSID... Figure 11.................... . EXEC SQL INCLUDE SQLCA END-EXEC. *************************************************************** * Open cursor * *************************************************************** EXEC SQL OPEN CURS END-EXEC.. *************************************************************** * Set-up WHENEVER statement to handle SQL errors.. 05 CC PIC X. WORKING-STORAGE SECTION. 4 ...99. 05 AVG-EDUC PIC S9(4) USAGE COMP-4. Preparing and Running a Program with SQL Statements 337 . AVG(EDLEVEL). CONFIGURATION SECTION.. * *************************************************************** EXEC SQL WHENEVER SQLERROR GO TO B000-SQL-ERROR END-EXEC. Date when the source record was last changed. *************************************************************** * This program will get the average education level and the * * average salary by department. Sequence number taken from the source record. 8 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 IDENTIFICATION DIVISION.. 77 FSTAT PIC XX. 05 DEPT-NO PIC X(3). * *************************************************************** A000-MAIN-PROCEDURE. 05 WORKDEPT PIC X(3). The sequence number is the number seen when you use the source entry utility (SEU) to edit the source member. IBM-AS400.. CBLTEST1.+. 05 AVG-SALARY PIC S9(6)V99 COMP-3.. INPUT-OUTPUT SECTION. 05 CC PIC X. SOURCE-COMPUTER. 05 FILLER PIC X(5). 3 .+. FILE SECTION. FD OUTFILE DATA RECORD IS REC-1. PROCEDURE DIVISION.. 05 FILLER PIC X(5). ENVIRONMENT DIVISION.. PROGRAM-ID... *************************************************************** * Declare cursor * *************************************************************** EXEC SQL DECLARE CURS CURSOR FOR SELECT WORKDEPT.. If Last is blank. OPEN OUTPUT OUTFILE. 6 ...+.+.+. 05 ERROR-MESSAGE PIC X(70). 05 AVERAGE-EDUCATION-LEVEL PIC ZZZ. IBM-AS400. LABEL RECORDS ARE OMITTED. SELECT OUTFILE. ASSIGN TO PRINTER-QPRINT. Sample COBOL Precompiler Output Format (Part 2 of 5) Chapter 18. DATA DIVISION.. 5 .... OBJECT-COMPUTER. 2 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 04/01/98 11:14:21 SEQNBR 3 Last Change Page 2 1 2 3 Record number assigned by the precompiler when it reads the source record.5769ST1 V4R4M0 990521 Create SQL COBOL Program CBLTEST1 1 Record *. 05 ERROR-CODE PIC S9(5)..+. 05 AVERAGE-SALARY PIC ZZZZ9. Figure 11. 01 REC-1.... 1 . 01 AVG-RECORD.. AVG(SALARY) FROM CORPDATA.+. 7 .EMPLOYEE GROUP BY WORKDEPT END-EXEC. FILE-CONTROL. it indicates that the record has not been changed since it was created.+... Record numbers are used to identify the source record in error messages and SQL run-time processing.. 01 ERROR-RECORD. 2 .... FILE STATUS IS FSTAT.. 76 STOP RUN...+..5769ST1 V4R4M0 990521 Create SQL COBOL Program CBLTEST1 Record *. 75 CLOSE OUTFILE. 4 .. 82 EXEC SQL 83 FETCH CURS INTO :AVG-RECORD 84 END-EXEC.+......+... 100 WRITE ERROR-RECORD AFTER ADVANCING 1 LINE..+. 5 .. 8 64 *************************************************************** 65 * Fetch all result rows * 66 *************************************************************** 67 PERFORM A010-FETCH-PROCEDURE THROUGH A010-FETCH-EXIT 68 UNTIL SQLCODE IS = 100. 7 . 6 ... 3 . 81 MOVE SPACES TO REC-1. 101 CLOSE OUTFILE. * * * * * E N D O F S O U R C E * * * * * 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 3 Figure 11.. 77 *************************************************************** 78 * Fetch a row and move the information to the output record. 98 MOVE SQLCODE TO ERROR-CODE. 91 EXIT.. * 79 *************************************************************** 80 A010-FETCH-PROCEDURE.....+. 102 STOP RUN.. Move the error number to the error * 94 * record and stop running...+.. 90 A010-FETCH-EXIT. 69 *************************************************************** 70 * Close cursor * 71 *************************************************************** 72 EXEC SQL 73 CLOSE CURS 74 END-EXEC.+.+. 97 MOVE SPACES TO ERROR-RECORD. 99 MOVE "AN SQL ERROR HAS OCCURRED" TO ERROR-MESSAGE.. * 95 *************************************************************** 96 B000-SQL-ERROR.... 85 IF SQLCODE IS = 0 86 MOVE WORKDEPT TO DEPT-NO 87 MOVE AVG-SALARY TO AVERAGE-SALARY 88 MOVE AVG-EDUC TO AVERAGE-EDUCATION-LEVEL 89 WRITE REC-1 AFTER ADVANCING 1 LINE. 2 . 92 *************************************************************** 93 * An SQL error occurred... Sample COBOL Precompiler Output Format (Part 3 of 5) 338 DB2 UDB for AS/400 SQL Programming V4R4 . 1 .. 0) IN AVG-RECORD STRUCTURE 83 DECIMAL(8. The line number is generated by the SQL precompiler.2) COLUMN IN CORPDATA.EMPLOYEE NUMERIC(5.2) IN AVG-RECORD DATE(10) COLUMN IN CORPDATA.EMPLOYEE 4 COLLECTION 5 55 CURSOR 62 73 83 CHARACTER(3) IN REC-1 COLUMN 54 6 SMALL INTEGER PRECISION(4. Preparing and Running a Program with SQL Statements 339 .EMPLOYEE CHARACTER(3) IN AVG-RECORD COLUMN 54 56 CHARACTER(3) COLUMN IN CORPDATA.2) COLUMN IN CORPDATA.EMPLOYEE CHARACTER(2) DATE(10) COLUMN IN CORPDATA. The reference column contains two types of information: v What the symbolic name is defined as 4 v The line numbers where the symbolic name occurs 5 If the symbolic name refers to a valid host variable.EMPLOYEE 1 2 Data names are the symbolic names used in source statements.EMPLOYEE * * * * * Figure 11. **** means that the object was not defined or the precompiler did not recognize the declarations.EMPLOYEE TABLE IN CORPDATA 7 55 CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA. 3 Figure 11.EMPLOYEE CHARACTER(4) COLUMN IN CORPDATA.EMPLOYEE COLUMN 54 DECIMAL(9.2) COLUMN IN CORPDATA. The define column specifies the line number at which the name is defined.0) IN ERROR-RECORD CHARACTER(70) IN ERROR-RECORD STRUCTURE VARCHAR(12) COLUMN (NOT NULL) IN CORPDATA.0) COLUMN (NOT NULL) IN CORPDATA. the data-type 6 or data-structure 7 is also noted.EMPLOYEE VARCHAR(15) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE CHARACTER(1) COLUMN (NOT NULL) IN CORPDATA. Sample COBOL Precompiler Output Format (Part 5 of 5) Chapter 18. Sample COBOL Precompiler Output Format (Part 4 of 5) 5769ST1 V4R4M0 990521 CROSS REFERENCE SEX WORKDEPT WORKDEPT Create SQL COBOL Program 55 33 **** CBLTEST1 04/01/98 11:14:21 Page 5 WORKDEPT 55 No errors found in source 102 Source records processed * * * * * E N D O F L I S T I N G CHARACTER(1) COLUMN IN CORPDATA.EMPLOYEE LABEL 47 CHARACTER(1) IN REC-1 CHARACTER(1) IN ERROR-RECORD DECIMAL(9.EMPLOYEE DECIMAL(9.EMPLOYEE CHARACTER(8) COLUMN IN CORPDATA.5769ST1 V4R4M0 990521 CROSS REFERENCE 1 Data Names AVERAGE-EDUCATION-LEVEL AVERAGE-SALARY AVG-EDUC AVG-RECORD AVG-SALARY BIRTHDATE BONUS B000-SQL-ERROR CC CC COMM CORPDATA CURS DEPT-NO EDLEVEL EDLEVEL EMPLOYEE EMPNO ERROR-CODE ERROR-MESSAGE ERROR-RECORD FIRSTNME FSTAT HIREDATE JOB LASTNAME MIDINIT PHONENO REC-1 SALARY SALARY Create SQL COBOL Program 2 Define 20 22 34 32 35 55 55 **** 17 24 55 **** 53 18 **** 55 **** 55 25 26 23 55 31 55 55 55 55 55 16 **** 55 CBLTEST1 04/01/98 11:14:21 Page 4 3 Reference IN REC-1 IN REC-1 SMALL INTEGER PRECISION(4. if USRPRF(*USER) or system naming (*SYS) with USRPRF(*NAMING) is specified. Using the object name in the CRTSQLxxx command as the member name. The CRTxxxPGM command is run specifying the program name.Non-ILE Precompiler Commands DB2 UDB Query Manager and SQL Development Kit includes non-ILE precompiler commands for the following host languages: CRTSQLCBL (for COBOL for AS/400). Refer to “Appendix D. Within these languages. the MARGINS are set in the temporary source file. the following parameters are passed: v For COBOL. SAAFLAG (*FLAG) is passed on the CRTxxxPGM command. v For PL/I. the *QUOTE or *APOST is passed on the CRTCBLPGM command. the REPLACE parameter value from the CRTSQLxxx command is specified on the CRTSQLPKG command. If the precompile and compile were done as separate steps. The program can be saved or restored to the level specified on the TGTRLS parameter of the CRTSQLPLI command. If a package is created as part of the precompile process. the SRTSEQ and LANGID parameter from the CRTSQLxxx command is specified on the CRTxxxPGM command. the precompiler created the source member in the output source file (specified as the TOSRCFILE parameter on the CRTSQLxxx command). CRTSQLPLI (for AS/400 PL/I). v For COBOL and RPG. You now can explicitly call the host language compilers. and change the defaults. v For all languages. and USRPRF. which is part of RPG for AS/400). If USRPRF(*OWNER) or SQL naming (*SQL) with USRPRF(*NAMING) is specified. Defaults are used for all other parameters with CRTxxxPGM commands. the TGTRLS parameter value from the CRTSQLxxx command is specified on the CRTxxxPGM command. precompiler created source member name. Some options only apply to certain languages. 340 DB2 UDB for AS/400 SQL Programming V4R4 . v For RPG and COBOL. They are not included in the commands for the other languages. For example. v For all languages. text. v For RPG and COBOL. then USRPRF(*USER) is specified on the CRTxxxPGM command. Compiling a Non-ILE Application Program The SQL precompiler automatically calls the host language compiler after the successful completion of a precompile. v For RPG and COBOL. unless *NOGEN is specified. and CRTSQLRPG (for RPG III. the options *APOST and *QUOTE are unique to COBOL. the CRTSQLPKG command can be used to create the SQL package for a distributed program. source file name. the CVTOPT (*DATETIME *VARCHAR) is always specified on the CRTxxxPGM command. the REPLACE parameter from the CRTSQLxxx command is specified on the CRTxxxPGM command. TGTRLS is not specified on the CRTPLIPGM command. *NOGEN specifies that the host language compiler will not be called. then USRPRF(*OWNER) is specified on the CRTxxxPGM command. You can interrupt the call to the host language compiler by specifying *NOGEN on the OPTION parameter of the precompiler command. specify the source member in the output source file. DB2 UDB for AS/400 CL Command Descriptions” on page 645 for more information. CRTSQLRPGI. the following ILE precompiler commands exist: CRTSQLCI.Note: You must not change the source member in QTEMP/QSQLTEMP prior to issuing the CRTxxxPGM command or the compile will fail. v If OBJTYPE is either *PGM or *SRVPGM. and USRPRF(*USER) or system naming (*SYS) with USRPRF(*NAMING) is specified. by language. let you specify the required parameters and take the default for the remaining parameters. and USRPRF(*OWNER) or SQL naming (*SQL) with USRPRF(*NAMING) is specified. v For C and C++. the following parameters are passed: v If DBGVIEW(*SOURCE) is specified on the CRTSQLxxx command. and CRTSRVPGM commands. the SQL precompiler issues the CRTBNDxxx command to create the program. v If OUTPUT(*PRINT) is specified on the CRTSQLxxx command. v The TGTRLS parameter value from the CRTSQLxxx command is specified on the CRTxxxMOD. the SQL precompiler issues the CRTxxxMOD command to create the module. CRTBNDxxx. the MARGINS are set in the temporary source file. If a package is created as part of the precompile process. v The REPLACE parameter value from the CRTSQLxxx command is specified on the CRTxxxMOD. Refer to “Appendix D. For example. DB2 UDB for AS/400 CL Command Descriptions” on page 645 for more information. They are not included in the commands for the other languages. CRTBNDxxx. CRTSQLCBLI. the options *APOST and *QUOTE are unique to COBOL. If OBJTYPE is either *PGM or *SRVPGM. Chapter 18. ILE Precompiler Commands In the DB2 UDB Query Manager and SQL Development Kit. The defaults are applicable only to the language you are using. The CRTSQLCPPI command only create *MODULE objects. unless *NOGEN is specified. then DBGVIEW(*ALL) is specified on both the CRTxxxMOD and CRTBNDxxx commands. If the *MODULE option is specified. it is passed on both the CRTxxxMOD and CRTBNDxxx commands. and Create Service Program (CRTSRVPGM) commands. ILE COBOL for AS/400. Preparing and Running a Program with SQL Statements 341 . and ILE RPG for AS/400. and CVTSQLCPP. If the *SRVPGM option is specified. CRTSQLCPPI. USRPRF(*OWNER) is specified on the CRTBNDxxx or the CRTSRVPGM commands. followed by the Create Service Program (CRTSRVPGM) command to create the service program. Within these languages. USRPRF(*USER) is specified on the CRTBNDxxx or the CRTSRVPGM commands. The CVTSQLCPP never creates an object. If the *PGM option is specified. the REPLACE parameter value from the CRTSQLxxx command is specified on the CRTSQLPKG command. There is a precompiler command for each of the host languages: ILE C for AS/400. Separate commands. If OUTPUT(*NONE) is specified on the CRTSQLxxx command. Compiling an ILE Application Program The SQL precompiler automatically calls the host language compiler after the successful completion of a precompile for the CRTSQLxxx commands. the SQL precompiler issues the CRTxxxMOD command to create the module. it is not specified on either the CRTxxxMOD command or the CRTBNDxxx command. then CVTOPT(*DATETIME) is specified on the CRTRPGMOD and CRTBNDRPG commands. If the program or service program is created later. the precompiler creates the source member in the output source file (TOSRCFILE parameter).mbr in Client Access. v FOR RPG and COBOL. the SRTSEQ and LANGID parameter from the CRTSQLxxx command is specified on the CRTxxxMOD and CRTBNDxxx commands. or Create Service Program (CRTSRVPGM) command. Using the specified program name in the CRTSQLxxx command as the member name.mbr directory. *NOGEN specifies that the host language compiler is not called. and change the defaults. Make sure both the base and option one are loaded for the product. The precompile and compile should be done following these steps: 1. 2. In this discussion. the CRTSQLPKG command can be used to create the SQL package for a distributed program. it is assumed that the x drive is mapped to the AS/400 system. issue the following command: CTTCRSQX myapp. You can now explicitly call the host language compilers. then the USRPRF parameter must be set to *USER. if OPTION(*CVTDT) is specified. the two steps must be run independently. 342 DB2 UDB for AS/400 SQL Programming V4R4 . then the USRPRF parameter must be set to *OWNER. If SQL naming is used. v For RPG. v Ensure you have a connection established to the AS/400 using the following command: CTTCONN /h<as400name> | 3.sqx (your source) to the AS/400 into the qsys. v Map the AS/400 to a workstation drive. the *QUOTE or *APOST is passed on the CRTBNDCBL or the CRTCBLMOD commands.sqx x mylib/myfile/myapp This command copies myapp. Since the precompiler runs on the AS/400 and the compiler runs on the workstation. Create Program (CRTPGM). the USRPRF parameter may not be set correctly on the CRTBNDxxx.lib/mylib. specify the source member in the output source file. If your source is on the workstation. v For COBOL.lib/myfile.| | | v For COBOL. The SQL program runs predictably only after the USRPRF parameter is corrected. If system naming is used. If the precompile and compile were done as separate steps. This is the same as the AS/400 file system MYLIB/MYFILE (MYAPP) member.file/myapp. Make sure that the environment is set up to run the compiler and precompiler: v Set EBCDIC/ASCII conversion for file extensions . CVTOPT(*VARCHAR *DATETIME *PICGGRAPHIC *FLOAT *DATE *TIME *TIMESTAMP) is always specified on the CRTCBLMOD and CRTBNDCBL commands. Precompiling for the VisualAge C++ for OS/400 Compiler The SQL precompiler for VisualAge C++ for OS/400 is invoked using the CVTSQLCPP CL command.h and . You can interrupt the call to the host language compiler by specifying *NOGEN on the OPTION parameter of the precompiler command. This precompiler is different than the other language precompilers since it does not have an option to generate the module or program object. lib\mylib.cpp This creates a file called myapp. C. 6. During a PL/I.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. the referred to files must not be changed between precompile and compile. Alternately. 5.file\myapp. and the source program refers to externally described files. it will be passed as is to the compiler.lib\mytosrcfile. Copy the output source file member containing the converted SQL to the workstation: CTTCRCPP mylib/mytosrcfile/myapp x myapp. Verify that the compiler interprets the host variable declaration as defined by the SQL precompiler for that language. Error and Warning Messages during a Compile The conditions described in the following paragraphs could produce an error or warning message during an attempted compile process. The compiler will not recognize the EXEC SQL statements. Run the C++ compiler and create the final module or program. Otherwise. You can also do this from the workstation by using the CTTHCMD command.mbr If the source member is on the workstation: iccas -c myapp. Examples of externally described files are: v v v v COPY DDS in COBOL %INCLUDE in PL/I #pragma mapinc and #include in C or C++ Data structures in RPG When the SQL precompiler does not recognize host variables. Run the SQL precompiler on the AS/400 for the source member. If the output source member is still on the AS/400: iccas /c x:\qsys. results that are not predictable may occur because the changes to the field definitions are not changed in the temporary source member. the SQL precompiler will not recognize the statement as an SQL statement. ignore these errors. try compiling the source. This is the CVTSQLCPP CL command.4. Interpreting Application Program Compile Errors Attention: If you separate precompile and compile steps. the default). you can leave the source on the AS/400 and run the compiler against it there. or C++ Compile If EXEC SQL starts before the left margin (as specified with the MARGINS parameter. Chapter 18.cpp on the workstation. Consequently. Preparing and Running a Program with SQL Statements 343 . view. It attempts to build access plans. For non-ILE compiles. see the specific programming examples in Chapter 12. this occurs as the result of a successful CRTxxxPGM. For a distributed SQL program (where the RDB parameter was specified on the CRTSQLxxx or CVTSQLCPP commands). If DB2 UDB for AS/400 detects at run time that an access plan is not valid (for example. SQL automatically attempts to bind and create access plans when the program object is created. the access plan is stored in the SQL package at the specified relational database. 3. When you attempt to run a program that contains an access plan that is not valid. During an RPG Compile If EXEC SQL is not coded in positions 8 through 16. If the table or view does not exist at run time.During a COBOL Compile If EXEC SQL starts before column 12. and other factors are considered. the SQL statements are checked for valid table. Consequently. and preceded with the ’/’ character in position 7. this occurs as the result of a successful CRTBNDxxx. For more information. This process is called binding. a relationship between the program and any specified tables and views must be established. a negative SQLCODE 344 DB2 UDB for AS/400 SQL Programming V4R4 . CRTPGM. For a nondistributed SQL program. If the access plan cannot be rebuilt. For ILE compiles. Coding SQL Statements in REXX Applications. Binding an Application Before you can run your application program. Consequently. the access plan may no longer be valid. In selecting an index. If all the SQL statements are valid. a new access plan is automatically created. and column names. through Chapter 17. a negative SQLCODE is returned. If the characteristics of a table or view your program accesses have changed. Coding SQL Statements in C and C++ Applications. the access plan is stored in the program. Binding does three things: 1. when it builds an access plan. the referenced tables are in a different library) or detects that changes have occurred to the database that may improve performance (for example. It considers all indexes available to access the data and decides which ones (if any) to use when selecting a path to the data. it will be passed as is to the compiler. the SQL precompiler will not recognize the statement as an SQL statement. the validation is done at run time. 2. 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. the SQL precompiler will not recognize the statement as an SQL statement. the bind process then builds and stores access plans in the program. An access plan contains information about the program and about the data the program intends to use. If a specified table or view does not exist at the time of the precompile or compile. the addition of indexes). It revalidates the SQL statements using the description in the database. the system automatically attempts to rebuild the access plan. it will be passed as is to the compiler. It selects the index needed to access the data your program wants to process. During the bind process. table sizes. or CRTSRVPGM command. Displaying Precompiler Options When the SQL application program is successfully compiled. In this case. 3. Program References All collections. SQL packages. the library name is stored as the name qualifier. 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 automatic rebind will be unsuccessful because COLUMNA no longer exists. the library name is stored in the OIR in one of three ways: 1. In this case you must change the program source and reissue the CRTSQLxxx command. For example. views. the Display Module (DSPMOD). the library name is stored in the OIR in one of three ways: 1. tables. the collection name specified on the DFTRDBCOL parameter is stored as the name qualifier. 2. you might have to change the program’s SQL statements and reissue the CRTSQLxxx or CVTSQLCPP command to correct the situation. The Print SQL Information (PRTSQLINF) command can also be used to determine some of the options that were specified on the SQL precompile.is returned. *LIBL is stored. If the SQL name is not fully qualified and the DFTRDBCOL parameter is not specified. the Display Program (DSPPGM). Preparing and Running a Program with SQL Statements 345 . If the SQL name is fully qualified. This information may be needed when the source of the program has to be changed. 2. 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. If the SQL name is not fully qualified and the DFTRDBCOL parameter is specified. These same SQL precompiler options can then be specified on the CRTSQLxxx or CVTSQLCPP command when the program is compiled again. the collection name is stored as the name qualifier. If the object name is fully qualified. when you call the program. Chapter 18. If the object is not fully qualified and the DFTRDBCOL parameter is not specified. or the Display Service Program (DSPSRVPGM) command can be used to determine some of the options that were specified on the SQL precompile. 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. the collection name specified on the DFTRDBCOL parameter is stored as the name qualifier. 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. If the system naming convention is used. users may encounter message CPF2218 in QHST using any Structured Query Language (SQL) program if the user does not have *CHANGE authority to the program. and the Data Management book. An alias is actually created as a DDM file. For more information on running programs. Overrides of statements in SQL packages are accomplished by doing both of the following: 1. For more information on overrides. SQL does support remote access through DRDA (Distributed Relational Database Architecture. OS/400 DDM Considerations SQL does not support remote file access through DDM (distributed data management) files. 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. 346 DB2 UDB for AS/400 SQL Programming V4R4 . The following parameters are processed if an override is specified: TOFILE MBR SEQONLY INHWRT WAITRCD All other override parameters are ignored. is the same as running any host program. Specifying the OVRSCOPE(*JOB) parameter on the OVRDBF command 2. You can create an override that refers to an alias name (DDM file).Running a Program with Embedded SQL Running a host language program with embedded SQL statements. an SQL statement that refers to the file that has the override actually uses the file to which the alias refers. see the CL Programming book. When the long name is specified in an SQL statement. Type: CALL pgm-name | | | | | | | on the system command line. Note: After installing a new release. Once a user with *CHANGE authority calls the program. after the precompile and compile have been successfully done. you can create an override using the system name that is associated with the table or view.) 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. In this case. the override is found using the corresponding system name. the access plan is updated and the message will be issued. see the DB2 UDB for AS/400 Database Programming book. Preparing and Running a Program with SQL Statements 347 . Chapter 18.SQL Return Codes A list of SQL return codes is provided in Appendix B. SQLCODEs and SQLSTATEs. 348 DB2 UDB for AS/400 SQL Programming V4R4 . © Copyright IBM Corp. – – – – – Retrieve and edit statements.Chapter 19. – Remove all entries from the current session. or select information from system catalog tables. The basic functions supplied by interactive SQL are: v The statement entry function allows you to: – Type in an interactive SQL statement and run it. problem analysis. v The list selection function allows you to select from lists of your authorized relational databases. a completion message or an error message is displayed. It also allows you to press F4 to get a menu of all SQL statements. A database administrator can use interactive SQL to grant or revoke privileges. If you want to learn how to use SQL. 1997. tables. tables. You can see help on a message by positioning the cursor on the message and pressing F1=Help. press F4=Prompt. or SQL packages. 1999 349 . can insert rows into a table and test the SQL statements before running them in an application program. or views. Invoke list selection function. Page through previous statements and messages. After an interactive SQL statement is run. Overview information and tips on using interactive SQL are provided. delete. v The prompt function allows you to type either a complete SQL statement or a partial SQL statement. In addition. – Print the current session. using interactive SQL. columns. status messages are normally displayed during long-running statements. Using Interactive SQL This chapter describes how to use interactive SQL to run SQL statements and use the prompt function. and database maintenance. or look at data for testing. The selections you make from the lists can be inserted into the SQL statement at the cursor position. create or drop collections. Getting Started with SQL. constraints. update. – Exit interactive SQL. collections. Special considerations for using interactive SQL with a remote connection are covered in “Accessing Remote Databases with Interactive SQL” on page 359. Call session services. v The session services function allows you to: – Change session attributes. you should see Chapter 2. and then be prompted for the syntax of the statement. views. A programmer. Basic Functions of Interactive SQL Interactive SQL allows the programmer or database administrator to quickly and easily define. Prompt for SQL statements. you can select a statement and be prompted for the syntax of the statement. From this menu. you can enter SQL statements and use: v v v v v F4=prompt F13=Session services F16=Select collections F17=Select tables F18=Select columns Enter SQL Statements Type SQL statement. _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ Bottom F14=Delete line F15=Split line F17=Select tables (files) F16=Select collections (libraries) F18=Select columns F24=More keys (fields) Note: If you are using the system naming convention. see Appendix D. v SQL statements you entered in the session along with corresponding messages that follow each SQL statement 350 DB2 UDB for AS/400 SQL Programming V4R4 . Starting Interactive SQL You can start using interactive SQL by typing STRSQL on an AS/400 command line. This is the main interactive SQL display. For a complete description of the command and its parameters. From this display. press Enter. The Enter SQL Statements display appears.– Save the session in a source file. 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 . ===>_____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ _____________________________________________________________________ F3=Exit F4=Prompt F12=Cancel F6=Insert line F13=Services F9=Retrieve F10=Copy line F24=More keys Bottom Press F24=More keys to view the remaining function keys. DB2 UDB for AS/400 CL Command Descriptions. Current connection is to relational database rdjacque. and *SYN. If an SQL session exists and is being re-entered. Using Interactive SQL 351 .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. If a statement is recognized by SQL but contains a syntax error. any parameters specified on the STRSQL command are ignored. The parameters from the existing SQL session are used. In the statement entry function. If you need more room to type an SQL statement. the statement and the resulting text message (syntax error) are moved upward on the display. Press F9=Retrieve with your cursor on a previous statement to place a copy of that statement in the input area. The statement is parsed and the clauses that are completed are filled in on the prompt displays. you type or prompt for the entire SQL statement and then submit it for processing by pressing the Enter key. and messages. You can place the cursor on the message and press F1=Help for more information about the error. the statement and the resulting message are moved upward on the display. page down on the display. You can page through previous statements. In the input area. 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. If you type SELECT and press F4=Prompt. The prompt function can be used in any of the three statement processing modes: *RUN. Typing Statements The statement you type on the command line can be one or more lines long. When the statement has been processed. You have two options when using the prompter: v Type the verb of the statement before pressing F4=Prompt. Prompting The prompt function helps you supply the necessary information for the syntax of the statement you want to use. Using Statement Entry Function The statement entry function is the function you first enter when selecting interactive SQL. You can then enter another statement. Also. commands. *VLD. You cannot type comments for the SQL statement in interactive SQL. a copy of the statement is shown with the cursor positioned at the syntax error. more than one interactive SQL session can be run from the same work station at the same time from the same user ID. the following display appears: Chapter 19. You return to the statement entry function after processing each interactive SQL statement. If you press F4=Prompt without typing anything. . _____________________________________________ _____________________________________________ _____________________________________________ _____________________________________________ _____________________________________________ _____________________________________________ _____________________________________________ Bottom Y=Yes. . . only statements that can be run in interactive SQL are shown. . 12. . . FOR UPDATE OF columns . N=No Y=Yes. 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 F12=Cancel More. the statement is run. . . . . 7. You are shown a list of statements. 8. . N Specify additional options . . . 3. . . . . . . . . The list of statements varies and depends on the current interactive SQL statement processing mode. . . 352 DB2 UDB for AS/400 SQL Programming V4R4 . . 5. . The prompter remains in control if an error is encountered. . . 2. . FROM tables . The system prompts you for the statement you selected. . press Enter. . the statement that was built through the prompt screens is inserted into the session. 9. 11. . . N 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 v Press F4=Prompt before typing anything on the Enter SQL Statements display. . .. . . . . N UNION with another SELECT . . . .Specify SELECT Statement Type SELECT statement information. . . . . . . 4. For syntax check mode with a language other than *NONE. the prompter displays the formatted SQL statement as it was filled in to that point. . . N=No Type choices. If the statement processing mode is *RUN. GROUP BY columns . . If you press F21=Display Statement on a prompt display. . 14. . When Enter is pressed within prompting. 13. . SELECT columns . . For run and validate modes. ORDER BY columns . . WHERE conditions . the list includes all SQL statements. . 10. You can select the number of the statement you want to use. N=No Y=Yes. Press F4 for a list. the following display appears: Select SQL Statement Select one of the following: 1. . 6. DISTINCT rows in result table . HAVING conditions . .. F6=Insert line. press F20=Display entire name. When processing a DBCS data string that requires more than one line for entering. the subquery information is filled in on the next display. Using Interactive SQL 353 . see “Using Subqueries” on page 84. Entering DBCS Data The rules for processing DBCS data across multiple lines are the same on the Enter SQL Statements display and in the SQL prompter. blank. support is available for entering column definitions individually. If the last two columns of a line contain a shift-in followed by a single-byte blank and the first column of the next line contains a shift-out. only statements that are allowed to run in interactive SQL can be prompted. only the syntax and existence of objects are checked. and press F4=Prompt. Each line must contain the same number of shift-in and shift-out characters. A display that provides room for entering all the information for one column definition is shown. For more information on subqueries. and F14=Delete line. all SQL statements are allowed. The shift characters are shown here at the beginning and end of the string sections on each of the two lines. In *RUN (run) or *VLD (validate) mode. shift-out sequence is removed when the two lines are assembled. You must correct the syntax or remove the incorrect part of the statement or prompting will not be allowed. The statement is not actually run in *SYN or *VLD modes. CREATE TABLE prompting When prompting for CREATE TABLE. Subqueries Subqueries can be selected on any display that has a WHERE or HAVING clause. If the last column on a line contains a shift-in and the first column of the next line contains a shift-out. the shift-in and shift-out characters are removed by the prompter when the two lines are assembled. can be used to add and delete entries in the column definition list. If the cursor is outside the parentheses of the subquery. Statement processing mode The statement processing mode can be selected on the Change Session Attributes display. This removal allows DBCS information to be read as one continuous character string. press F9=Specify subquery when the cursor is on a WHERE or HAVING input line. F10=Copy line. A display appears that allows you to type in subselect information. suppose the following WHERE condition were entered. In *SYN (syntax check) mode. As an example. If the cursor is within the parentheses of the subquery when F9 is pressed. A window with enough space for a 30 character name will be displayed. To see the subquery display. The editing keys. To enter a column name longer than 18 characters. Chapter 19. the shift-in. Place your cursor in the column definition section of the display. The prompter does not accept a syntactically incorrect statement.Syntax Checking The syntax of the SQL statement is checked when it enters the prompter. the extra shift-in and shift-out characters are removed. the next display is blank. . _____________________________________________ ORDER BY columns . . The statement would look like this on the Enter SQL Statements display: SELECT * FROM TABLE1 WHERE COL1 = '<AABBCCDDEEFFGGHHIIJJKKLLMMNNOOPPQQRRSS>' Using the List Selection Function The list selection function is available by pressing F4 on certain prompt displays. You would not have a choice for selecting columns. . . . numerically specifying the order in which you want them to appear in the statement. or F16. or packages from which to choose. . Assume you have: v Just entered interactive SQL by typing STRSQL on an AS/400 command line. . COL1 = '<AABBCCDDEEFFGGHHIIJJKKLLMMNNOOPPQQ> <RRSS>'______________________________________ GROUP BY columns . 354 DB2 UDB for AS/400 SQL Programming V4R4 .Specify SELECT Statement Type SELECT statement information. you are asked to select a collection first. _____________________________________________ HAVING conditions . _____________________________________________ When Enter is pressed. If you request a list of tables. . removing the extra shift characters. . you can select one or more items. . . Then. However. tables. collections. views. but you believe that the columns you want are in a table not currently selected. the table name would be inserted into your statement. You can request a list at any time while typing an SQL statement on the Enter SQL Statements display. constraints. _____________________________________________ FOR UPDATE OF columns . . . For example. When the list function is exited. Example of Using the List Selection Function The following example shows you how to use the list function to build a SELECT statement. . Although the selected list information is added for you. the character string is put together. if you want a list of columns. parameters. columns. and SQL packages are properly qualified. They are inserted where the cursor is located in the numeric order that you specified on the list display. . . The list function tries to provide qualifications that are necessary for the selected columns. Press F4 for a list. . . . After pressing the function key. . the selections you made are inserted at the position of the cursor on the display you came from. . . press F18=Select columns. you must type the keywords for the statement. or F18 on the Enter SQL Statements display. F17. On a list. but you have not previously selected a collection. you are given a list of authorized relational databases. tables. procedures. . . The selections you make from the lists are inserted on the Enter SQL Statements display. . press F17 to change the table. . . aliases. If the table list were selected first. and SQL packages. . *____________________________________________ WHERE conditions . tables. Always select the list you are primarily interested in. FROM tables . TABLE1_______________________________________ SELECT columns . . sometimes the list function cannot determine the intent of the SQL statement. from the column list. You need to review the SQL statement and verify that the selected columns. . Press Enter. 5. Type FROM on the second statement entry line. 7. v Selected *SQL for the naming convention. You have just entered the SQL session and have not selected a collection to work with. Seq 1 Collection YOURCOLL1 YOURCOLL2 YOURCOLL3 YOURCOLL4 Type SYS SYS SYS SYS Text Company benefits Employee personal data Job classifications/requirements Company insurances 6. Begin using SQL statements: 1. Note: The example shows lists that are not on your AS/400 system. They are used as an example only. press Enter. a list of collections appears (the Select and Sequence Collections display). 2. showing the tables existing in the YOURCOLL2 collection. Select and Sequence Tables Type sequence numbers (1-999) to select tables. Type a 1 in the Seq column next to PEOPLE table. Type a 1 in the Seq column next to YOURCOLL2 collection. Type SELECT on the first statement entry line. 3. Enter SQL Statements Type SQL statement. Seq 1 Table EMPLCO PEOPLE EMPLEXP EMPLEVL EMPLBEN EMPLMED EMPLINVST Collection YOURCOLL2 YOURCOLL2 YOURCOLL2 YOURCOLL2 YOURCOLL2 YOURCOLL2 YOURCOLL2 Type TAB TAB TAB TAB TAB TAB TAB Text Employee Employee Employee Employee Employee Employee Employee company data personal data experience evaluation reports benefits record medical record investments record 8. Press Enter. Chapter 19. because you want the table name to follow FROM. Leave the cursor positioned after FROM. Using Interactive SQL 355 .v Made no list selections or entries. Select and Sequence Collections Type sequence numbers (1-999) to select collections. ===> SELECT FROM _ 4. press Enter. press Enter. Press F17=Select tables to obtain a list of tables. The Select and Sequence Tables display appears. Instead of a list of tables appearing as you expected. Select and Sequence Columns Type sequence numbers (1-999) to select columns. 11. Seq Column 2 NAME EMPLNO 1 SOCSEC STRADDR CITY ZIP PHONE 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 13. Enter SQL Statements Type SQL statement. The statement you created is now run. 356 DB2 UDB for AS/400 SQL Programming V4R4 . press Enter. Enter SQL Statements Type SQL statement. press Enter. the values you selected remain in effect until you change them or until you change the list of collections on the Change Session Attributes display.PEOPLE. NAME appearing after SELECT.The Enter SQL Statements display appears again with the table name. 12. Session Services Description The interactive SQL Session Services display is requested by pressing F13 on the Enter SQL Statements display. inserted after FROM. Press Enter. Type a 1 in the Seq column next to the SOCSEC column. ===> SELECT FROM YOURCOLL2. The table name is qualified by the collection name in the *SQL naming convention. because you want the column name to follow SELECT. YOURCOLL2. ===> SELECT SOCSEC. Press Enter. Press F18=Select columns to obtain a list of columns. showing the columns in the PEOPLE table.PEOPLE 14.PEOPLE _ 9. 10. Once you have used the list function. The Select and Sequence Columns display appears. press Enter. Type a 2 in the Seq column next to the NAME column. NAME FROM YOURCOLL2. The Enter SQL Statements display appears again with SOCSEC. Position the cursor after SELECT. You are prompted for the source file name. v The sort sequence. clear. The options shown on this display change based on the statement processing option selected. You are prompted to ensure that you really want to delete the information. which allows you to select the current values that are in effect for your interactive SQL session. Using Interactive SQL 357 . Option 2 (Print current session) accesses the Change Printer display. Option 1 (Change session attributes) displays the Change Session Attributes display. v The list type to select either all your system and SQL objects. v The list of collections. v The date format. v The SQL string delimiter. 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. The source file created by option 4 may be edited and used as the input source file for the Run SQL Statements (RUNSQLSTM) command. This function lets you embed the source file into a host language program by using the source entry utility (SEU). v The statement processing control. v The time format. v The naming option. v The SELECT output device. The following session attributes can be changed: v Commitment control attributes. v The date separator. v The language identifier. or save the session to a source file. v The allow copy data option. All the SQL statements you entered and all the messages displayed are printed just as they appear on the Enter SQL Statements display. v The programming language. Note: Option 4 allows you to embed prototyped SQL statements in a high-level language (HLL) program that uses SQL. You are prompted for printer information. v The time separator. which lets you save the session in a source file. or only your SQL objects. Exiting Interactive SQL Pressing F3=Exit on the Enter SQL Statements display allows you to exit the interactive SQL environment and do one of the following: Chapter 19. v The data refresh option when displaying data. v The decimal point representation.From this display you can change session attributes and print. which lets you print the current session immediately and then continue working. Option 4 (Save session in source file) accesses the Change Source File display. Using an existing SQL Session If you saved only one interactive SQL session by using option 1 (Save and exit session) on the Exit Interactive SQL display. If no sessions for your user ID are available. 4. However. If that session is currently in use.1. Save the current session in a source file. You cannot recover and work with this session again in interactive SQL. If you choose to delete the old session and continue with the new session. Exit without saving session. Option 4 allows you to embed prototype SQL statements in a high-level language (HLL) program that uses SQL. If rows have been changed and locks are currently being held for this unit of work and you attempt to exit interactive SQL. If no matching sessions are available. If that session is also in use. interactive SQL will then attempt to resume the session that was saved for workstation 2. Use the source entry utility (SEU) to copy the statements into your program. Leave interactive SQL without saving your session. you can either: v Recover the old session by selecting option 1 (Attempt to resume existing SQL session). However. The Change Source File display is shown to allow you to select where to save the session. Save session in source file. Leave interactive SQL. you saved a session on workstation 1 and saved another session on workstation 2 and you are currently working at workstation 1. Interactive SQL will first attempt to resume the session saved for workstation 1. 3. if you use option 1 to save two or more sessions on different workstations. suppose you are working at workstation 3 and want to use the ISQL session associated with workstation 2. v Delete the old session and start a new session by selecting option 2 (Delete existing SQL session and start a new session). interactive SQL presents the Recover SQL Session display at the start of the next session (when the next STRSQL command is entered). Recovering an SQL Session If the previous SQL session ended abnormally. you may resume that session at any workstation. 2. Notes: 1. The current session parameters remain in effect. the system will create a new session for your user ID and current workstation. the parameters you specified when you entered STRSQL are used. For example. You then may need to first delete the session from workstation 1 by using option 2 (Exit without saving session) on the Exit Interactive SQL display. If you choose to 358 DB2 UDB for AS/400 SQL Programming V4R4 . then interactive SQL will increase the scope of the search to include all sessions that belong to your user ID. interactive SQL will first attempt to resume a session that matches your work station. 2. From this display. Your current session will be saved and used the next time you start interactive SQL. Remain in interactive SQL and return to the Enter SQL Statements display. then the system will create a second session for workstation 1. The source file can also be edited and used as the input source file for the Run SQL Statements (RUNSQLSTM) command. Resume session. a warning message is displayed. Save and exit session. Using Interactive SQL 359 . the parameters you specified when you entered STRSQL are ignored and the parameters from the old session are used. a message shows the relational database connection that was established. some session attributes are changed to attributes that are supported by that application server. Accessing Remote Databases with Interactive SQL In interactive SQL. a RELEASE ALL followed by a COMMIT be issued to end previous connections. When the CONNECT statement is completed. This implicit connect and possible commitment control registration may influence subsequent connections to remote databases. and change the commitment control level to at least *CHG. *NONE *ALL *SYS *NO. a RELEASE ALL followed by a COMMIT be issued to end previous connections.recover the old session. Interactive SQL does an implicit connect to the local RDB when starting an SQL session. The following table shows the attributes that change. Table 35. It is recommended that prior to connecting to the remote system: v When connecting to an application server that does not support distributed unit of work. Interactive SQL uses the CONNECT (Type 2) semantics (distributed unit of work) for CONNECT statements. including the implicit connection to local. *YES *ALWAYS *SYSVAL Any value other than *HEX *JIS *EUR *CS Repeatable Read New Value *ISO *EUR *USA *USA Commitment Control Naming Convention Allow Copy Data Data Refresh Decimal Point Sort Sequence *SQL *OPTIMIZE *FORWARD *PERIOD *HEX Chapter 19. or are entering a previously saved session. If starting a new session and COMMIT(*NONE) was not specified. Values Table Session Attribute Date Format Original Value *YMD *DMY *MDY *JUL Time Format *HMS with a : separator *HMS with any other separator *CHG. A message is returned to indicate which parameters were changed from the specified value to the old session value. For further information. When you are connecting to a non-DB2 UDB for AS/400 application server. see “Determining Connection Type” on page 567. including the implicit connection to local. or if restoring a saved session and the commit level saved with the session was not *NONE. the connection will be registered with commitment control. you can communicate with a remote relational database by using the SQL CONNECT statement. v When connecting to a non-DB2 UDB for AS/400 application server. You can also end the connections by doing a RELEASE ALL and a COMMIT before exiting interactive SQL. After the connection is completed. the sort sequence value changes to *HEX. 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. the connections remain. the SQL prompter and list support use the statement syntax and naming conventions supported by the local system. on the remote system. there may be a reference to a ’CREATE TABLE XXX’ statement. and can be ignored. Note: In the output of a communications trace. When connected to a remote system with interactive SQL. For more information. Lists of columns are available only when you are connected to a relational database manager that supports the DESCRIBE TABLE statement. no other connection can be established for the default activation group. the date and time formats specified must be the same format. When you exit interactive SQL with connections that have pending changes or connections that use protected conversations. The changed session attributes can be displayed by using the session services display. Lists of collections and tables are available when you are connected to the local relational database. however. While interactive SQL is running. 360 DB2 UDB for AS/400 SQL Programming V4R4 . If connecting to an AS/400 system that is running a release prior to Version 2 Release 3.Notes: 1. Using interactive SQL for remote access to non-DB2 UDB for AS/400 application servers can require some setup. This is used to determine package existence. The statement is run. see the Distributed Database Programming book. 2. the connections are ended during the next COMMIT or ROLLBACK operation. syntax errors may be found in the statement on the remote system at run time. a message is sent stating that the session attributes have been changed. Similarly. If you do not perform additional work over the connections. Because of differences in the level of SQL support between the two systems. it is part of normal processing. When connecting to a DB2/2 or DB2/6000 application server. only the first 80 characters will be read. This makes the setup of a database environment easier. The statements that can be used with the SQL statement processor are: v ALTER TABLE v v v v v v v v v v v v v CALL COMMENT ON COMMIT CREATE ALIAS CREATE COLLECTION CREATE DISTINCT TYPE CREATE FUNCTION CREATE INDEX CREATE SCHEMA CREATE TABLE CREATE VIEW DELETE DROP | | v CREATE PROCEDURE v GRANT (Package Privileges) v GRANT (Procedure Privileges) v GRANT (Table Privileges) v INSERT v LABEL ON v LOCK TABLE v RENAME v REVOKE (Package Privileges) v REVOKE (Procedure Privileges) v v v v v REVOKE (Table Privileges) ROLLBACK SET PATH SET TRANSACTION UPDATE | In the source member. or changed. without compiling the source. If the record length of the source member is longer than 80. Line comments begin with a double hyphen (−−) and end at the end of the line.Chapter 20. The default print file is QSYSPRT. This processor is available when you use the Run SQL Statements (RUNSQLSTM) command. © Copyright IBM Corp. The output listing and the resulting messages for the SQL statements are sent to a print file. Block comments start with /* and can continue across many lines until the next */ is reached. Using the SQL Statement Processor This section describes the SQL Statement processor. The statements in the source member can be run repeatedly. statements end with a semicolon and do not begin with EXEC SQL. 1999 361 . Comments in the source member can be either line comments or block comments. The SQL statement processor allows SQL statements to be executed from a source member. Block comments can be nested. Only SQL statements and comments are allowed in the source file. 1997. If a commitment-control level other than *NONE is specified. This is a complex statement that can be thought of as having two distinct sections. Schemas in the SQL Statement Processor The SQL statement processor supports the CREATE SCHEMA statement. but those statements will not be executed. v CREATE SCHEMA AUTHORIZATION authorization-name A collection is created using the authorization name as the collection name. A statement is considered successful if its return code severity is less than or equal to the value specified on the ERRLVL parameter of the RUNSQLSTM command. Most SQL errors have a severity of 30. If all of the statements successfully execute. If you want to continue processing after an SQL statement fails. The first section can be written in one of two ways: v CREATE SCHEMA collection-name A collection is created using the specified collection name.To perform syntax checking only on all statements in the source member. The first section defines the collection for the schema. When the schema is run. the statement has failed. a COMMIT is done at the completion of the SQL statement processor. the user must have authority to the user profile that is named authorization-name. The privileges held by the authorization-name of the statement must include: – Authority to run the CREATE COLLECTION statement – Authority to run each SQL statement within the CREATE SCHEMA The second section of the CREATE SCHEMA statement can contain from zero to any number of the following statements: v COMMENT ON v CREATE DISTINCT TYPE v CREATE TABLE | 362 DB2 UDB for AS/400 SQL Programming V4R4 . Note: The job must be at a unit of work boundary to use the SQL statement processor with commitment control. Otherwise. Execution of Statements After Errors Occur When a statement returns an error with a severity higher than the value specified for the error level (ERRLVL) parameter of the RUNSQLSTM command. The rest of the statements in the source will be parsed to check for syntax errors. a ROLLBACK is done. the SQL statements are run under commitment control. set the ERRLVL parameter of the RUNSQLSTM command to 30 or higher. The SET TRANSACTION statement can be used within the source member to override the level of commitment control specified on the RUNSQLSTM command. specify the PROCESS(*SYN) parameter on the RUNSQLSTM command. Commitment Control in the SQL Statement Processor A commitment-control level is specified on the RUNSQLSTM command. The second section contains DDL statements that define the objects in the collection. .................... If other SQL statements follow this schema definition..*JOB Date separator.10 Date format................................*RUN Allow copy of data........ The statements and sections are not separated by semicolons........*JOB Time format.. All qualified references must be qualified by the created collection......CORPDATA/SRC Member.*JOB Printer file. Source Member Listing for the SQL Statement Processor 5769ST1 V4R4M0 990521 Run SQL Statements Source file....*READ Source member changed on 04/01/98 11:54:10 SCHEMA 04/01/98 15:35:18 Page 1 Figure 12......*NOFLAG ANS flagging..........*JOB Default Collection.....*LIBL/QSYSPRT Source file CCSID.......... the last statement in the schema must be ended by a semicolon.........*NONE Decimal point.| v v v v v CREATE VIEW CREATE INDEX CREATE ALIAS GRANT (User-Defined Type Privileges) GRANT (Table Privileges) v LABEL ON These statements follow directly after the first section of the statement..............65535 Job CCSID...........................................*JOB Language ID...0 Statement processing..........*JOB Sort Sequence......... Using the SQL Statement Processor 363 ............ All unqualified references are implicitly qualified by the collection that was created.*NONE IBM SQL flagging.. QSYSPRT listing for SQL statement processor (Part 1 of 3) Chapter 20......... All objects created or referenced in the second part of the schema statement must be in the collection that was created for the schema..............*SYS Generation level.*NONE Naming.....SCHEMA Commit............*HMS Time separator ....................*OPTIMIZE Allow blocking...... .5769ST1 V4R4M0 990521 Run SQL Statements SCHEMA Record *...... 4 . 6 . 5 . SQL7952 0 5 Position 3 Collection DEPT created. 3 . SQL7966 0 25 Position 9 GRANT of authority to LEVEL in MANAGER completed..+. QSYSPRT listing for SQL statement processor (Part 2 of 3) 5769ST1 V4R4M0 990521 Run SQL Statements SCHEMA Record *....Two statements can be on the same line * * * * * E N D O F S O U R C E * * * * * SEQNBR 04/01/98 15:35:18 Last change Page 2 Figure 12.. 5 . SQL7954 0 23 Position 9 Index SALARYIND created on table EMP_SALARY in MANAGER. SQL7953 0 3 Position 3 Drop of MANAGER in QSYS complete.+... 8 MSG ID SEV RECORD TEXT SQL7953 0 1 Position 1 Drop of DEPT in QSYS complete..+. SQL7966 0 10 Position 8 GRANT of authority to EMP in DEPT completed.. SQL7950 0 19 Position 9 Table EMP_SALARY created in collection MANAGER.. 20 LEVEL CHAR(10)) 21 CREATE VIEW LEVEL AS SELECT EMPNBR... 13 /* table must be qualified since no 14 longer in the schema */ 15 16 CREATE SCHEMA AUTHORIZATION MANAGER 17 -...+.. 3 DROP COLLECTION MANAGER. 2 .+...+. SQL7950 0 6 Position 8 Table EMP created in collection DEPT.. 1 . -..+..+... 6 .... 3 .. 4 5 CREATE SCHEMA DEPT 6 CREATE TABLE EMP (EMPNAME CHAR(50). EMPNBR INT) 7 -.+.EMP will be created in collection DEPT 8 CREATE INDEX EMPIND ON EMP(EMPNBR) 9 -..+.+. SQL7952 0 13 Position 28 Collection MANAGER created.. 7 . SQL7956 0 10 Position 40 1 rows inserted in EMP in DEPT.user profile 19 CREATE TABLE EMP_SALARY (EMPNBR INT.. SQL7966 0 25 Position 37 GRANT of authority to EMP_SALARY in MANAGER completed... 2 ..this schema will use MANAGER's 18 -... QSYSPRT listing for SQL statement processor (Part 3 of 3) 364 DB2 UDB for AS/400 SQL Programming V4R4 ..+.. 1 .+. 8 1 2 DROP COLLECTION DEPT.....EMPIND will be created in DEPT 10 GRANT SELECT ON EMP TO PUBLIC.+.. SQL7954 0 8 Position 8 Index EMPIND created on table EMP in DEPT... Message Summary Total Info Warning Error Severe Terminal 13 13 0 0 0 0 00 level severity errors found in source * * * * * E N D O F L I S T I N G * * * * * SEQNBR 04/01/98 15:35:18 Last change Page 3 Figure 12. LEVEL 22 FROM EMP_SALARY 23 CREATE INDEX SALARYIND ON EMP_SALARY(EMPNBR... SALARY DECIMAL(7...SALARY) 24 25 GRANT ALL ON LEVEL TO JONES GRANT SELECT ON EMP_SALARY TO CLERK 26 -....+.2).+... SQL7951 0 21 Position 9 View LEVEL created in collection MANAGER. 4 . 1234).grant authority 11 12 INSERT INTO DEPT/EMP VALUES('JOHN SMITH'...... 7 .. The authority to run the SQL statement remotely is checked using the user profile at the application server. see the Security . including SQL objects. The highest authority is the authority that is used. In some cases. and RVKOBJAUT to authorize users to other objects. GRTOBJAUT. 1999 365 . 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 server job and the owner of the SQL package. are managed by the system security function. The authority to run the SQL statement remotely is checked using the user profile of the application server job. you should use the *OWNER parameter © Copyright IBM Corp. The authority checked for SQL statements depends on whether the statement is static. The authority to run the SQL statement remotely is checked using the user profile of the application server job. 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. it is necessary to use EDTOBJAUT. For dynamic SQL statements: v If the USRPRF value is *USER. v If the USRPRF value is *OWNER. Users may authorize SQL objects through either the SQL GRANT and REVOKE statements or the CL commands Edit Object Authority (EDTOBJAUT). *OWNER is the default for SQL (*SQL) naming. and Revoke Object Authority (RVKOBJAUT). the authority to run the SQL statement locally is checked using the user profile of the person running the program. The SQL GRANT and REVOKE statements operate on SQL packages. SQL procedures. DB2 UDB for AS/400 Data Protection This chapter describes the security plan for protecting SQL data from unauthorized users and the methods for ensuring data integrity. v If the USRPRF value is *OWNER and DYNUSRPRF is *USER. *USER is the default for system (*SYS) naming.Reference book. Furthermore. the authority to run the SQL statement locally is checked using the user profile of the person running the program. For more information on system security and the use of the GRTOBJAUT and RVKOBJAUT commands. SQL GRANT and REVOKE statements only grant private and public authorities. views. Grant Object Authority (GRTOBJAUT). The higher authority is the authority that is used. 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. dynamic. see the DB2 UDB for AS/400 SQL Reference book. the authority to run the SQL statement locally is checked using the user profile of the user running the program. Because of security concerns. For more information on the GRANT and REVOKE statements. tables. 1997. For static SQL statements: v If the USRPRF value is *USER.Chapter 21. Security All objects on the AS/400 system. and the individual columns of tables and views. v If the USRPRF value is *OWNER and DYNUSRPRF is *OWNER. such as commands and programs. or being run interactively. authorization failures. This option gives the access authority of the owner program or package to those who run the program. programming errors.S. An object that is deleted under commitment control is hidden and not actually deleted until a commit is done. authority is checked against the authority of the person processing the statement. DB2 UDB for AS/400 uses the audit facilities managed by the system security function. revokes. A view can also restrict access to particular rows in a table by specifying a WHERE clause (for example. A view can restrict access to particular columns by not specifying those columns in the SELECT list (for example. The application program can access the data it needs in a table. DB2 UDB for AS/400 can also audit row changes by using the DB2 UDB for AS/400 journal support. system operation or hardware failures (such as physical damage to a disk). then does a commit. Once the commit is done. For interactive SQL statements. user. Views A view can prevent unauthorized users from having access to sensitive data. creates.value for DYNUSRPRF carefully. Auditing DB2 UDB for AS/400 is designed to comply with the U. grants. or system level. etc. creates a new table with the same name as the one that was deleted. Auditing can be performed on an object level. allowing access only to the rows associated with a particular department number). This is because objects that are created are journalled immediately. The system value QAUDLVL controls what types of actions are audited (for example. A key feature of that level is the ability to audit actions on the system. The Change User Audit (CHGUSRAUD) command and Change Object Audit (CHGOBJAUD) command specify which users and objects are audited. In some cases. government C2 security level. or interference from running applications at the same time (such as serialization problems). Authorization IDs can be created using the system Create User Profile (CRTUSRPRF) command.Reference book. employee salaries). Data Integrity Data integrity protects data from being destroyed or changed by unauthorized persons. interruptions before a job is completed (such as a power failure). For example. entries in the auditing journal will not be in the same order as they occured. This will be recorded in the auditing journal as a create followed by a delete. a job that is running under commitment control deletes a table. Authorization ID The authorization ID identifies a unique user and is a user profile object on the AS/400 system. without having access to sensitive or restricted data in the table. the action is journaled. Data integrity is ensured by the following functions: 366 DB2 UDB for AS/400 SQL Programming V4R4 .) For more information on auditing see the Security . Adopted authority is not used for interactive SQL statements. deletes. The system value QAUDCTL controls whether auditing is performed at the object or user level. If the second job then attempts to lock row 1. The lock wait time used for all DDL statements and the LOCK TABLE statement. and indexes with the default record wait time (60 seconds) and the default file wait time (*IMMED). However. and Override Database File (OVRDBF). In the event that a large record wait time is specified. This will prevent a positioned UPDATE or positioned DELETE statement that references the first cursor until another FETCH is performed. 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). 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. deadlock detection is provided. it will wait because the second job is holding the lock. If the first job attempts to lock row 2. some situations require DB2 UDB for AS/400 to acquire a more exclusive table level lock instead of row locks. DB2 UDB for AS/400 Data Protection 367 . Locks are implicitly acquired on tables and rows to protect concurrent users from changing the same data at precisely the same time. DB2 UDB for AS/400 creates tables. | | | | | | | For example. You can change these values by using the CL commands Change Physical File (CHGPF). assume one job has an exclusive lock on row 1 and another job has an exclusive lock on row 2. DB2 UDB for AS/400 will detect that the two jobs are in a deadlock and an error will be returned to the second job. Default and user-specifiable lock-wait time-out values are supported. 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. Chapter 21. For example. This ability is automatically supplied by the DB2 UDB for AS/400 database manager. Change Logical File (CHGLF). Typically. This lock wait time is used for DML statements. For more information see “Commitment Control” on page 369. views.v v v v v Concurrency Journaling Commitment control Atomic operations Constraints v Save/restore v Damage tolerance v Index recovery The DB2 UDB for AS/400 Database Programming book and the Backup and Recovery book contain more information about each of these functions. You can change this value by using the CL commands Change Job (CHGJOB) or Change Class (CHGCLS). DB2 UDB for AS/400 will acquire locks on rows to ensure integrity. is the job default wait time (DFTWAIT). DB2 UDB for AS/400 will frequently leave the open data path (ODP) open (for more information see “Chapter 25. Journaling The DB2 UDB for AS/400 journal support supplies an audit trail and forward and backward recovery. 368 DB2 UDB for AS/400 SQL Programming V4R4 . data which has been read by one job can be immediately changed by another job. The data in the temporary result table will not reflect changes made after the cursor was opened. DB2 UDB for AS/400 will detect that other jobs are holding locks and events will be signalled to those jobs. The event causes DB2 UDB 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. however. v ALWCPYDTA(*OPTIMIZE) was specified and the optimizer determined that making a copy of the data would perform better than not making a copy. This performance feature also leaves a lock on tables referenced by the ODP. which is described in the DB2 UDB for AS/400 SQL Reference book. Backward recovery can be used to remove changes logged on the journal from the table. – UNION or DISTINCT clauses are specified. Additional SQL performance considerations” on page 459). – Joining or specifying GROUP BY on a logical file which is based on multiple database file members. 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. the data that is read at the time the SQL statement is executed and therefore it is very current (for example. Usually. or either COMMIT(*ALL) or COMMIT(*RR) is used.You can explicitly prevent other users from using a table at the same time by using the SQL LOCK TABLE statement. Forward recovery can be used to take an older version of a table and apply the changes logged on the journal to the table. v A basic subquery is evaluated when the query is opened. 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. Using COMMIT(*RR) will also prevent other users from using a table during a unit of work. In order to improve performance. In the following cases. during OPEN). v Some queries require the database manager to create a temporary result table. – Joining a logical file defined by the JOINDFT data definition specifications (DDS) keyword with another file. data is read prior to the execution of the SQL statement and therefore the data may not be current (for example. – ORDER BY or GROUP BY clauses specify columns which are not all from the same table. however. but does not leave any locks on rows. – ORDER BY and GROUP BY clauses specify different columns or columns in a different order. during FETCH). A lock left on a table may prevent another job from performing an operation on that table. In most cases. – The query contains a GROUP BY clause which references a view that contains a GROUP BY clause. – The query contains a join in which at least one of the files is a view which contains a GROUP BY clause. if the table was journaled at the time of the save. all update and delete operations will be prevented. however. if a table is moved into a collection. A commit operation can be issued through several different interfaces. This is because DB2 UDB 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. 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. For example. CASCADE. If a table is restored. DB2 UDB for AS/400 Data Protection 369 . A user can stop journaling on any table using the journal functions. If the table was not journaled at the time of the save. the normal journal rules apply. The journal created in the SQL collection is normally the journal used for logging all changes to SQL tables. You can. For example. SET NULL. A commit operation guarantees that the group of operations is completed. However. Commitment Control The DB2 UDB for AS/400 commitment control support provides a means to process a group of database changes (updates.When an SQL collection is created. DDL operations. an application is still able to function if you have specified COMMIT(*NONE). because placing journal receivers on their own ASPs can improve performance. If journaling is stopped on a parent table of a referential constraint with a delete rule of NO ACTION. A rollback operation guarantees that the group of operations is backed out. use the system journal functions to journal SQL tables to a different journal. A table created in a non-collection will also have journaling started if a journal named QSQJRN exists in that library. the person managing the journal might want to create all future journal receivers on a separate ASP. inserts. After this point. For example. v An SQL ROLLBACK statement v A CL ROLLBACK command v A language rollback statement (such as an RPG ROLBK statement) The only SQL statements that cannot be committed or rolled back are: Chapter 21. the journal receivers. it is automatically journaled to the journal DB2 UDB for AS/400 created in the collection (QSQJRN). When SQL creates the journal and journal receiver. this does not provide the same level of integrity that journaling and commitment control provide. or SET DEFAULT. however. a journal and journal receiver are created in the collection. but doing so prevents an application from running under commitment control. no automatic change to the journaling status occurs. it is journaled to the same journal at restore time. or deletes) as a single unit of work (transaction). Otherwise. That is. This may be necessary if a table in one collection is a parent to a table in another collection. it is your responsibility to use the journal functions to manage the journal. v An SQL COMMIT statement v A CL COMMIT command v A language commit statement (such as an RPG COMMIT statement) A rollback operation can be issued through several different interfaces. When a table is created into the collection. it is not journaled at restore time. and the journaling of tables to the journal. a ROLLBACK HOLD has no effect on the cursor’s position. all read only cursors will allow blocking of rows and a ROLLBACK HOLD will not roll the cursor position back. or RUNSQLSTM commands will override the default lock level. 370 DB2 UDB for AS/400 SQL Programming V4R4 . In addition. v If COMMIT(*ALL). NFYOBJ. Message SQL0595 may also be sent. the LCKLVL specified is the lock level on the SET OPTION statement. For cursors that use column functions. or COMMIT(*CS) with the KEEP LOCKS clause is specified and either catalog files are used or a temporary result table is required. the tables will be locked until the query is closed. or HAVING. If the cursor is in 16. or COMMIT(*CS) with the KEEP LOCKS clause is specified for one of the cursors. Message SQL0595 may also be sent. DB2 UDB for AS/400 uses the job level commitment definition for programs in that activation group. or COMMIT(*CS) with the KEEP LOCKS clause is specified for one of the cursors requested but not allowed.v DROP COLLECTION v GRANT or REVOKE if an authority holder exists for the specified object If commitment control was not already started when either an SQL statement is executed with an isolation level other than COMMIT(*NONE) or a RELEASE statement is executed. COMMIT(*RR). the tables referred to in the application program by Data Manipulation Language statements must be journaled. then DB2 UDB for AS/400 sets up the commitment control environment by implicitly calling the CL command Start Commitment Control (STRCMTCTL). a message (CPI430B) is sent that says COMMIT(*CHG) requested but not allowed. In REXX. The LCKLVL specified is the lock level on the COMMIT parameter on the CRTSQLxxx. STRSQL. or LCKLVL. the SET TRANSACTION SQL statement and the lock level specified on the COMMIT parameter on the CRTSQLxxx. DB2 UDB for AS/400 specifies NFYOBJ(*NONE) and CMTSCOPE(*ACTGRP) parameters along with LCKLVL on the STRCMTCTL command. 16 You may use the STRCMTCTL command to specify a different CMTSCOPE. the table will be locked (*SHRNUP). The lock prevents concurrent application processes from executing any but read-only operations on the named table. GROUP BY. Note: When using commitment control. COMMIT(*RR). If COMMIT(*RR) is requested. After commitment control is started. COMMIT(*RR). DB2 UDB for AS/400 will lock all referenced tables in shared mode (*SHRNUP). the following occurs under commitment control: v If COMMIT(*CHG) and (ALWBLK(*NO) or (ALWBLK(*READ)) is specified for one of these cursors. DB2 UDB for AS/400 will lock all referenced tables in shared mode (*SHRNUP). A message (either SQL7902 or CPI430A) is sent that says COMMIT(*ALL). If you specify CMTSCOPE(*JOB) to start the job level commitment definition. Note that the LCKLVL specified is only the default lock level. If ALWBLK(*ALLREAD) and COMMIT(*CHG) were specified. If the cursor is read only. This will prevent concurrent processes from executing anything but read-only operations on the table(s). or RUNSQLSTM commands. and are running under commitment control. For cursors where either COMMIT(*ALL). STRSQL. when the program was precompiled. A message (either SQL7902 or CPI430A) is sent that says COMMIT(*ALL) is requested but not allowed. all updates. This ensures that. Record Lock Duration SQL Statement SELECT INTO SET variable VALUES INTO FETCH (read-only cursor) COMMIT Parameter (See note 6) *NONE *CHG *CS (See note 8) *ALL (See note 2) *NONE *CHG *CS (See note 8) *ALL (See note 2) Duration of Record Locks No locks No locks Row locked when read and released From read until ROLLBACK or COMMIT No locks No locks From read until the next FETCH From read until ROLLBACK or COMMIT Lock Type READ READ READ READ Chapter 21. Such a cursor is closed on a rollback. This will not prevent other jobs from reading the unchanged records. and DDL operations made within the unit of work are committed. deletes. If the application issues a COMMIT or the activation group ends normally. Commitment control handles up to 4 million distinct row changes in a unit of work. it is only counted once toward the limit. the WITH HOLD option on DECLARE CURSOR may be used to keep the cursor open after a COMMIT. if the same unit of work rereads a record. inserts.) Holding a large number of locks adversely affects system performance and does not allow concurrent users to access rows locked in the unit of work until the end of the unit of work. If COMMIT(*ALL) or COMMIT(*RR) is specified. Table 36. read locks on rows fetched are also used to prevent other jobs from changing data that was read before a unit of work completes.update mode. The HOLD value is not available when you are connected to a remote database that is not on an AS/400 system. It is in your best interest to keep the number of rows processed in a unit of work small. (If a row is changed or read more than once in a unit of work. This type of cursor is supported when you are connected to a remote database that is not on an AS/400 system. DB2 UDB for AS/400 uses locks on rows to keep other jobs from accessing changed data before a unit of work completes. all rows read are also included in the limit. inserts. Since other users will be locked out of the table. COMMIT HOLD and ROLLBACK HOLD allows you to keep the cursor open and start another unit of work without issuing an OPEN again. running with repeatable read will prevent concurrent access of the table. it gets the same result. and DDL operations made within the unit of work are backed out. deletes. Commitment control will allow up to 512 files for each journal to be open under commitment control or closed with pending changes in a unit of work. Read locks do not prevent other jobs from fetching the same rows. DB2 UDB for AS/400 Data Protection 371 . the table will be locked (*EXCLRD). all updates. If an isolation level other then COMMIT(*NONE) was specified and the application issues a ROLLBACK or the activation group ends normally (and the commitment definition is not *JOB). However. If COMMIT(*ALL) is specified. Record Lock Duration (continued) SQL Statement FETCH (update or delete capable cursor) (See note 1) COMMIT Parameter (See note 6) *NONE Duration of Record Locks When record not updated or deleted from read until next FETCH When record is updated or deleted from read until UPDATE or DELETE When record not updated or deleted from read until next FETCH When record is updated or deleted from read until COMMIT or ROLLBACK When record not updated or deleted from read until next FETCH When record is updated or deleted from read until COMMIT or ROLLBACK From read until ROLLBACK or COMMIT No locks From insert until ROLLBACK or COMMIT From insert until ROLLBACK or COMMIT From insert until ROLLBACK or COMMIT No locks No locks Each record locked while being read From read until ROLLBACK or COMMIT Each From From From Each From From From Lock From From From Lock From From From From From From From record locked while being updated read until ROLLBACK or COMMIT read until ROLLBACK or COMMIT read until ROLLBACK or COMMIT record locked while being deleted read until ROLLBACK or COMMIT read until ROLLBACK or COMMIT read until ROLLBACK or COMMIT released when record updated read until ROLLBACK or COMMIT read until ROLLBACK or COMMIT read until ROLLBACK or COMMIT released when record deleted read until ROLLBACK or COMMIT read until ROLLBACK or COMMIT read until ROLLBACK or COMMIT read read read read until until until until next FETCH next FETCH next FETCH ROLLBACK or COMMIT Lock Type UPDATE *CHG UPDATE *CS UPDATE *ALL INSERT (target table) *NONE *CHG *CS *ALL *NONE *CHG *CS *ALL *NONE *CHG *CS *ALL *NONE *CHG *CS *ALL *NONE *CHG *CS *ALL *NONE *CHG *CS *ALL *NONE *CHG *CS *ALL (see note 2) UPDATE3 UPDATE UPDATE UPDATE4 INSERT (tables in subselect) READ READ UPDATE UPDATE UPDATE UPDATE UPDATE UPDATE UPDATE UPDATE UPDATE UPDATE UPDATE UPDATE UPDATE UPDATE UPDATE UPDATE READ READ READ READ UPDATE (non-cursor) DELETE (non-cursor) UPDATE (with cursor) DELETE (with cursor) Subqueries (update or delete capable cursor or UPDATE or DELETE non-cursor) Subqueries (read-only *NONE cursor or SELECT INTO) *CHG *CS *ALL No locks No locks Each record locked while being read From read until ROLLBACK or COMMIT READ READ 372 DB2 UDB for AS/400 SQL Programming V4R4 .Table 36. 8. they will complete or they will appear not to have started. If no cursors are associated with the isolation clause. DB2 UDB for AS/400 Data Protection 373 . some underlying database data definition functions are not atomic.Table 36. If COMMIT (*NONE) is specified. Repeatable read (*RR) record locks will be the same as the locks indicated for *ALL. abnormal job end. all operations are guaranteed to be atomic. however. The locks acquired and their duration are identical to *ALL. A table or view can be locked exclusively in order to satisfy repeatable read. 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. then locks are held until the completion of the SQL statement. 6. 5. v The cursor is defined without a FOR UPDATE. A cursor is open with UPDATE or DELETE capabilities if the result table is not read-only (see description of DECLARE CURSOR in DB2 UDB for AS/400 SQL Reference book) and if one of the following is true: v The cursor is defined with a FOR UPDATE clause. If a subselect is processed that includes a UNION. an exclusive lock is acquired to protect you from seeing uncommitted changes. Row locking is still done under repeatable read. An UPDATE lock on rows of the target table and a READ lock on the rows of the subselect table. Record Lock Duration (continued) SQL Statement Notes: 1. 4. 7. If the row is not updated or deleted. 3. This is true regardless of when or how the function was ended or interrupted (such as power failure. For a detailed explanation of isolation levels and locking. The following SQL data definition statements are guaranteed to be atomic: ALTER TABLE (See note 1) COMMENT ON (See note 2) 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 | | | | | | | | | | | Chapter 21. or COMMIT(*ALL). 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. the lock is reduced to *READ. COMMIT(*CS). or job cancel). see the section entitled ″Isolation Level″ in Chapter 1 of the DB2 UDB for AS/400 SQL Reference book. COMMIT Parameter (See note 6) Duration of Record Locks Lock Type Atomic Operations When running under COMMIT(*CHG). FOR READ ONLY. or if the processing of the query requires the use of a temporary result. That is. 2. A table or view can be locked exclusively in order to satisfy COMMIT(*ALL). the operations are processed one at a time. ADD COLUMN) v add constraints 2. For example. | | | 374 DB2 UDB for AS/400 SQL Programming V4R4 . so the entire SQL statement is not atomic. so the entire SQL statement is not atomic. The following data definition statements are not atomic because they involve more than one DB2 UDB for AS/400 database operation: CREATE ALIAS CREATE COLLECTION | | | CREATE DISTINCT TYPE CREATE FUNCTION CREATE PROCEDURE CREATE TABLE CREATE VIEW CREATE INDEX CREATE SCHEMA DROP ALIAS DROP COLLECTION DROP DISTINCT TYPE DROP FUNCTION DROP PROCEDURE DROP SCHEMA RENAME (See note 1) Notes: 1. as well as column definitions changed. 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. RENAME is atomic only if the name or the system name is changed. but the COMMENT ON or LABEL ON to each individual column or object will be atomic. so the entire SQL statement is not atomic. but before the member has been added. the tables are processed one at a time. If dependent views need to be dropped during DROP TABLE or DROP VIEW.Notes: 1. If constraints need to be added or removed. ALTER COLUMN. in the case of create statements. If multiple tables. When both are changed. a CREATE TABLE can be interrupted after the DB2 UDB for AS/400 physical file has been created. or users are specified for a GRANT or REVOKE statement. Therefore. the columns are processed one at a time. but the GRANT or REVOKE to each individual table will be atomic. 4. if an operation ends abnormally. the RENAME is not atomic. If multiple columns are specified for a COMMENT ON or LABEL ON statement. SQL packages. you may have to drop the collection again or use the CL command Delete Library (DLTLIB) to remove the remaining parts of the collection. 3. you may have to drop the object and then create it again. each dependent view is processed one at a time. In the case of a DROP COLLECTION statement. so the entire SQL statement is not atomic. as long as the type and functions do not already exist. user-defined types. v If DB2 UDB for AS/400 does not currently know whether a referential constraint or check constraint is valid. The saved versions can be restored onto any AS/400 system at some later time. If the information exists and the signature is unique. When an *SQLUDT object is restored for a user-defined type. If an index that implements a unique constraint is invalid. journal receivers. DB2 UDB for AS/400 Data Protection 375 . A unique constraint is a rule that guarantees that the values of a key are unique. the user-defined type is automatically added to the SYSTYPES catalog. the functions or procedures will also be added to SYSROUTINES and SYSPARMS when restored. Additionally. A referential constraint is a rule that all non-null values of foreign keys in a dependent table have a corresponding parent key in a parent table. the Edit Rebuild of Access Paths (EDTRBDAP) command can be used to display any indexes that currently require rebuild. The appropriate functions needed to cast between the user-defined type and the source type are also created. v Unique constraints are implemented with indexes. and check constraints. The Edit Check Pending Constraints (EDTCPCST) command can be used to display any indexes that currently require rebuild. SQL packages. or only objects changed since a given date and time to be saved. the constraint is considered to be in a check pending state. views. Save/Restore | | | | | | | | | | | | | | | | | | | | | | | The AS/400 save/restore functions are used to save tables. For more information on constraints see the DB2 UDB for AS/400 Database Programming book. and collections on disk (save file) or to some external media (tape or diskette). DML statements may be prevented until DB2 UDB for AS/400 has verified the validity of the constraint. referential. SQL procedures. user-defined functions. it is automatically added to the SYSROUTINES and SYSPARMS catalogs. 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. indexes. journals. external programs or service programs that were referenced on a CREATE PROCEDURE or CREATE FUNCTION statement may contain the information required to register the routine in SYSROUTINES. A check constraint is a rule that limits the values allowed in a column or group of columns. as long as the procedure or function does not already exist with the same signature. Certain operations (such as restore of the dependent table). DB2 UDB for AS/400 will enforce the validity of the constraint during any DML (data manipulation language) statement.Constraints DB2 UDB for AS/400 supports unique. All information needed to restore an object to its previous state is saved. This allows any number of copies of the SQL programs on different systems to access the same SQL package on the same Chapter 21. In this case. When a program that was created for an SQL procedure or a service program that was created for an SQL function or a sourced function is restored. Either a distributed SQL program or its associated SQL package can be saved and restored to any number of AS/400 systems. SQL programs created in QSYS will not be created as SQL procedures when restored. The save/restore function allows an entire collection. selected objects. cause the validity of the constraint to be unknown. however. view. The system automatically journals enough information in a system journal to limit the recovery time to the specified amount. checksums. All indexes on the system have a recovery option that specifies when an index should be rebuilt if necessary. A DROP operation always succeeds. 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. 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. the amount of time required to recover all indexes on the system is kept below a specified time.application server. v System managed index protection The EDTRCYAP CL command allows a user to instruct DB2 UDB for AS/400 to guarantee that in the event of a system or power failure. the catalog views in that collection will only reflect objects in the old collection. use the CL command Start Journal Access Path (STRJRNAP) to journal any index created by DB2 UDB for AS/400. journal receivers. The DB2 UDB for AS/400 functions also have a certain amount of tolerance to damage caused by disk errors or system errors. will appropriately reflect all objects. Attention: Restoring a collection to an existing library or to a collection that has a different name does not restore the journal. In the event that a disk error has damaged a small portion of the rows in a table. If the collection is restored to a collection with a different name. v Index rebuild All indexes on the system have a maintenance option that specifies when an index is maintained. In the event of a power failure or abnormal system failure. Damage Tolerance The AS/400 system provides several mechanisms to reduce or eliminate damage caused by disk errors. The catalog views in QSYS2. If the index is journaled. SQL package. mirroring. SQL packages cannot be restored to a different library. however. if indexes were not protected by one of the previously described techniques. the DB2 UDB for AS/400 database manager allows you to read rows still accessible. SQL indexes are created with an attribute of *IMMED maintenance. or IDDU dictionary (if one exists). You can. at least the table. For example. This ensures that should damage occur. SQL indexes are not journaled automatically. Index Recovery DB2 UDB for AS/400 supplies several functions to deal with index recovery. and RAID disks can all reduce the possibility of disk problems. however. regardless of the damage. v Journaling of indexes DB2 UDB for AS/400 supplies an index journaling function that makes it unnecessary to rebuild an entire index due to a power or system failure. All SQL indexes with an attribute of UNIQUE are created with a recovery attribute of *IPL 376 DB2 UDB for AS/400 SQL Programming V4R4 . or index can be deleted and restored or created again. 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). indexes. The operator can override the recovery options. Any indexes not previously saved and restored are automatically and asynchronously rebuilt by the database manager. views. 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. and parameters described in the catalog.(this means that these indexes are rebuilt before the OS/400 has been started). System/36 Environment functions. System/38 Environment CL commands. views. In the event of a restore when the indexes have also been saved. 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. and parameters in a collection. DB2 UDB for AS/400 Data Protection 377 . issuing a System/38 DLTF CL command or entering option 4 on a WRKF or WRKOBJ display. OS/400 CL commands. procedures. the operator can see a display showing indexes needing to be rebuilt and their recovery option. there is no need to rebuild the indexes. indexes. SQL packages. Effect of Various Functions on Catalogs Function Add constraint to table Remove of constraint from table Create object into collection Delete of object from collection Restore of object into collection Change of object long comment Change of object label (text) Change of object owner Move of object from a collection Move of object into collection Rename of object Effect on the Catalog Information added to catalog Related information removed from catalog Information added to catalog Related information removed from catalog Information added to catalog Comment updated in catalog Label updated in catalog Owner updated in catalog Related information removed from catalog Information added to catalog Name of object updated in catalog Chapter 21. During an IPL. issuing an OS/400 DLTF CL command. The integrity of the catalog is maintained whether objects in the collection are changed by SQL statements. deleting a table can be done by running an SQL DROP statement. For example. or any other product or utility on an AS/400 system. All other SQL indexes are created with the *AFTIPL recovery option (this means that after the operating system has been started. The database manager ensures that the information in the catalog is accurate at all times. SQL packages. Catalog Integrity Catalogs contain information about tables. Regardless of the interface used to delete the table. procedures. indexes are asynchronously rebuilt). 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. and indexes.User Auxiliary Storage Pool (ASP) An SQL collection can be created in a user ASP by using the ASP clause on the CREATE COLLECTION and CREATE SCHEMA statements. See the Backup and Recovery book and the Backup and Recovery book for more information on auxiliary storage pools. The CRTLIB command can also be used to create a library in a user ASP. That library can then be used to receive SQL tables. views. 378 DB2 UDB for AS/400 SQL Programming V4R4 . You cannot be sure that your output data is valid unless you use valid input data. For example: v Use input data that forces the program to run each of its branches. if the program updates a row. or deletes data from tables and views. v A test data structure. If your program only retrieves data from tables and views. See Chapter 2. 1999 379 . test as many of the paths through the program as possible. When your application creates. include both valid and not valid data to verify that the valid data is processed and the not valid data is detected. v Test the editing and validation routines your program uses. See the chapter on testing in the CL Programming for more information on debugging. See the chapter on testing in the CL Programmingbook for more information on debugging. changes. If your program updates. You need to be authorized to create tables and views. Again. you will probably want to test the application by using tables that contain test data. and create and run programs. If your application does not change data and the data exists in one or more production-level tables. To test the program thoroughly. access SQL data. you might consider using a view of the existing tables. that you use the CL command Start Debug (STRDBG) with UPDPROD(*NO) to assure that the production level data does not accidentally get changed. 1997. Give the program as many different combinations of input data as possible to verify that it correctly edits or validates that data. use input data that forces the program to encounter as many of the anticipated error conditions as possible. v Test input data. or deletes data. It is recommended. If your program verifies that input data is valid. you might consider using production-level data when testing your program. For example. © Copyright IBM Corp. Establishing a Test Environment Some things you need to test your program are: v Authorization. however. Getting Started with SQL for a description of how to create tables and views. Designing a Test Data Structure To test an application that accesses SQL data. The input data your program uses during testing should be valid data that represents as many possible input conditions as you can think of. You might have to refresh the data for subsequent tests. you might have to create test tables and views: v Test views of existing tables. v Be sure to test the program error routines.Chapter 22. It is also recommended that you use STRDBG command with UPDPROD(*NO) to assure that the production level data does not accidentally get changed. you should use test data to verify the running of the program. Testing SQL Statements in Application Programs This chapter describes how to establish a test environment for SQL statements in an application program and how to debug this program. inserts. select the row to see if it was updated correctly. v Check the results. v Test tables. In addition. Debugging your program with SQL statements is much the same as debugging your program without SQL statements. For example. references to high-level language statement numbers in debug mode must be taken from the compile listing. Authorization Before you can create a table. 380 DB2 UDB for AS/400 SQL Programming V4R4 . This return code is particularly useful when determining the cause of errors returned from the relational database operations performed on non-DB2 UDB for AS/400 system. The message is either a 4-digit code prefixed by SQL or a 5-digit code prefixed by SQ. A negative SQLCODE results in a diagnostic message. an SQLCODE of −204 results in a message of SQL0204. when SQL statements are run in a job in the debug mode. the SQLCODE value is zero. you must be authorized to create tables and to use the collection in which the table is to reside. The same error conditions will not produce the same SQLCODE. 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. For ILE program debugging. you must be authorized to create views and must have authorization to each table and view on which the view is based. The SQLSTATE is an additional return code provided in the SQLCA that identifies common error conditions among the different IBM relational database products. and an SQLCODE of 30000 results in a message of SQ30000. the database manager puts messages in the job log about how each SQL statement ran. precompile the program specifying DBGVIEW(*SOURCE) and then use the source-level debugger. view. or index. This message is an indication of the SQLCODE for the SQL statement. For more information on specific authorities required for any specific SQL statement. Testing Your SQL Application Programs There are two phases for testing DB2 UDB for AS/400 SQL applications: the program debug phase and the performance verification phase. and a completion message is issued.Also. The Program Debug Phase This test phase is done to ensure that the SQL queries are specified correctly and that the program is producing the correct results. see the DB2 UDB for AS/400 SQL Reference book. 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. you must have authority to create and run the programs you want to test. If the statement ran successfully. The same error condition on different relational database products will produce the same SQLSTATE. For non-ILE program debugging. A positive SQLCODE results in an informational message. However. If you want to create a view. you might want to use the CL command Create Duplicate Object (CRTDUPOBJ) to create a duplicate test table. Associated with a SQLCODE is a SQLSTATE. Testing SQL Statements in Application Programs 381 . DSPJOB The CL command Display Job (DSPJOB) with parameter OPTION(*OPNF) shows the indexes and tables being used by an application that is running in a job. when you run that same query on a database with large tables and appropriate indexes do not exist. Also. The test collection should have tables with the same names and composition as the production collection. The test environment should resemble the production environment as closely as possible. even if the job in not in debug. The performance of an SQL application is dependent on the attributes of the tables being accessed. Chapter 22. Using the DB2 UDB for AS/400 Predictive Query Governor” on page 391. The same indexes need to be available over the tables in both collections. It displays the objects and rows that are locked and the name of the job holding the lock. The number of rows and the distribution of values in the tables should be similar. and the pending DDL functions. the response time of the query is not affected by the availability of indexes. the number of rows being locked during a transaction. see “Chapter 23. However. DSPJOB with parameter OPTION(*CMTCTL) shows the isolation level that the program is running. CL Command Usage for SQL Application Performance Verification Verification of the performance of an SQL application can be done using the following commands: CHGQRYA The CL command Change Query Attribute (CHGQRYA) can be used to prevent users from running long queries. The actual isolation level. the response time for the queries can be very long. For information restricting query runtime using this command.The Performance Verification Phase This test phase verifies that the appropriate indexes are available and that the queries are coded in a manner that allows the database manager to resolve the queries in the expected response time. The isolation level displayed is the default isolation level. used for any SQL program. is specified on the COMMIT parameter of the CRTSQLxxx command. This stops the building of temporary indexes or other resource intensive query operations. This command can be used to set the parameter Query Time Limit (QRYTIMLMT) to prevent a query from starting whose estimated number of elapsed seconds is longer than the specified number of seconds. a query which is canceled because of the query time limit creates performance information messages in the job log. DSPJOB with parameter OPTION(*JOBLCK) can be used to analyze object and row lock contention. If you use small tables. the processing unit and page resource usage for running each SQL statement can be determined. SQL package. The ampersand variables (&1. v CPI432F Access path suggestion for file &1. or service program. TRCJOB Performance Information Messages You can evaluate the structure and performance of the given SQL statements in a program using informational messages put in the job log by the database manager. CPI432A Query optimizer timed out. The trace job output lists the indexes and files being used when the initial database open processing occurs for each SQL statement. and a list of the command parameters used to precompile the source member for the object. CPI432C All access paths were considered for file &1. v CPI4331 &6 tasks used for parallel index created over file &1. v v v v v v v CPI4327 File &1 processed in join position 1. CPI432D Additional access path reason codes were used. the access plans used during the running of the statement. v CPI4326 File &1 processed in join position &X.PRTSQLINF The CL command Print Structured Query Language Information (PRTSQLINF) allows you to print information about the embedded SQL statements in a program. v CPI4332 &1 host variables used in query. For more information on printing information about SQL Statements. The CL command Trace Job (TRCJOB) can be used to capture a trace of the program modules being run for an SQL application. The messages are: v CPI4321 Access path built for file &1. The database manager may send any of the following messages when appropriate. &X) are replacement variables that contain either an object name or some other substitution value when the message appears in the job log. see the PRTSQLINF section in “Appendix D. v CPI4333 Hashing algorithm used to process join. v CPI4323 The OS/400 query access plan has been rebuilt. v CPI432E Selection fields mapped to different attributes. DB2 UDB for AS/400 CL Command Descriptions” on page 645. v CPI4322 Access path built from keyed file &1. v CPI4324 Temporary file built for file &1. The messages are issued for an SQL program or interactive SQL when running in the debug mode. v CPI4334 Query implemented as reusable ODP. CPI4329 Arrival sequence access was used for file &1. The information includes the SQL statements. v CPI4330 &6 tasks used for parallel &10 scan of file &1. v CPI4325 Temporary result file built for query. Also. 382 DB2 UDB for AS/400 SQL Programming V4R4 . CPI432B Subselects processed as join query. CPI4328 Access path &4 was used by query. &1 Access path(s) used for bitmap processing of file &2. Testing SQL Statements in Application Programs 383 . SQL7915 Access plan for SQL statement has been built. The new access path is created by reading all of the records in the specified file. The actual message help is more complete and should be used when trying to determine the meaning and responses for each message. Chapter 22. in some cases. SQL7914 ODP not deleted. v With key fields named in the message help. SQL7917 Access plan not updated. The time required to create an access path on each run of a query can be significant. These messages provide feedback on how a query was run and. v SQL7939 Data conversion required on INSERT or UPDATE. CPI4345 Temporary distributed result file &4 built for query. CPI4342 Performing distributed join for query. The time at which the message is sent does not necessarily indicate when the associated function was performed. Query options retrieved from Library &1. The messages contain message help that provides information about the cause for the message. The possible user action for each message follows: CPI4321 . v With the ascending or descending sequencing specified in the message help. SQL7913 ODP deleted. SQL7916 Blocking used for query. Temporary hash table built for hash join step &1. Consider creating a logical file (CRTLF) or an SQL index (CREATE INDEX SQL statement): v Over the file named in the message help.Access path built for file &1. CPI433A Unable to retrieve query options file. SQL7910 SQL cursors closed. SQL7911 ODP reused. Some messages are sent altogether at the start of a query run. v SQL7918 Reusable ODP deleted. The causes and user responses for the following messages are paraphrased. v SQL7919 Data conversion required on FETCH or embedded SELECT. SQL7912 ODP created.| | | v v v v v v v v v v v v v v v v v v CPI4335 CPI4336 CPI4337 CPI4338 CPI4339 Optimizer debug messages for hash join step &1 follow: Group processing generated. This message indicates that a temporary access path was created to process the query. indicate the improvements that can be made to help the query run faster. CPI4341 Performing distributed query. CPI433C Library &1 not found. object name references. and possible user responses. CPI4322 .Access path built from keyed file &1.v With the sort sequence table specified in the message help. Consider creating the logical file with select or omit criteria that either match or partially match the query’s predicates involving constants. this message will be sent when an SQL package is run the first time after a restore. this message is sent when the queried file environment has changed. then the optimizer may create a new access path to get faster performance when accessing the data.Temporary file built for file &1. Excessive rebuilds may indicate a possible application design problem or inefficient database management practices.The OS/400 query access plan has been rebuilt. and a new access plan is created. CPI4324 . 384 DB2 UDB for AS/400 SQL Programming V4R4 . This message can be sent for a variety of reasons. If the record selection results in roughly 20% of the records or more to be returned. replacing the old one. However. this action should not take a significant amount of time or resource because only a subset of the data in the file needs to be read. using the most current state of the database without user intervention. For more detail. For certain queries. Sometimes even faster performance can be achieved by creating a logical file or SQL index that satisfies the access path requirement stated in the message help. that warrants an implicit rebuild. An access plan contains the instructions for how a query is to be run and lists the access paths for running the query. The specific reason is provided in the message help. making the current access plan obsolete. The database manager will consider using select or omit logical files even though they are not explicitly specified on the query. excessive rebuilds should be avoided because extra query processing will occur. see the previous message. Most of the time. CPI4321. It allows a query to be run as efficiently as possible. An example of the file environment changing is when an access path required by the query no longer exists on the system. CPI4323 . The process of again optimizing the query and building a new access plan at runtime is a function of DB2 UDB for AS/400. If a needed access path is no longer available. This message indicates that a temporary access path was created from the access path of a keyed file. The infrequent appearance of this message is not a cause for action. The new access path minimizes the amount of data that needs to be read. This might occur when a query has an ordering field as a key field for an access path. or anytime the optimizer detects that a change has occurred (such as a new index was created). and the only record selection specified uses a different field. For example. the query is again optimized. Generally. the optimizer may decide to create an access path even when an existing one can be used. When a query is changed as suggested above. The message help contains the reason why a temporary result file is required. Testing SQL Statements in Application Programs 385 . The improved efficiency of the join order will. Other queries that have many records to be copied into the temporary result file can take a significant amount of time. creating a temporary result file provides the fastest way to run a query. consider one of the following: v Add an additional column from a different file to the clause. in most cases. Consider using an INSERT statement with a subselect to select only the records that are required into a physical file. the order in which the files are specified will help determine the join Chapter 22. A temporary result file was created to contain the intermediate results of the query. This message provides the join position of the specified file when an access path is used to access the file’s data. A temporary result table is used to allow the system to order the files in the most efficient join order. the query may be slow. In some cases.Temporary result file built for query.Before the query processing could begin. Join position pertains to the order in which the files are joined. For example. One way to do this is by breaking the query into multiple steps. usually less than 1000 rows. The order in which files are joined can significantly influence the efficiency of a query. The system orders the files in the most efficient join order. CPI4326 . consider changing the query so that a temporary result file is not required. make up for any loss of efficiency caused by the temporary result.File &1 processed in join position &11. then the row selection part of the query’s implementation should not take a significant amount of resource and time. However if the query is taking more time and resources than can be allowed. and then use that file’s records for the rest of the query. if two files are being joined. CPI4325 . If the referenced file is a large file. If the GROUP BY or ORDER BY clause is specified where all the columns in the clause are referenced from one of the files in the query. The message help contains the reason why this message was sent. the file with the fewest selected records should be in join position 1 and the file with the larger number of selected records should be in join position 2. that file becomes the first file in the final join order. However. if the query is taking more time and resources than can be allowed. To improve performance. If the query uses the JOIN clause or refers to a join logical file within the file specifications. a temporary result table may be used to change the join order. If the specified file selects few rows. v Specify the ALWCPYDTA(*OPTIMIZE) parameter on the ORDER BY clause. consider changing the query so that a temporary file is not required. the data in the specified file had to be copied into a temporary physical file to simplify running the query. The system processes the join of two files with different numbers of selected records more efficiently when the file with the smaller number of selected records is joined to the file with the larger number of selected records. Generally. The records were scanned sequentially in arrival sequence. To force the use of an existing access path. if necessary. CPI432A . You may want to delete any access paths that are no longer needed.order the optimizer uses. CPI4328 . The message help contains a list of access paths that were considered before the optimizer exceeded the estimated time.Access path of file &4 was used by query. The reason the access path was used is given in the message help. CPI4327 . 386 DB2 UDB for AS/400 SQL Programming V4R4 . the more records in the files. This message names an existing access path that was used by the query. the greater the number of access paths that will be considered. or if either a left outer or exception join is specified using the JOIN clause. for information on join position and join performance tips. 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 optimizer uses the current best method for running the query. The optimizer cannot change the file join order if the query contains a join logical file. When the estimated time to run the query is exceeded. CPI4326. 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. or an access path will have to be created. See the previous message. specify the logical file associated with the access path as the file to be queried. change the ORDER BY clause of the query to specify the first key field of the access path. CPI4329 . The use of an access path may improve the performance of the query if record selection is specified. No access path was used to access the data in the specified file. Either an access path has been found to get the best performance. To ensure that an access path is considered for optimization. If an access path does not exist.File &1 processed in join position 1. You should only create an access path if the record selection (WHERE clause) selects 20% or fewer records in the file. 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. The optimizer will consider the access path of the file specified on the query or SQL statement first.Arrival sequence access was used for file &1. Remember that SQL indexes cannot be queried. you may want to create one whose key field matches one of the fields in the record selection.Query optimizer timed out for file &1. 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 22. Testing SQL Statements in Application Programs 387 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. Performance Information Messages and Open Data Paths Several of the following SQL run-time messages refer to open data paths. An open data path (ODP) definition is an internal object that is created when a cursor is opened or when other SQL statements are run. It provides a direct link to the data so that I/O operations can occur. ODPs are used on OPEN, INSERT, UPDATE, DELETE, and SELECT INTO statements to perform their respective operations on the data. Even though SQL cursors are closed and SQL statements have already been run, the database manager in many cases will save the associated ODPs of the SQL operations to reuse them the next time the statement is run. So an SQL CLOSE statement may close the SQL cursor but leave the ODP available to be used again the next time the cursor is opened. This can significantly reduce the processing and response time in running SQL statements. The ability to reuse ODPs when SQL statements are run repeatedly is an important consideration in achieving faster performance. The following informational messages are issued at SQL run time: SQL7910 - All SQL cursors closed. This message is sent when the job’s call stack no longer contains a program that has run an SQL statement. Unless CLOSQLCSR(*ENDJOB) or CLOSQLCSR(*ENDACTGRP) was specified, the SQL environment for reusing ODPs across program calls exists only until the active programs that ran the SQL statements complete. Except for ODPs associated with *ENDJOB or *ENDACTGRP cursors, all ODPs are deleted when all the SQL programs on the call stack complete and the SQL environment is exited. This completion process includes closing of cursors, the deletion of ODPs, the removal of prepared statements, and the release of locks. Putting an SQL statement that can be run in the first program of an application keeps the SQL environment active for the duration of that application. This allows ODPs in other SQL programs to be reused when the programs are repeatedly called. CLOSQLCSR(*ENDJOB) or CLOSQLCSR(*ENDACTGRP) can also be specified. SQL7911 - ODP reused. This message indicates that the last time the statement was run or when a CLOSE statement was run for this cursor, the ODP was not deleted. It will now be used again. This should be an indication of very efficient use of resources by eliminating unnecessary OPEN and CLOSE operations. 388 DB2 UDB for AS/400 SQL Programming V4R4 SQL7912 - ODP created. No ODP was found that could be used again. The first time that the statement is run or the cursor is opened for a process, an ODP will always have to be created. However, if this message appears on every run of the statement or open of the cursor, the tips recommended in “Improving Performance by Retaining Cursor Positions for Non-ILE Program Calls” on page 467 should be applied to this application. SQL7913 - ODP deleted. For a program that is run only once per job, this message could be normal. However, if this message appears on every run of the statement or open of the cursor, then the tips recommended in “Improving Performance by Retaining Cursor Positions for Non-ILE Program Calls” on page 467 should be applied to this application. SQL7914 - ODP not deleted. If the statement is rerun or the cursor is opened again, the ODP should be available again for use. SQL7915 - Access plan for SQL statement has been built. The DB2 UDB for AS/400 precompilers allow the creation of the program objects even when required tables are missing. In this case the binding of the access plan is done when the program is first run. This message indicates that an access plan was created and successfully stored in the program object. SQL7916 - Blocking used for query. SQL will request multiple records from the database manager when running this statement instead of requesting one record at a time. SQL7917 - Access plan not updated. The database manager rebuilt the access plan for this statement, but the program could not be updated with the new access plan. Another job is currently running the program that has a shared lock on the access plan of the program. The program cannot be updated with the new access plan until the job can obtain an exclusive lock on the access plan of the program. The exclusive lock cannot be obtained until the shared lock is released. The statement will still run and the new access plan will be used; however, the access plan will continue to be rebuilt when the statement is run until the program is updated. SQL7918 - Reusable ODP deleted. A reusable ODP exists for this statement, but either the job’s library list or override specifications have changed the query. Chapter 22. Testing SQL Statements in Application Programs 389 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. 390 DB2 UDB for AS/400 SQL Programming V4R4 Chapter 23. Using the DB2 UDB for AS/400 Predictive Query Governor The DB2 UDB for AS/400 Predictive Query Governor (governor) can stop the initiation of a query if the query’s estimated or predicted runtime (elapsed execution time) is excessive. The governor acts before a query is run instead of while a query is run. The governor can be used in any interactive or batch job on the AS/400. It can be used with all DB2 UDB for AS/400 query interfaces and is not limited to use with SQL queries. | | | | | | | | | | The ability of the governor to predict and stop queries before they are started is important because: v Operating a long-running query and abnormally ending the query before obtaining any results wastes system resources. v Some operations within a query cannot be interrupted by the End Request (ENDRQS) CL command. The creation of a temporary keyed access path or a query using a column function without a GROUP BY clause are two examples of these types of queries. It is important to not start these operations if they will take longer than the user wants to wait. The governor in DB2 UDB for AS/400 is based on the estimated runtime for a query. If the query’s estimated runtime exceeds the user defined time limit, the initiation of the query can be stopped. The time limit is user-defined and can be specified in one of three ways: v Using the Query Time Limit (QRYTIMLMT) parameter on the Change Query Attributes (CHGQRYA) CL command. v Setting the QQRYTIMLMT system value and allowing each job to use the value *SYSVAL on the CHGQRYA CL command. v Setting the Query Time Limit option in the “Query Options File QAQQINI” on page 543. The governor works in conjunction with the query optimizer. When a user requests DB2 UDB for AS/400 to run a query, the following occurs: 1. The query access plan is evaluated by the optimizer. As part of the evaluation, the optimizer predicts or estimates the runtime for the query. This helps determine the best way to access and retrieve the data for the query. 2. The estimated runtime is compared against the user-defined query time limit currently in effect for the job or user session. 3. If the predicted runtime for the query is less than or equal to the query time limit, the query governor lets the query run without interruption and no message is sent to the user. 4. If the query time limit is exceeded, inquiry message CPA4259 is sent to the user. The message states that the estimated query processing time of XX seconds exceeds the time limit of YY seconds. Note: A default reply can be established for this message so that the user does not have the option to reply to the message, and the query request is always ended. 5. If a default message reply is not used, the user chooses to do one of the following: © Copyright IBM Corp. 1997, 1999 | | | | | | 391 v End the query request before it is actually run. v Continue and run the query even though the predicted runtime exceeds the governor time limit. 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. General Implementation Considerations | | | | | | | | | It is important to remember that the time limit generated by the optimizer is only an estimate. The actual query runtime could be more or less than the estimate, but the value of the two should be about the same. When setting the time limit for the entire system, it is usually best to set the limit to the maximum allowable time that any query should be allowed to run. By setting the limit too low you will run the risk of preventing some queries from completing and thus preventing the application from successfully finishing. There are many functions that use the query component to internally perform query requests. These requests will also be compared to the user-defined time limit. User Application Implementation Considerations | | | | | | | | | | | | | The time limit specified for the governor is established on a per-job basis by the query optimizer. The query optimizer determines the time limit using the following process: 1. The query optimizer attempts to extract the time limit from the QRYTIMLMT parameter on the CHGQRYA command. 2. If the time limit is not explicitly specified on the CHGQRYA command, it uses the query options file that is in use for this job. 3. If the time limit parameter in the query options file has been set to *DEFAULT, then the value that is stored in the QQRYTIMLMT system value is used for this job or user session. You can also set the time limit for a job other than the current job. You do this by using the JOB parameter on the CHGQRYA command to specify either a query options file library to search (QRYOPTLIB) or a specific QRYTIMLMT for that job. After the source job runs the CHGQRYA command, effects of the governor on the target job is not dependent upon the source job. The query time limit remains in effect for the duration of the job or user session, or until the time limit is changed by a CHGQRYA command. Under program control, a user could be given different query time limits depending on the application function being performed, the time of day, or the amount of system resources available. This provides a significant amount of flexibility when trying to balance system resources with temporary query requirements. 392 DB2 UDB for AS/400 SQL Programming V4R4 Controlling the Default Reply to the Inquiry Message The system administrator can control whether the interactive user has the option of ignoring the database query inquiry message by using the CHGJOB CL command as follows: v If a value of *DFT is specified for the INQMSGRPY parameter of the CHGJOB CL command, the interactive user does not see the inquiry messages and the query is canceled immediately. v If a value of *RQD is specified for the INQMSGRPY parameter of the CHGJOB CL command, the interactive user sees the inquiry and must reply to the inquiry. v If a value of *SYSRPYL is specified for the INQMSGRPY parameter of the CHGJOB CL command, a system reply list is used to determine whether the interactive user sees the inquiry and whether a reply is necessary. For more information on the *SYSRPYL parameter, see the CL Reference (Abridged) book. The system reply list entries can be used to customize different default replies based on user profile name, user id, or process names. The fully qualified job name is available in the message data for inquiry message CPA4259. This will allow the keyword CMPDTA to be used to select the system reply list entry that applies to the process or user profile. The user profile name is 10 characters long and starts at position 51. The process name is 10 character long and starts at position 27. The following example will add a reply list element that will cause the default reply of C to cancel any requests for jobs whose user profile is ’QPGMR’. ADDRPYLE SEQNBR(56) MSGID(CPA4259) CMPDTA(QPGMR 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 SEQNBR(57) MSGID(CPA4259) CMPDTA(QPADEV0011 27) RPY(C) Using the Governor for Performance Testing The query governor lets you optimize performance without having to run through several iterations of the query. If the query time limit is set to zero ( QRYTIMLMT(0) ) with the CHGQRYA command, the inquiry message is always sent to the user saying the estimated time exceeds the query time limit. The programmer can prompt for message help on the inquiry message and find the same information which one can see from the PRTSQLINF (Print SQL Information) command. Additionally, if the query is canceled, the query optimizer evaluates the access plan and sends the optimizer tuning messages to the joblog. This occurs even if the job is not in debug mode. The user or a programmer can then review the optimizer tuning messages in the joblog to see if additional tuning is needed to obtain optimal query performance. Minimal system resources are used because the actual query of the data is never actually done. If the files to be queried contain a large number of records, this represents a significant savings in system resources. | | | | | | | Be careful when you use this technique for performance testing, because all query requests will be stopped before they are run. This is especially important for a query that cannot be implemented in a single query step. For these types of queries, separate multiple query requests are issued, and then their results are accumulated before returning the final results. Stopping the query in one of these intermediate steps gives you only the performance information that relates to that intermediate step, and not for the entire query. Chapter 23. Using the DB2 UDB for AS/400 Predictive Query Governor 393 Examples | | | | | | To set the query time limit for the current job or user session using query options file QAQQINI, specify QRYOPTLIB parameter on the CHGQRYA command to a user library where the QAQQINI file exists with the parameter set to QUERY_TIME_LIMIT, and the value set to a valid query time limit. For more information on setting the query options file, see “Query Options File QAQQINI” on page 543. 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) This sets the query time limit at 45 seconds for job 123456/USERNAME/JOBNAME. If job 123456/USERNAME/JOBNAME tries to run a query with an estimated runtime equal to or less than 45 seconds the query runs without interruption. If the estimated runtime for the query is greater than 45 seconds, for example 50 seconds, a message would be sent to the user stating that the estimated runtime of 50 seconds exceeds the query time limit of 45 seconds. The time limit remains in effect for the duration of job 123456/USERNAME/JOBNAME, or until the time limit for job 123456/USERNAME/JOBNAME is changed by the CHGQRYA command. To set or change the query time limit to the QQRYTIMLMT system value, use the following CHGQRYA command: CHGQRYA QRYTIMLMT(*SYSVAL) The QQRYTIMLMT system value is used for duration of the job or user session, or until the time limit is changed by the CHGQRYA command. This is the default behavior for the CHGQRYA command. 394 DB2 UDB for AS/400 SQL Programming V4R4 Chapter 24. DB2 UDB for AS/400 Data Management and Query Optimizer Tips | | | | | | | | | | | This chapter provides guidelines for designing queries that will perform and will use system resources more efficiently. This chapter covers queries that are optimized by the query optimizer and includes interfaces such as SQL, OPNQRYF, and QUERY/400 queries. 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 queries 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 UDB 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 UDB 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 UDB 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. General Optimization Tips | Here are some tips to help your queries run as fast as possible: v Create indexes whose leftmost key fields match your selection predicates to help supply the optimizer with selectivity values (key range estimates). v For join queries, create indexes that match your join fields to help the optimizer determine the average number of matching rows. v Minimize extraneous mapping by specifying only fields of interest on the query. For example, in SQL, avoid SELECT* in favor of FOR FETCH ONLY on read-only cursors. v If your queries often use arrival sequence, use the RGZPFM (Reorganize Physical File Member) command to remove deleted rows from tables or the CHGPF (Change Physical File) REUSEDLT (*YES) command to reuse deleted rows. For embedded SQL, consider using the following precompile options: v Specify ALWCPYDTA(*OPTIMIZE) to allow the query optimizer to create temporary copies of data if better performance can be obtained. v Use CLOSWLCSR(*ENDJOB) or CLOSQLCSR(*ENDACTGRP) to allow open data paths to remain open for future invocations. v Specify DLYPRP(*YES) to delay SQL statement validation until an OPEN, EXECUTE, or DESCRIBE statement is run. This option improves performance by eliminating redundant validation. v Use ALWBLK(*ALLREAD) to allow record blocking for read-only cursors. © Copyright IBM Corp. 1997, 1999 | 395 | For OPNQRYF (Open Query File) queries, consider using the following parameters: v Use ALWCPYDTA(*OPTIMIZE) to let the query optimizer create temporary copies of data if it can obtain better performance by doing so. v Use OPTIMIZE(*FIRSTIO) to bias the optimizer to use an existing index instead of creating a temporary index. Data Management Methods This section introduces the fundamental techniques used by DB2 UDB for AS/400 and the AS/400 Licensed Internal Code to access data. 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. Sequential Access Path A sequential access path uses the order of rows as they are stored in the table to locate data specified in a query. Processing tables using the sequential access path is similar to processing sequential or direct files on traditional systems. Keyed Sequence Access Path A keyed sequence access path provides access to a table that is arranged according to the contents of key fields (indexes). The keyed sequence is the order in which rows are retrieved. The access path is automatically maintained whenever rows are added to or deleted from the table, or whenever the contents of the index columns are changed. The best example of a keyed sequence access path is an index created using the CREATE INDEX statement or a logical file created using the CRTLF command. Columns that are good candidates for creating keyed sequence access paths are: v Those frequently referenced in row selection predicates. v Those frequently referenced in grouping or ordering. v Those used to join tables (see “Join Optimization” on page 426). | | Encoded Vector Access Paths An encoded vector access path provides access to a database file by assigning codes to distinct key values and then representing these values in an array. The elements of the array can be 1, 2, or 4 bytes in length, depending on the number of distinct values that must be represented. Because of their compact size and relative simplicity, encoded vector access paths provide for faster scans that can be more easily processed in parallel. You create encoded vector access paths by using the SQL CREATE INDEX statement. For more information about accelerating your queries with encoded , go to the DB2 for AS/400 web pages. vector indexes For a further description of access paths, refer to the Data Management book. 396 DB2 UDB for AS/400 SQL Programming V4R4 Access Method The Licensed Internal Code and DB2 UDB 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 17, 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 399) v Parallel pre-fetch method (page 401) v Key selection method (page 404) v Key positioning method (page 406) v Parallel table or index pre-load (page 413) v Index-from-index method (page 414) v Index only access method (page 412) v Hashing method (page 415) v Bitmap processing method (page 416) The DB2 UDB 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. 17. An interrupt that occurs when a program refers to a 4K-byte page that is not in main storage. Chapter 24. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 397 ┌───────────────────┐ │ QUERY │ └─────────┬─────────┘ │ ┌────────────┬─────┴─────┬────────────┐ │ │ │ │ │ │ │ │ ┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ │ │ │ │ │ │ │ │ │ CPU │ │ CPU │ │ CPU │ │ CPU │ │ │ │ │ │ │ │ │ └───┬───┘ └───┬───┘ └───┬───┘ └───┬───┘ │ │ │ │ └────────────┴─────┬─────┴────────────┘ │ ┌─────────────┴──────────────┐ │ │ │ SHARED MEMORY │ │ │ └────────────────────────────┘ Figure 13. Database Symmetric Multiprocessing The following methods are available to the optimizer once the DB2 UDB Symmetric Multiprocessing feature has been installed on your system: v Parallel data space scan method (page 402) v Parallel key selection method (page 405) v Parallel key positioning method (page 410) v Parallel index only access method (parallel and non-parallel) (page 412) v Parallel hashing method (parallel and non-parallel) (page “Hashing Access Method” on page 415) v Parallel bitmap processing method (page 416) Ordering An ORDER BY clause (or OPNQRYF KEYFLD parameter) 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. Enabling Parallel Processing | | | | The application or user must enable parallel processing for queries; the optimizer does not automatically use parallelism as the chosen access method. You can use the system-value QQRYDEGREE, the query options file, and the DEGREE parameter on the Change Query Attributes (CHGQRYA) command to control the 398 DB2 UDB for AS/400 SQL Programming V4R4 | | degree of parallelism that the query optimizer uses. See “Controlling Parallel Processing” on page 473 for information on how to control parallel processing. 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. Automatic Data Spreading DB2 UDB for AS/400 automatically spreads the data across the disk devices available in the auxiliary storage pool (ASP) where the data is allocated. This ensures that the data is spread without user intervention. The spreading allows the database manager to easily process the blocks of records on different disk devices in parallel. Even though DB2 UDB for AS/400 spreads data across disk devices within an ASP, sometimes the allocation of the data extents (contiguous sets of data) might not be spread evenly. This occurs when there is uneven allocation of space on the devices, or when a new device is added to the ASP. The allocation of the data space may be spread again by saving, deleting, and then restoring the table. Dataspace Scan Access Method | | | | | The rows in the table are processed in no guaranteed order. If you want the result in a particular sequence, you must specify the ORDER BY clause (or OPNQRYF KEYFLD parameter). All rows in the table are read. The selection criteria is applied to each row, and only the rows that match the criteria are returned to the calling application. Dataspace scan can be very efficient for the following reasons: v It minimizes the number of page I/O operations because all rows in a given page are processed, and once the page is in main storage, the page is not retrieved again. v The database manager can easily predict the sequence of pages from the dataspace for retrieval. For this reason, the database manager can schedule asynchronous I/O of the pages into main storage from auxiliary storage. This is commonly referred to as pre-fetching. This is done so that the page is available in main storage when the database manager needs to access the data. This selection method is very good when a large percentage of the rows are to be selected. A large percentage is generally 20% or more. | | | | | | | Dataspace scan processing can be adversely affected when rows are selected from a table that contains deleted rows. This is because the delete operation only marks rows as deleted. For dataspace scan processing, the database manager reads all of the deleted rows, even though none of the deleted rows are ever selected. You should use the Reorganize Physical File Member (RGZPFM) CL command to eliminate deleted rows. Specifying REUSEDLT(*YES) on the physical file can also reuse the deleted record space. SQL tables are created with REUSEDLT(*YES). Chapter 24. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 399 Dataspace scan processing is not very efficient when a small percentage of rows in the table will be selected. Because all rows in the table are examined, this leads to unnecessary use of I/O and processing unit resources. The messages created by the PRTSQLINF CL command to describe a query in an SQL program which is using the dataspace selection method would appear as follows: SQL4010 Arrival sequence access for file 1. 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 The dataspace entry algorithm is as follows: DO UNTIL END OF FILE 1. Calculate a search limit. This limit is usually the number of records which are already in active memory, or have already had an I/O request done to be loaded into memory. 2. DO UNTIL (search limit reached or record selection criteria is TRUE) a. Address the next (or first) record b. Evaluate any selection criteria which does not require a derived value directly for the dataspace record. END 3. IF the selection is true THEN a. Map all column values to an internal buffer, performing all derived operations. b. Copy the values from the internal buffer into the user's answer buffer. ELSE No operation END 400 DB2 UDB for AS/400 SQL Programming V4R4 The dataspace entry selection algorithm provides better performance than intermediate buffer selection for two reasons: v Data movement and computations are only done on records which are selected. 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 UDB 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. Parallel Pre-Fetch Access Method DB2 UDB for AS/400 can also use parallel pre-fetch processing to shorten the processing time required for long-running I/O-bound dataspace scan queries. | | | | | | | | This method has the same characteristics as the dataspace scan method; except that the I/O processing is done in parallel. This is accomplished by starting multiple input streams for the table to pre-fetch the data. This method is most effective when the following are true: v The data is spread across multiple disk devices. v The query is not CPU-processing-intensive. v There is an ample amount of main storage available to hold the data collected from every input stream. Chapter 24. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 401 | | | | | | | As mentioned previously, DB2 UDB 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 database manager uses tasks to retrieve data from different disk devices. Usually the request is for an entire extent (contiguous set of data). This improves performance because the disk device can use smooth 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 UDB 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, the query option file, or by the DEGREE parameter on the Change Query Attributes (CHGQRYA) command. See “Controlling Parallel Processing” on page 473 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 UDB 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 dataspace pre-fetch used. 402 DB2 UDB for AS/400 SQL Programming V4R4 Parallel Data Space Scan Method (available only when the DB2 UDB Symmetric Multiprocessing feature is installed) DB2 UDB 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 into tasks that can be run on the multiple processors simultaneously. All selection and column processing is performed in the task. The application’s 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 previously, DB2 UDB 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 job’s 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 must be enabled either by the system value QQRYDEGREE, the query option file, or by the DEGREE parameter on the Change Query Attributes (CHGQRYA) command. See “Controlling Parallel Processing” on page 473 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 426. | | | | | | | | | | v Backward scrolling. For example, parallel data space scan cannot normally be used for queries defined by the Open Query File (OPNQRYF) command, which specify ALWCPYDTA(*YES) or ALWCPYDTA(*NO), 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 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. OPNQRYF can be defined as not scrollable by specifying the *OPTIMIZE parameter value for the ALWCPYDTA parameter, which enbles the usage of most of the parallel access methods. Chapter 24. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 403 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. 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. Key Selection Access Method This access method requires keyed sequence access paths. The entire index is read and any selection criteria that references the key columns of the index is applied against the index. The advantage of this method is that the dataspace is only accessed to retrieve rows that satisfy the selection criteria applied against the index. Any additional selection not performed through the key selection method is performed at the dataspace level. The key selection access method can be very expensive if the search condition applies to a large number of rows because: v The whole index is processed. v For every key selected from the index, a random I/O to the dataspace occurs. Normally, the optimizer would choose to use dataspace scan processing when the search condition applies to a large number of rows. The optimizer only chooses the key selection method if less than 20% of the keys are selected or if an operation forces the use of an index. Options that might force the use of an index include: v Ordering v Grouping v Joining | | | | | | | | In these cases, the optimizer may choose to create a temporary index rather than use an existing index. When the optimizer creates a temporary index, it uses a 32K page size. An index created using a CREATE INDEX statement or the CRTLF command normally uses only a 4K page size. The optimizer also processes as much of the selection as possible while building the temporary index. Nearly all temporary indexes built by the optimizer are select/omit or sparse indexes. Finally, the optimizer can use multiple parallel tasks when creating the index. The page size difference, corresponding performance improvement from swapping in fewer pages, 404 DB2 UDB for AS/400 SQL Programming V4R4 or *CS When a query specifies a select/omit index and the optimizer decides to build a temporary index. Parallel Key Selection Access Method (available only when the DB2 UDB Symmetric Multiprocessing feature is installed) For the parallel key selection access method.WORKDEPT) DECLARE BROWSE2 CURSOR FOR SELECT * FROM EMPLOYEE WHERE WORKDEPT = 'E01' OPTIMIZE FOR 99999 ROWS OPNQRYF example: OPNQRYF FILE((EMPLOYEE)) QRYSLT('WORKDEPT *EQ ''E01''') If the optimizer chooses to run this query in parallel with a degree of four. *CHG. Each partition is processed by a separate task just as in the key selection access method. If key selection access method is used because the query specified ordering (an index was required) the query performance might be improved by using the following parameters to allow the ordering to be done with the query sort. the following combinations of precompiler parameters: – ALWCPYDTA(*OPTIMIZE). Dataspace selection is used for building of temporary keyed access paths. the following parameters: – *ALWCPYDTA(*OPTIMIZE) and COMMIT(*NO) – ALWCPYDTA(*OPTIMIZE) and COMMIT(*YES) and the commitment control level is started with a commit level of *NONE. all of the selection from the select/omit index is put into the temporary index after any applicable selection from the query. ALWBLK(*ALLREAD). Key partitions that contain a larger portion of the existing keys from the index are further split as processing of other partitions complete. The following example illustrates a query where the optimizer could choose the key selection method: CREATE INDEX X1 ON EMPLOYEE(LASTNAME. the possible key values are logically partitioned. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 405 .| | | | | | | | | | | | | | | | | and the ability to use parallel tasks to create the index may be enough to overcome the overhead of creating an index. v For SQL. and COMMIT(*CHG or *CS) – ALWCPYDTA(*OPTIMIZE) and COMMIT(*NONE) v For OPNQRYF. this method cannot be used by the optimizer if the index is being used for ordering. 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' Chapter 24. Because the keys are not processed in order. The number of partitions processed concurrently is determined by the query optimizer. parallel key selection cannot be used for queries defined by the Open Query File (OPNQRYF) command which specify ALWCPYDTA(*YES) or ALWCPYDTA(*NO). After the first two partitions are finished. OPNQRYF can be defined as not scrollable by specifying the *OPTIMIZE parameter value for the ALWCPYDTA parameter. Key Positioning Access Method This access method is very similar to the key selection access method. You should run the job in a shared pool with *CALC paging option as this will cause more efficient use of active memory. 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. the remaining key values in the last two might be further split. | | | | | Parallel key selection requires that SMP parallel processing be enabled either by the system value QQRYDEGREE. For example. v Update or delete capabilitiy. such as a sort or hash operation. See “Nested Loop Join Implementation” on page 426. which enables the usage of most of the parallel access methods. v Restoration of the cursor position (for instance. SQL defined queries that are not defined as scrollable can use this method. Because key 406 DB2 UDB for AS/400 SQL Programming V4R4 . selection is against the index directly on a range of keys that match some or all of the selection criteria. processing starts at the beginning of the index and continues to the end. Any selection not performed through key positioning or key selection is performed at the dataspace level. the query options file. In the key positioning access method. They both require a keyed sequence access path. For more information on the paging option see the “Automatic System Tuning” section of the Work Management book.If there were fewer keys in the first and second partition. | | | | | | | | | | | | | | | v Backward scrolling. This is similar to the selection performed by the key selection method. In the key selection access method. 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. a query requiring that the cursor position be restored as the result of the SQL ROLLBACK HOLD statement or the ROLLBACK CL command). processing of those key values would complete sooner than the third and fourth partitions. v Nested loop join implementation. or by the DEGREE parameter on the Change Query Attributes (CHGQRYA) command. See “Controlling Parallel Processing” on page 473 for information on how to control parallel processing. no matter what interface was used to define the query. Parallel key selection can be used during the creation of a temporary result. because the application might attempt to position to the last record and retrieve previous records. All the keys from this range are read and any remaining key selection is performed. The following example illustrates a query where the optimizer could choose the key positioning method: CREATE INDEX X1 ON EMPLOYEE(WORKDEPT) DECLARE BROWSE2 CURSOR FOR SELECT * FROM EMPLOYEE WHERE WORKDEPT = 'E01' OPTIMIZE FOR 99999 ROWS | | | | OPNQRYF example: OPNQRYF FILE((EMPLOYEE)) QRYSLT('WORKDEPT *EQ ''E01''') In this example. or join operations). the optimizer tries to find an existing index to use for key positioning. For each key equal to ’E01’. The query ends when the key selection moves beyond the key value of E01. grouping.positioning only processes a subset of the keys in the index. Note that for this example all index entries processed and rows retrieved meet the selection criteria. One such capability is to perform range selection across several values. The key positioning access method has additional processing capabilities. The messages created by the PRTSQLINF CL command to describe this query in an SQL program would appear as follows: SQL4008 SQL4011 Access path X1 used for file 1. the optimizer generally chooses to: v Use dataspace scan processing (if index is not required) v Use key selection (if an index is required) v Use query sort routine (if conditions apply) For queries that do not require an index (no ordering. Any remaining selection is performed at the dataspace level. the performance of the key positioning method is better than the performance of the key selection method. the database support uses X1 to position to the first index entry with the WORKDEPT value equal to ’E01’. If more than approximately 20% of the rows are to be selected. it randomly accesses the dataspace 18 and selects the row. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 407 . If no existing index can be found. random accessing occurs because the keys may not be in the same sequence as the rows in the dataspace Chapter 24. The key positioning method is most efficient when a small percentage of rows are to be selected (less than approximately 20%). the optimizer stops trying to use keyed access to the data because it is faster to use dataspace scan processing than it is to build an index and then perform key positioning. Key row positioning used on file 1. 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. For example: CREATE INDEX X1 EMPLOYEE(WORKDEPT) DECLARE BROWSE2 CURSOR FOR SELECT * FROM EMPLOYEE WHERE WORKDEPT BETWEEN 'E01' AND 'E11' OPTIMIZE FOR 99999 ROWS 18. of the index. Key row positioning used on file 1. CREATE INDEX X2 ON EMPLOYEE(WORKDEPT.LASTNAME. Key row positioning used on file 1. It allows for the selection of rows for multiple ranges of values for the first key columns of an index over multiple columns. The messages created by PRTSQLINF CL command to describe this query in an SQL program would appear as follows: SQL4008 SQL4011 Access path X1 used for file 1. is available. Key positioning also handles more than one key (although the keys must be contiguous to the left-most key). 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. All of the key positioning examples have so far only used one key. it means that the processing of rows 408 DB2 UDB for AS/400 SQL Programming V4R4 . CREATE INDEX X1 ON EMPLOYEE(WORKDEPT) DECLARE BROWSE2 CURSOR FOR SELECT * FROM EMPLOYEE WHERE WORKDEPT BETWEEN 'E01' AND 'E11' OR WORKDEPT BETWEEN 'A00' AND 'B01' OPTIMIZE FOR 99999 ROWS | | | | | OPNQRYF example: OPNQRYF FILE((EMPLOYEE)) QRYSLT('WORKDEPT *EQ %RANGE(''E01'' ''E11'') *OR WORKDEPT *EQ %RANGE(''A00'' ''B01'')') In the previous example. there is no multiple key position support for this example. only the WORKDEPT = ’D11’ part of the selection can be applied against the index (single key positioning). the left-most key.FIRSTNME) DECLARE BROWSE2 CURSOR FOR SELECT * FROM EMPLOYEE WHERE WORKDEPT = 'D11' AND FIRSTNME = 'DAVID' OPTIMIZE FOR 99999 ROWS | | | | | OPNQRYF example: OPNQRYF FILE((EMPLOYEE)) QRYSLT('WORKDEPT *EQ ''D11'' *AND FIRSTNME *EQ ''DAVID''') Because the two selection keys (WORKDEPT and FIRSTNME) are not contiguous. The messages created by PRTSQLINF CL command to describe this query in an SQL program would appear as follows: SQL4008 SQL4011 Access path X1 used for file 1.| | | | OPNQRYF example: OPNQRYF FILE((EMPLOYEE)) QRYSLT('WORKDEPT *EQ %RANGE(''E01'' ''E11'')') In the previous example. A further extension of this access method. Therefore. the positioning and processing technique is used twice. called multi-range key positioning. once for each range of values. While this may be acceptable. 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. This improves performance considerably. CREATE INDEX X3 ON EMPLOYEE(WORKDEPT.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’. LASTNAME) Multiple key positioning support can apply both pieces of selection as key positioning. Key row positioning used on file 1.'WILLIAM') OPTIMIZE FOR 99999 ROWS OPNQRYF example: OPNQRYF FILE((EMPLOYEE)) QRYSLT('WORKDEPT *EQ ''D11'' *AND FIRSTNME *EQ %VALUES(''DAVID'' ''BRUCE'' ''WILLIAM'')') 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 | | | | | | | OPNQRYF example: OPNQRYF FILE((EMPLOYEE)) QRYSLT('(WORKDEPT *EQ ''D11'' *AND FIRSTNME *EQ ''DAVID'') *OR (WORKDEPT *EQ ''D11'' *AND FIRSTNME *EQ ''BRUCE'') *OR (WORKDEPT *EQ ''D11'' *AND FIRSTNME *EQ ''WILLIAM'')') 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' Index X3 Stop value 'D11DAVID' 'D11BRUCE' 'D11WILLIAM' Chapter 24. the above example query would run using multiple key positioning.'BRUCE'. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 409 . The messages created by the PRTSQLINF CL command when used to describe this query in an SQL program would look like this: SQL4008 SQL4011 Access path X3 used for file 1. | | | | | | | | | | | | | | | This next example shows a more interesting use of multiple key positioning. FIRSTNME. By creating the following index. X3. CREATE INDEX X3 ON EMPLOYEE(WORKDEPT.FIRSTNME) DECLARE BROWSE2 CURSOR FOR SELECT * FROM EMPLOYEE WHERE WORKDEPT = 'D11' AND FIRSTNME IN ('DAVID'. The complexity of this range analysis can be taken to a further degree in the following example: DECLARE BROWSE2 CURSOR FOR SELECT * FROM EMPLOYEE WHERE (WORKDEPT = 'D11' AND FIRSTNME IN ('DAVID'. significantly reducing the number of keys selected to just 3.'C01')) | | | | | | | | | OPNQRYF example: OPNQRYF FILE((EMPLOYEE)) QRYSLT('(WORKDEPT *EQ ''D11'' *AND FIRSTNME *EQ %VALUES(''DAVID'' ''BRUCE'' ''WILLIAM'')) *OR (WORKDEPT *EQ ''E11'' *AND FIRSTNME *EQ %VALUES(''PHILIP'' ''MAUDE'')) *OR (FIRSTNME *EQ %RANGE(''CHRISTINE'' ''DELORES'') *AND WORKDEPT *EQ %VALUES(''A00'' ''C01''))') 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' = 'DAVID') = 'BRUCE') = 'WILLIAM') = 'PHILIP') = 'MAUDE') BETWEEN 'CHRISTINE' AND 'DELORES') OR (WORKDEPT = 'C01' AND FIRSTNME BETWEEN 'CHRISTINE' AND 'DELORES') OPTIMIZE FOR 99999 ROWS AND AND AND AND AND AND FIRSTNME FIRSTNME FIRSTNME FIRSTNME FIRSTNME FIRSTNME | | | | | | | | | | | | | | OPNQRYF example: OPNQRYF FILE((EMPLOYEE)) QRYSLT('(WORKDEPT *EQ ''D11'' *AND FIRSTNME *EQ ''DAVID'') *OR (WORKDEPT *EQ ''D11'' *AND FIRSTNME *EQ ''BRUCE'') *OR (WORKDEPT *EQ ''D11'' *AND FIRSTNME *EQ ''WILLIAM'') *OR (WORKDEPT *EQ ''E11'' *AND FIRSTNME *EQ ''PHILIP'') *OR (WORKDEPT *EQ ''E11'' *AND FIRSTNME *EQ ''MAUDE'') *OR (WORKDEPT *EQ ''A00'' *AND FIRSTNME *EQ %RANGE(''CHRISTINE'' ''DELORES'')) *OR (WORKDEPT *EQ ''C01'' *AND FIRSTNME *EQ %RANGE(''CHRISTINE'' ''DELORES''))') 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' Index X3 Stop value 'D11DAVID' 'D11BRUCE' 'D11WILLIAM' 'E11MAUDE' 410 DB2 UDB for AS/400 SQL Programming V4R4 .Key positioning is performed over each range.'BRUCE'.'WILLIAM')) OR (WORKDEPT = 'E11' AND FIRSTNME IN ('PHILIP'. All of the selection can be accomplished through key positioning.'MAUDE')) OR (FIRSTNME BETWEEN 'CHRISTINE' AND 'DELORES' AND WORKDEPT IN ('A00'. Parallel Key Positioning Access Method (available only when the DB2 UDB Symmetric Multiprocessing feature is installed) Using the parallel key positioning access method. Because the keys are not processed in order. Consider the following example if the SQL statement is run using parallel degree of four. the ranges can be further partitioned and processed simultaneously. As processing for a range completes and there are no more ranges in the list to process. range of values. Only those rows whose key values fall within one of the ranges are returned. The number of concurrent tasks is controlled by the optimizer. each processing a separate key range. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 411 . this method can not be used by the optimizer if the index is being used for ordering. All of the selection can be accomplished through key positioning. This significantly improves the performance of this query. the existing key ranges are processed by separate tasks concurrently in separate database tasks. The query will start processing the key ranges of the query up to the degree of parallelism being used. As processing of those ranges completes. just as in the parallel key selection method. ranges that still have keys left to process are split. the next ones on the list are started. or multi-range key positioning. Whether using the single value. 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' = 'DAVID') = 'BRUCE') = 'WILLIAM') = 'PHILIP') = 'MAUDE') BETWEEN 'CHRISTINE' AND 'DELORES') OR (WORKDEPT = 'C01' AND FIRSTNME BETWEEN 'CHRISTINE' AND 'DELORES') OPTIMIZE FOR 99999 ROWS AND AND AND AND AND AND FIRSTNME FIRSTNME FIRSTNME FIRSTNME FIRSTNME FIRSTNME OPNQRYF example: OPNQRYF FILE((EMPLOYEE)) QRYSLT('(WORKDEPT *EQ ''D11'' *AND FIRSTNME *EQ ''DAVID'') *OR (WORKDEPT *EQ ''D11'' *AND FIRSTNME *EQ ''BRUCE'') *OR (WORKDEPT *EQ ''D11'' *AND FIRSTNME *EQ ''WILLIAM'') *OR (WORKDEPT *EQ ''E11'' *AND FIRSTNME *EQ ''PHILIP'') *OR (WORKDEPT *EQ ''E11'' *AND FIRSTNME *EQ ''MAUDE'') *OR (WORKDEPT *EQ ''A00'' *AND FIRSTNME*EQ %RANGE(''CHRISTINE'' ''DELORES'')) *OR (WORKDEPT *EQ ''C01'' *AND FIRSTNME *EQ %RANGE(''CHRISTINE'' ''DELORES''))') The key ranges the database manager starts with are as follows: Range Range Range Range Range Range Range Index X3 Start value 1 'D11DAVID' 2 'D11BRUCE' 3 'D11WILLIAM' 4 'E11MAUDE' 5 'E11PHILIP' 6 'A00CHRISTINE' 7 'C01CHRISTINE' Index X3 Stop value 'D11DAVID' 'D11BRUCE' 'D11WILLIAM' 'E11MAUDE' 'E11PHILIP' 'A00DELORES' 'C01DELORES' Chapter 24.'E11PHILIP' 'A00CHRISTINE' 'C01CHRISTINE' 'E11PHILIP' 'A00DELORES' 'C01DELORES' Key positioning is performed over each range. The database manager attempts to keep all of the tasks that are being used busy. v Restoration of the cursor position. v Update or delete capability. which enbles the usage of most of the parallel access methods. because the application might attempt to position to the last record and retrieve previous records. For example. a query requiring that the cursor position be restored as the result of the SQL ROLLBACK HOLD statement or the ROLLBACK CL command. parallel key positioning cannot be used for queries defined by the Open Query File (OPNQRYF) command. As soon as one of those four completes. You should run the job in a shared pool with the *CALC paging option as this will cause more efficient use of active memory. However. Index Only Access Method The index only access method can be used in conjunction with any of the key selection or key positioning access methods. See “Controlling Parallel Processing” on page 473 for information on how to control parallel processing. For more information on the paging option see the ″Automatic System Tuning″ section of Work Management book. including the parallel options for these methods. range 5 is started. SQL-defined queries that are not defined as scrollable can use this method. (The parallel options are available only when the DB2 Symmetric Multiprocessing feature is installed. OPNQRYF can be defined as not scrollable by specifying the *OPTIMIZE parameter value for the ALWCPYDTA parameter. by the query options file PARALLEL_DEGREE option. Parallel key positioning can be used during the creation of a temporary result. When another range completes. range 6 is started. 412 DB2 UDB for AS/400 SQL Programming V4R4 . 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.) The processing for the selection does not change from what has already been described for these methods. v Nested loop join implementation. See “Nested Loop Join Implementation” on page 426. and so on. no matter what interface was used to define the query. all of the data is extracted from the index rather than performing a random I/O to the data space. | | | | | | | | | | v Backward scrolling. The optimizer chooses this method when: v All of the columns that are referenced within the query can be found within a permanent index or within the key fields of a temporary index that the optimizer has decided to create. the remaining work left in one of the other key ranges is split and each half is processed separately. For instance. Parallel key selection requires that SMP parallel processing be enabled either by the system value QQRYDEGREE. When one of the four ranges in progress completes and there are no more new ones in the list to start.Ranges 1 to 4 are processed concurrently in separate tasks. or by the DEGREE parameter on the Change Query Attributes (CHGQRYA) command. which specify ALWCPYDTA(*YES) or ALWCPYDTA(*NO). such as a sort or hash operation. The index entry is then used as the input for any derivation or result mapping that might have been specified on the query. Parallel key positioning cannot be used for queries that require any of the following: v Specification of the *ALL commitment control level. FIRSTNME) DECLARE BROWSE2 CURSOR FOR SELECT FIRSTNME FROM EMPLOYEE WHERE WORKDEPT = 'D11' OPTIMIZE FOR 99999 ROWS OPNQRYF example: OPNQRYF FILE((EMPLOYEE)) QRYSLT('WORKDEPT *EQ ''D11''') In this example.or table-based pre-load when query processing begins. Note: Index only access is implemented on a particular file. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 413 . 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. a high percentage of the data in the index or table is referenced.v The data values must be able to be extracted from the index and returned to the user in a readable format. See “Controlling Parallel Processing” on page 473 for information on how to control parallel processing. Parallel Table or Index Based Pre-load Access Method Some queries implemented with key selection can require a lot of random I/O in order to access an index or a table. no variable length or null capable fields can require key feedback. 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. random access to the data is achieved without further I/O. The DB2 UDB for AS/400 cost-based query optimizer recognizes the queries and objects that benefit from table or index pre-loads if I/O parallel processing has been enabled. After the table or index is loaded into memory. CREATE INDEX X2 ON EMPLOYEE(WORKDEPT.LASTNAME. in other words. The messages created by the PRTSQLINF command to describe this query in an SQL program are as follows: SQL4008 SQL4011 SQL4022 Access path X2 used for file 1. so it is possible to perform index only access on some or all of the files of a join query. v For non-SQL users. The data is loaded into active memory in parallel as is done for parallel pre-fetch. Key row positioning used on file 1. none of the key fields that match the query columns have: – Absolute value specified – Alternative collating sequence or sort sequence specified – Zoned or digit force specified v The query does not use a left outer join or an exception join. The following example illustrates a query where the optimizer could choose to perform index only access. Chapter 24. Index only access used on file 1. 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. Any key field in the index can be used to provide data for the index only query. Because of this. DB2 UDB for AS/400 attempts to avoid this random I/O by initiating index. a temporary select/omit index is created with the primary key field LASTNAME. The result is an index containing entries in the required key sequence for rows that match the selection criteria. grouping. The application continues fetching rows using the other database access methods without any knowledge of pre-load.The parallel pre-load method can be used with any of the other data access methods. The temporary index that is created only contains entries for rows that meet the selection predicates. Generally speaking. Uses key positioning on the permanent index with the query selection criteria 2. v The selection columns are not the same as the ordering. The optimizer chooses this method when: v The query requires an index because it uses grouping. or join-to columns. or join processing. you can use the query sort routine: v For SQL (see “Improving Performance by Using the ALWCPYDTA Parameter” on page 465) specify either of the following precompile options: – ALWCPYDTA(*OPTIMIZE). Index-From-Index Access Method The database manager can build a temporary index from an existing index without having to read all of the rows in the dataspace. The pre-load is started when the query is opened and control is returned to the application before the pre-load is finished. this selection method is one of the most efficient. If WORKDEPT = ’D11’. less than approximately 20% of the rows are selected. and COMMIT(*CHG or *CS) 414 DB2 UDB for AS/400 SQL Programming V4R4 . ordering. To use the index-from-index access method. Builds index entries in the new temporary index using selected row entries. v A permanent index exists that has selection columns as the left-most keys and the left-most keys are very selective. | | | | | | Rather than using the index-from-index access method. the database manager: 1. ALWBLK(*ALLREAD). It contains index entries for only those rows where WORKDEPT = ’D11’. Key row positioning used on file 1. The messages created by the PRTSQLINF CL command to describe this query in an SQL program are as follows: SQL4012 SQL4011 Access path created from keyed file X1 for file 1. This is similar to the key access path created by a select/omit logical file or sparse index. A common index-from-index access method example follows: CREATE INDEX X1 ON EMPLOYEE(WORKDEPT) DECLARE BROWSE2 CURSOR FOR SELECT * FROM EMPLOYEE WHERE WORKDEPT = 'D11' ORDER BY LASTNAME OPTIMIZE FOR 99999 ROWS | | | | | | | OPNQRYF example: OPNQRYF FILE((EMPLOYEE)) QRYSLT('WORKDEPT *EQ ''D11''') KEYFLD((LASTNAME)) For this example. If the row’s source value is not found in the table. If one hash table partition contains a majority of the hash table entries. the hash table entry for this value is retrieved and additional query processing is performed based on the requested operation (such as grouping or joining). the hash table rows are not guaranteed to be sorted in ascending or descending order. given that the source data is random and distributed. but has a different structure that is logically partitioned based on the specified query. The hashing algorithm then ensures that the new hash table entries are distributed evenly across the hash table partitions. The hash table itself is partitioned based on the requested query operation and the number of source values being processed. The hashing access method can complement keyed sequence access paths or serve as an alternative. For each selected row. Since the hash method typically processes the rows in a table sequentially. This balanced distribution is necessary to guarantee that scans in different partitions of the hash tables are processing the same number of entries. or *CS This decision is based on the number of rows to be retrieved. A new hash table entry is initialized with this first-time value and additional processing is performed based on the query operation. then this marks the first time that this source value has been encountered in the database table. The hash method can only correlate (or group) identical values. Pre-fetching enables very efficient I/O operations for the hash method leading to improved query performance. If the row’s source value is found in the table. The predictability allows the database manager to schedule asynchronous I/O of the table pages into main storage (also known as pre-fetching). specify either: – ALWCPYDTA(*OPTIMIZE) and COMMIT(*NO) – ALWCPYDTA(*OPTIMIZE) and COMMIT(*YES) and commitment control is started with a commit level of *NONE. This is not very efficient. The hashing method can be used only when the ALWCPYDTA(*OPTIMIZE) option has been specified unless a temporary result is required. then scans of that partition are going to have to examine the majority of the entries in the hash table. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 415 . This is similar to the advantages of the dataspace scan access method. A hash table is similar to a temporary work table. if the optimizer had to create a temporary index for that query.| | | | | | – ALWCPYDTA(*OPTIMIZE) and COMMIT(*NONE) v For OPNQRYF. the database manager can easily predict the sequence of memory pages from the database table needed for query processing. extra processor time and resources are used when creating this index before the requested query can be run. Chapter 24. However. since the hash table built by the database manager is a temporary copy of the selected rows. the specified grouping or join value in the row is run through a hashing function. The hashing algorithm allows the database manager to build a hash table that is well-balanced. Keyed sequence access paths (indexes) are used to sort and group the data and are effective in some cases for implementing grouping and join query operations. Hashing Access Method The hashing access method provides an alternative method for those queries (groupings and joins) that must process data in a grouped or correlated manner. or *CHG. The computed hash value is then used to search a specific partition of the hash table. the hashing methods can be performed in parallel. A keyed sequence access path can also be used by the hash method to process the table rows in keyed order. For this reason. Bitmap Processing Method As the name implies. If the DB2 SMP feature is installed. grouping. When the processing of the index is complete. This can offset the random I/O costs associated with keyed sequence access paths. the hashing access method can also be performed in parallel so that several groups of records are being hashed at the same time. it is used to avoid mapping in records from the data space unless they are selected by the query. the bit associated with that record is set to ’1’ (i. This shortens the amount of time it takes to hash all the rows in the database table. The bitmap processing method is used to: v Eliminate the random I/O that occurs on a data space when using a keyed sequence access path in conjunction with the key position and/or key selection method. key positioning and key selection methods are used to apply selection criteria. Once the hash table has been completely populated with the specified database records. The keyed access path can significantly reduce the number of table rows that the hash method has to process. indexes used to access the final records are called primary indexes. v Allow multiple keyed sequence access paths to be used to access a particular table. Random I/O can reduce query performance because it leads to unnecessary use of I/O and processor unit resources. Conversely. It is important to note that the indexes used to generate the bitmaps are not actually used to access the selected records. query processing with a keyed sequence access method causes a random I/O to the database table for every key value examined. For each index. The data space is not accessed. In this method. Since blocks of table rows are automatically spread. and for selection when no bitmap is used. Primary indexes are used for ordering. depending on the requested query operations. Once the resulting bitmap is built. turned on). joins. If two or more indexes are used. the optimizer chooses one or more keyed sequence access paths to be used to aid in selecting records from the data space. one for each index. the temporary bitmaps are logically ANDed and ORed together to obtain one resulting bitmap. Additional processing might be required on the resulting hash table rows. This process is repeated for each index. The hash table creation and population takes place before the query is opened. they are called tertiary indexes. For each index entry selected. the bitmap contains the information on which records are to be selected from the underlying data space. The I/O operations are random since the keyed-order of the data in the index does not match the physical order of the rows in the database table. this method generates bitmaps that are used during access to the data space. the hash table is used by the database manager to start returning the results of the queries. Temporary bitmaps are allocated (and initialized).e. 416 DB2 UDB for AS/400 SQL Programming V4R4 . Each bitmap contains one bit for each record in the underlying data space.In contrast. Access path IX2 used for bitmap processing of file 1. The database manager first generates a bitmap from the results of applying selection WORKDEPT = ’E01’ against index IX1 (using key positioning). it implies that the bitmap (generated from tertiary indexes) is being used to aid a primary index access. the bitmap initiates a skip-sequential processing. a data space scan is initiated. the database manager combines these two bitmaps into one using OR logic. Bitmap processing. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 417 . both indexes IX1 and IX2 are used. If the bitmap is used in conjunction with either the key selection or key positioning method. Arrival sequence access was used for file EMPLOYEE. Next. When using bitmap processing. key selection. The data space scan uses the bitmap to skip through the data space records. | | | | | | | | The messages created by the PRTSQLINF command when used to describe this query would look like: SQL4010 SQL4032 SQL4032 CPI4329 CPI4388 Arrival sequence access for file 1. or key positioning.The bitmap processing method is used in conjunction with primary access methods data space scan. The data space scan (and parallel data space scan) uses the bitmap to ″skip over″ non-selected records. it assists the primary methods. 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). The following example illustrates a query where bitmap processing is used in conjunction with the key positioning for a primary index: Chapter 24. This has several advantages: v No CPU processing is used processing non-selected records. Finally. Access path IX1 used for bitmap processing of file 1. If the bitmap is used in conjunction with the data space scan method. 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 OPNQRYF example: OPNQRYF FILE((EMPLOYEE)) QRYSLT('WORKDEPT *EQ ''E01'' *OR SALARY > 50000') In this example. 2 Access path(s) used for bitmap processing of file EMPLOYEE. does not actually select the records from the data space. v I/O is minimized and the memory is not filled with the contents of the entire data space. like parallel pre-fetch and parallel table/index pre-load. The database manager then generates a bitmap from the results of applying selection SALARY>50000 against index IX2 (again using key positioning). multiple index usage is possible with selections where OR is the major boolean operator. retrieving only those selected by the bitmap. the optimizer decides that the join order is file PROJECT to file EMPLOYEE. index EPIX is used to process the join (primary index). the bitmap is checked. For each entry in index PIX. Indexes TIX1 and TIX2 are used in bitmap processing. Access path TIX1 used for bitmap processing of file 1. Data space scan is used on file PROJECT. For file EMPLOYEE. would look like: | | | | | | | | | | | | | | | | | | | | | | | | | | | SQL4008 SQL4032 CPI4328 CPI4338 Access path PIX used for file 1. each file of a join can independently use or not use bitmap processing The following example illustrates a query where bitmap processing is used against the second file of a join query but not on the first file: CREATE INDEX EPIX ON EMPLOYEE(EMPNO) CREATE INDEX TIX1 ON EMPLOYEE(WORKDEPT) CREATE INDEX TIX2 ON EMPLOYEE(SALARY) DECLARE C1 CURSOR FOR SELECT * FROM PROJECT. Access path of file PIX was used by query. It then generates a bitmap from the results of applying selection SALARY>50000 against index TIX2 (again using key positioning). EMPLOYEE WHERE RESEMP=EMPNO AND (WORKDEPT='E01' OR SALARY>50000) Using the OPNQRYF command: OPNQRYF FILE((PROJECT) (EMPLOYEE)) FORMAT(RESULTFILE) JFLD((1/RESPEMP 2/EMPNO)) QRYSLT('2/WORKDEPT=''E01'' *OR 2/SALARY>50000') In this example. If the entry is selected by the bitmap. The database manager positions to the first record in file PROJECT. as well. 2 Access path(s) used for bitmap processing of file EMPLOYEE. It 418 DB2 UDB for AS/400 SQL Programming V4R4 . it generates a bitmap from the results of applying selection WORKDEPT=’E01’ against index TIX1 (using key positioning). then the data space record is retrieved and processed. Since bitmap processing is on a per file basis. A key selection method is initiated using (primary) index PIX. The messages created by the PRTSQLINF CL command.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 OPNQRYF example: OPNQRYF FILE((EMPLOYEE)) QRYSLT('WORKDEPT *EQ ''E01'' *OR SALARY > 50000') KEYFLD(LASTNAME) In this example. Bitmap processing can be used for join queries. Next. The database manager first generates a bitmap from the results of applying selection WORKDEPT = ’E01’ against index TIX1 (using key positioning). It then performs the join using index EPIX. indexes TIX1 and TIX2 are used in bitmap processing. when used to describe this query. | | | | The database manager then combines these two bitmaps into one using OR logic. v Bitmaps are generated at the first record fetch (I/O). 'BRUCE'. Therefore. it is compared against the bitmap and either selected or rejected. The entry is either selected or rejected by the bitmap. 'WILLIAM') Or the same query using the OPNQRYF command: OPNQRYF FILE((EMPLOYEE)) QRYSLT('WORKDEPT=''D11'' *AND FIRSTNME = %VALUES(''DAVID'' ''BRUCE'' ''WILLIAM'')') An index with keys (WORKDEPT. For example. and have the optimizer use them as general purpose indexes for many queries. the bitmap is built from the results of performing either parallel key positioning and/or parallel key selection on the tertiary index. Through a separate database operation. two indexes. Once the bitmap is generated. If the entry is selected. but at some cost to performance. one with a key of WORKDEPT and the other with a key of FIRSTNME could be used in bitmap processing. in comparison to using a multiple key field index. index EPIX is probed for the next join record. The query optimizer debug messages put into the job log would look like: CPI4327 File PROJECT processed in join position 1. with their resulting bitmaps ANDed together and data space scan used to retrieve the result. the database manager combines these two bitmaps into one using OR logic. you can use parallel processing whenever you use bitmap processing. When an entry is found. it will not select any new or modified records. in this case. Finally. the entry that EPIX is currently positioned to is checked against the bitmap. v Bitmaps. Note that the bitmap was generated only once (the first time it was needed) and is just reused after that. You can avoid problems involved with trying to determine the best composite key indexes for all queries being performed against a table. Bitmap processing alleviates some of the headache associated with having composite key indexes (multiple key fields in one index). FIRSTNAME) would be the best index to use to satisfy this query. CPI4338 2 Access path(s) used for bitmap processing of file EMPLOYEE. all records where QUANTITY is equal to 4 are updated so QUANTITY is equal to 10. the records are retrieved from the underlying data space. Next. With the bitmap processing method. the first record fetched may take longer to retrieve than subsequent records.| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | then generates a bitmap from the results of applying selection SALARY>50000 against index TIX2 (again using key positioning). Since the bitmap was already built (during Chapter 24. Bitmap processing. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 419 . by their nature. given an SQL query: DECLARE C1 CURSOR FOR SELECT * FROM EMPLOYEE WHERE WORKDEPT='D11' AND FIRSTNAME IN ('DAVID'. contain static selection. you can create several indexes. Keep in mind that you will always achieve the best performance by using composite key indexes. Some additional points regarding bitmap processing: v As long as the DB2 SMP feature is installed. Next. suppose an OPNQRYF statement specifying (QRYSLT(’QUANTITY >5’) is opened using bitmap processing and the first record is read. CPI4326 File EMPLOYEE processed in join position 2. each with only one key field. allows more ease of use. However. For example. v Do not use bitmap processing for a query that is insert. or delete capable. Table 38. Query is CPU bound on a uniprocessor system. The exception to this is if the query contains grouping or one or more aggregate functions (for example. Selection criteria applied to data in dataspace. Data Access Methods The following table provides a summary of the data management methods discussed. < 10% rows selected. Reads all rows. 1. Summary of Data Management Methods Access Method “Dataspace Scan Access Method” on page 399 “Parallel Pre-Fetch Access Method” on page 401 Selection Process Good When Reads all rows. SUM. Adequate active memory available. Selected When Advantages No ordering. Significant performance especially on multiprocessors. For this reason. the query optimizer will not consider bitmap processing if the ALWCPYDTA option is *NO. update. MAX). 3. > 20% rows selected. 2. I/O bound or running on a multi-processor system. Data spread across multiple disk units. Query would otherwise be I/O bound. COUNT. For OPNQRYF. Data spread across multiple disk units. There must not be any overrides to SEQONLY(*NO)). in which case static data is already being made. 3. Method (available only when the DB2 UDB Symmetric Multiprocessing feature is installed)” on page 403 > 10% rows selected. 2. > 20% rows selected. or joining and > 20% rows selected. < 20% rows selected. Not Good When < 20% rows selected.| | | | | | | | | | | | the first record fetch from the OPNQRYF open identifier). Minimizes wait time for page I/O through parallel pre-fetching. Multi-processor system. No ordering. DB2 UDB Symmetric Multiprocessing installed. “Parallel Data read and Data Space selected in parallel Scan tasks. 4. Adequate active memory available. these updated records will not be retrieved on subsequent fetches through the OPNQRYF open identifier. selected. Query is CPU bound. DB2 UDB Symmetric Multiprocessing installed. 1. Selection criteria applied to data in dataspace. grouping. 1. 2. large table. the OPTION parameter must be set to *INP and the SEQONLY parameter must be set to *YES. or joining through and > 20% rows pre-fetching. 420 DB2 UDB for AS/400 SQL Programming V4R4 . Minimizes page I/O grouping. MIN. Data retrieved from auxiliary storage in parallel streams. Large number of and joining. DB2 UDB rows selected. > 20% rows selected. Can fully utilize a multiprocessor systems. Index and dataspace accessed only for rows matching selection criteria. “Parallel Key Selection criteria Positioning applied to range of Access index entries in Method parallel tasks. No existing index to satisfy ordering but existing index does satisfy selection and selecting < 20% rows. (available only when the DB2 UDB Symmetric Multiprocessing feature is installed)” on page 411 < 20% rows Large number of selected. Ordering. Better I/O overlap because parallel tasks perform the I/O. Selection columns match left-most keys and < 20% rows selected. Ordering specified. Size of index is Large number of much less than the rows selected. key positioning. Commonly used option. “Parallel Key Selection criteria Selection applied to index in Access parallel tasks. When ordering of results not required. Not Good When Selected When Index is required and cannot use key positioning method. 3. Method (available only when the DB2 UDB Symmetric Multiprocessing feature is installed)” on page 405 “Key Positioning Access Method” on page 406 Selection criteria applied to range of index entries. > 20% rows Order data read selected or large using dataspace scan processing or result set of rows. rows selected. Symmetric Multiprocessing must be installed. See dataspace scan and key positioning in this table. Summary of Data Management Methods (continued) Access Method “Key Selection Access Method” on page 404 Selection Process Good When Selection criteria applied to index. Sort routine < 20% rows selected or small result set of rows. Index and dataspace accessed only for rows matching selection criteria. When ordering of results not required. < 20% rows selected. grouping. Index and dataspace accessed only for rows matching selection criteria. dataspace. DB2 UDB Symmetric Multiprocessing must be installed.Table 38. Better I/O overlap because parallel tasks perform the I/O. > 20% rows selected. 2. Chapter 24. “Index-FromIndex Access Method” on page 414 Key row positioning Ordering. Builds temporary index over selected index entries. 1. grouping on permanent and joining. 1. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 421 . Can fully utilize multiprocessor systems. index. 2. Selection columns match left-most keys and < 20% rows selected. either no index exists to satisfy the ordering or a large result set is expected. Advantages Dataspace accessed only for rows matching key selection criteria. Table 38. DB2 result set of rows. Join or grouping specified. key fields and DB2 UDB Symmetric Multiprocessing is installed. possible exploitation of SMP parallelism. Random page I/O is avoided which can improve I/O bound queries. Selection can be >25% rows applied to index selected. Excessive random activity would result from processing the query and active memory is available which can hold the entire object. Reduces page I/O to the data space. If DB2 UDB Symmetric Multiprocessing is installed. Excessive random Active memory is activity would already otherwise occur over-committed. and either >5% or <25% rows selected or an OR operator is involved in selection that precludes the use of only one index. Summary of Data Management Methods (continued) Access Method “Index Only Access Method” on page 412 Selection Process Good When Done in combination with any of the other index access methods Index or table data loaded in parallel to avoid random access. Not Good When Selected When Advantages All columns used in < 20% rows the query exist as selected or small key fields. against the object and active memory is available to hold the entire object. “Parallel Table or Index Based Pre-load Access Method” on page 413 “Hashing Rows with common Longer running Access values are grouped grouping and/or Method” on together. 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 422 DB2 UDB for AS/400 SQL Programming V4R4 . Short running queries. v Identifies the techniques which could be used to implement the query. page 415(Parallel or non-parallel) Reduce random I/O when compared to index methods. Indexes match selection criteria. not how to get to that data. UDB Symmetric Multiprocessing must be installed. Data manipulation statements such as SELECT specify only what data the user wants. This access path to the data is chosen by the optimizer and stored in the access plan. Allows multiple indexes per table. join queries. “Bitmap Processing Method” on page 416 Key position/key selection used to build bitmap. All columns used in Reduced I/O to the the query exist as dataspace. The Optimizer The optimizer is an important part of DB2 UDB for AS/400 because the optimizer: v Makes the key decisions which affect database performance. Bitmap used to avoid touching rows in table. v Selects the most efficient technique. ALWCPYDTA(*OPTIMIZE) specified as a precompiler parameter. – For OPNQRYF. This mode can be specified in two ways: a. note: . 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. Specifying ALWCPYDTA(*NONE) or ALWCPYDTA(*YES) a precompiler option. b. The optimizer uses this value to determine the percentage of rows that will be returned and optimizes accordingly. This mode can be specified in two ways: a. allows the optimizer to minimize the time required to retrieve the first 3% of the resulting rows. the optimizer chooses an optimal access method for the query by calculating an implementation cost based on the current state of the database.Cost Estimation At run-time.The optimizer can optimize SQL queries with one of two goals: 1. b. A small value instructs the optimizer to minimize the time required to retrieve the first n rows. 2. 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. Minimize the time required to retrieve the first buffer of rows from the table. This goal biases the optimization towards not creating an index. the precompile option ALWCPYDTA and the OPTIMIZE FOR n ROWS clause indicate to the query optimizer the optimization goal to be achieved. The optimizer uses this value to determine the percentage of rows that will be returned and optimizes accordingly. or *MINWAIT).The cost associated with the given optimization parameter (*FIRSTIO. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 423 . *ALLIO. Either a data scan or an existing index is preferred. – For SQL. Minimize the time to process the whole query assuming that all selected rows are returned to the application. The OPTIMIZE FOR n ROWS allows the users to specify the number of rows they expect to retrieve from the query. The OPTIMIZE FOR n ROWS allows the users to specify the number of rows they expect to retrieve from the query. Does not bias the optimizer to any particular access method. This option is effective only if the OPTIMIZE FOR n ROWS is not specified. | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Chapter 24. This option is effective only if the OPTIMIZE FOR n ROWS was not specified. . Biases optimization toward either creating a temporary index or performing a sort. users may also pass in the number of records they expect to retrieve from the query. Minimize I/O time at the expense of open time. Page faults and number of rows processed may be predicted by statistics the optimizer can obtain from the database objects. similar to *FIRSTIO. A large value would minimize the time to retrieve all n records. When *FIRSTIO is selected. Full indexes over columns used in selection predicates can significantly help optimization. greater-than. v *ALLIO–Minimize the time to process the whole query assuming that all query records are read from the file. thus eliminating any random I/O to the data space. The optimizer uses this value to determine the percentage of records that will be returned and optimizes accordingly. including: – Table size – Row size – Index size – Key size Page faults can also be greatly affected if index only access can be performed.| | | | | | | | | | | | | | | | | | | v *FIRSTIO–Minimize the time required to retrieve the first buffer of records from the file. Either an index is created or an existing index is used. that index can be used to estimate the number of keys that match the selection criteria. Note: If you specify ALWCPYDTA(*OPTIMIZE) and use the sort routine. A small value would minimize the time required to retrieve the first n records. 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. less-than-equal-to. A weighted measure of the expected number of rows to process is based on what the relational operators in the row selection predicates. v *MINWAIT–Minimize delays when reading records from the file. 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. similar to *ALLIO. If an index exists whose left-most keys match columns used in row selection predicates. Does not bias the optimizer to any particular access method. are likely to retrieve: – 10% for equal – 33% for less-than. default filter factors. Either a data scan or an existing index is preferred. | | 424 DB2 UDB for AS/400 SQL Programming V4R4 . or greater-than-equal-to – 90% for not equal – 25% for BETWEEN range (OPNQRYF %RANGE) – 10% for each IN list value (OPNQRYF %VALUES) 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. 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. your query resolves according to the *ALLIO optimize parameter. Biases the optimization toward not creating an index. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 425 . – Compares the cost of using this index with the previous cost (current best). the optimization time is not limited. the optimizer does the following until its time limit is exceeded: – Extracts attributes of the index from internally stored statistics. For any query. – Determines the cost of using the index using the estimated page faults and the predicate filter factors to help determine the cost. The time limit factor controls how much time is spent choosing an implementation. The optimizer: v Determines the default filter factor for each predicate in the selection clause.Page faults and the number of rows processed are dependent on the type of access the optimizer chooses. if you specify OPTALLAP(*YES). v Extracts attributes of the table from internally stored information. whenever optimization occurs. Chapter 24. along with the query definition template (QDT). v Determines the cost of creating an index over a table if an index is required. The information is kept in what is called a mini plan. v For a DB2 UDB for AS/400 program. an optimized plan of how to access the requested data is developed. Refer to “Data Management Methods” on page 396 for more information on access methods. – Determines if the index meets the selection criteria. A new access plan is created each time the OPNQRYF command is processed. – Continues to search for best index until time out or no more indexes. an access plan is created. It is based on how much time was spent so far and the current best implementation cost found. v For each index available. v Determines the cost of using a sort routine or hashing method if selection conditions apply and an index is required. The mini plan. For OPNQRYF. v For Query/400. Access Plan Validation An access plan is a control structure that describes the actions necessary to satisfy each query request. v Determines the cost of dataspace scan processing if an index is not required. – Picks the cheaper one. An access plan contains information about the data and how to extract it. v For dynamic SQL. an access plan is created but is not saved. the access plan is saved in the associated space of the program or package that contains embedded SQL statements. but the plan is not saved. A new access plan is created each time the PREPARE statement is run. v For OPNQRYF. Optimizer Decision-Making Rules In performing its function. an access plan is saved as part of the query definition object. Dynamic SQL queries are subject to the optimizer time restrictions. v Performs an estimate key range to determine the true filter factor of the predicates when the selection predicates match the left-most keys of an index. is used to interface with the optimizer and make an access plan. the optimizer uses a general set of guidelines to choose the best method for accessing data. in the order of most recently created to oldest. Static SQL queries optimization time is not limited. Generally. Uses key positioning to locate the first row that satisfies the join condition for the first secondary table using a keyed access path with keys matching the join condition or local row selection columns of the secondary table. the query optimizer considers more indexes. Each join table position is called a dial. For this method. DB2 UDB for AS/400: 1. It also describes design tips and techniques which help avoid or solve performance problems. LEFT OUTER JOIN or EXCEPTION JOIN (OPNQRYF JDFTVAL(*YES) or JDFTVAL(*ONLYDFT) parameter). Steps 1 through 5 are repeated until a row that satisfies both the join condition and any remaining selection is selected from all secondary tables 6. if applicable. During the join. Returns the result join row. 5. The first table in the final join order is called the primary table. If the secondary dial row is not selected then the next row that satisfies the join condition is located. The optimization for other types of joins. but most of the information and tips in this section also apply to joins of this type. For large tables. This section describes how DB2 UDB for AS/400 implements inner join queries and how optimization choices are made by the query optimizer. Join Optimization | | | | | | | | | | | A join operation is a complex function that requires special attention in order to achieve good performance. the query optimizer spends little time in query optimization. Builds a key value from the join columns in the primary table. Applies bitmap selection. This order is called the join order. Information about these types of joins will not be detailed here. Nested Loop Join Implementation DB2 UDB for AS/400 provides a nested loop join method. Processes the last secondary table again to find the next row that satisfies the join condition in that dial. 426 DB2 UDB for AS/400 SQL Programming V4R4 . Accesses the first primary table row selected by the predicates local to the primary table. the optimizer considers five or six indexes (for each table of a join) before running out of optimization time. the processing backs up to the logical previous dial and attempts to read the next row that satisfies its join condition. then that table becomes the primary table and is processed with a keyed access path over the table. The other tables are called secondary tables.For small tables. is similar except that the join order is always the same as the order of the tables specified in the FROM clause (OPNQRYF FILE paramter). the processing of the tables in the join are ordered. 2. 8. Note the following characteristics of a nested loop join: v If ordering or grouping of result rows is specified over a single table. when no more rows that satisfy the join condition can be selected. During this processing. Determines if the row is selected by applying any remaining selection local to the first secondary dial. 4. 7. 3. Ends processing when all selected rows from the primary table are processed. Any inefficiencies in the processing of the later dials can significantly inflate the query processing time. a temporary keyed access path is created. 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. | | | | The query optimizer might also decide to break the query into these two parts to improve performance when the SQL ALWCPYDTA(*OPTIMIZE) precompiler parameter or the OPNQRYF KEYFLD. Because efficiency is very important for secondary dials of longer running queries. 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. This allows the optimizer to consider any table of the join query as a candidate for the primary table. Rows are retrieved from secondary tables in random sequence. Since a given secondary dial is searched once for each row selected from the primary and the preceding secondary dials that satisfy the join condition for each of the preceding secondary dials. v All rows that satisfy the join condition from each secondary dial are located using a keyed access path. Instead of using keyed access paths to locate the matching rows in a secondary table. 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. 2. This random disk I/O time often accounts for a large percentage of the processing time of the query. v The hash temporary result table can be built using SMP parallelism.v If ordering or grouping of processing of the join result rows is specified on tables from other than the primary dial or on columns from two or more dials. 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. all selected rows from secondary dials are accessed through a keyed access path. The location of the rows for any given join value can be found by applying a hashing function to the join value. so all matching rows for a given join value can usually be accessed with a single I/O request. Chapter 24. and ALWCPYDTA(*OPTIMIZE) parameters are specified. v Like join values are clustered. v Again. a large number of searches may be performed against the later dials. Some join queries build temporary access paths over secondary dials even when an access path exists for all of the join keys. Hash Join The hash join method is similar to nested loop join. a hash temporary result table is created that contains all of the rows selected by local selection against the table. so less CPU processing is required to build and probe a hash table. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 427 . If an efficient keyed access path cannot be found. The structure of the hash table is such that rows with the same join value are loaded into the same hash table partition (clustered). Process the join query omitting the ordering or grouping processing and write the result rows to a temporary work table. The ordering or grouping processing is then performed on the data in the temporary work table. DB2 UDB for AS/400 breaks the processing of the query into two parts: 1. 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. however. 3. 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. Hash join can be used with OPTIMIZE(*YES) if a temporary result is required to run the query. hash join queries can use SMP parallelism if the query attribute DEGREE is set to either *OPTIMIZE. or *NBRTASKS. *MAX. The Client Access/400 ODBC driver and Query Management driver always uses this mode. This occurs when the query is opened.EMPNO OPTIMIZE FOR 99999999 ROWS | | | | | | | OPNQRYF example : OPNQRYF FILE((EMPLOYEE EMP_ACT)) FORMAT(FORMAT1) JFLD((1/EMPNO 2/EMPNO *EQ)) ALWCPYDTA(*OPTIMIZE) This query is implemented using the following steps: 1. 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. However. The existence of a hash table does not affect the processing cost of other updating jobs in the system. EMP_ACT WHERE EMPLOYEE. 2. A temporary hash table is built over table EMP_ACT with a key of EMPNO. v Require that the cursor position be restored as the result of the SQL ROLLBACK HOLD statement or the ROLLBACK CL command. This parameter can be specified either on precompiler commands.v Unlike indexes. this requires that *ALLREAD be specified as the value for the ALWBLK precompiler parameter. 428 DB2 UDB for AS/400 SQL Programming V4R4 . For SQL applications using commitment control level other than *NONE. For each row retrieved from the EMPLOYEE table. For each matching row found. entries in hash tables are not updated to reflect changes of column values in the underlying table. Hash join cannot be used for queries that: v Perform subqueries unless all subqueries in the query can be transformed to inner joins. The following is an example of a join query that would process all of the rows from the queried tables: SELECT * FROM EMPLOYEE. which can be changed by using the Change Query attribute CL command (CHGQRYA). a result row is returned. Hash join is used only for queries running with ALWCPYDTA(*OPTIMIZE). the temporary hash table will be probed for any matching join values. the STRSQL CL command. v Require live access to the data as specified by the *NO or *YES parameter values for the ALWCPYDTA precompiler parameter.EMPNO = EMP_ACT. or the OPNQRYF CL command. v Perform left outer or exception join. does not enable or disable the optimizer from choosing to use hash join. v Use a DDS created join logical file. The query attribute DEGREE. v Perform a UNION or UNION ALL. ’D21’. DEPTNO IN (’A00’. The messages created by the PRTSQLINF CL command to describe this hash join query in an SQL program would appear as follows: SQL402A SQL402B SQL402B Hashing algorithm used to process join. the query will be completed using the temporary table. DEPARTMENT EMPLOYEE. 'D11'. a result row is returned. 'D21'.MGRNO OPTIMIZE FOR 99999999 ROWS | | | | | OPNQRYF example: OPNQRYF FILE((EMPLOYEE DEPARTMENT) FORMAT(FORMAT2) JFLD((1/WORKDEPT 2/DEPTNO *EQ) (1/EMPNO 2/MGRNO *GT)) Chapter 24. LASTNAME. DEPARTMENT WHERE EMPLOYEE. 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 EMPNO. ’E11’). ’D01’. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 429 . LASTNAME. File EMPLOYEE used in hash join step 1. For each row retrieved from the EMPLOYEE table matching the selection predicate. File EMPLOYEE used in hash join step 1. as a second step. The following is an example of a join query with selection specified with operands derived from columns of different tables: SELECT EMPNO. 'D01'.The messages created by the PRTSQLINF CL command to describe this hash join query in an SQL program would appear as follows: SQL402A SQL402B SQL402B Hashing algorithm used to process join. grouping. 3. or result columns are derived from columns of different tables. 2. For each matching row found. DEPTNAME FROM EMPLOYEE. File DEPARTMENT used in hash join step 2.DEPTNO IN ('A00'. DEPTNAME EMPLOYEE. File EMP_ACT used in hash join step 2. A temporary hash table is built over table DEPARTMENT with key values of DEPTNO containing rows matching the selection predicate. HIREDATE BETWEEN 1996-01-30 and 1995-01-30.DEPTNO EMPLOYEE. the temporary hash table will be probed for the matching join values. the hash join processing will be done and the result rows of the join will be written to a temporary table.WORKDEPT = DEPARTMENT. Then.EMPNO > DEPARTMENT.WORKDEPT = DEPARTMENT.DEPTNO AND EMPLOYEE. ’D11’. non-equal selection specified with operands derived from columns of different tables. 'E11') FOR 99999999 ROWS | | | | | | | | | OPNQRYF example: OPNQRYF FILE((EMPLOYEE DEPARTMENT)) FORMAT(FORMAT2) QRYSLT('1/HIREDATE *EQ %RANGE(''1996-01-30'' ''1995-01-30'') *AND 2/DEPTNO *EQ %VALUES(''A00'' ''D01'' ''D11'' ''D21'' ''E11''') JFLD((1/WORKDEPT 2/DEPTNO *EQ)) ALWCPYDTA(*OPTIMIZE) This query is implemented using the following steps: 1.HIREDATE BETWEEN 1996-01-30 AND 1995-01-30 DEPARTMENT. This occurs when the query is opened. When ordering. When looking for an existing keyed access path to access a secondary dial. for the second dial the only join specifications that can be used to satisfy the join condition are join specifications which reference columns in the primary dial. the third dial can only use join specifications which reference columns in the primary and the second dials and so on. Join specifications which reference later dials are deferred until the referenced dial is processed. File DEPARTMENT used in hash join step 2. a result row is written to a temporary table. For example. For each row retrieved from the EMPLOYEE table. 2. Join Optimization Algorithm The query optimizer must determine the join columns. Join specifications which are not implemented for the dial are either deferred until they can be processed in a later dial or. 3. the only join specifications which are usable as join columns for that dial are those being joined to a previous dial. A temporary hash table is built over table DEPARTMENT with a key of DEPTNO. Temporary result table created for hash join query. only one type of join operator is normally implemented. Likewise. rows that are selected by EMPNO > MGRNO are read from the temporary file and returned to the application. local row selection. The join columns and join operators depend on the: v v v v Join column specifications of the query Join order Interaction of join columns with other row selection Keyed access path used. the join specifications which use the left-most key columns can be used. File EMPLOYEE used in hash join step 1. if an inner join was being performed for this dial.| This query is implemented using the following steps: 1. keyed access path usage. The ’>’ join specification is processed as row selection after a matching row for the ’=’ specification is found. Note: For OPNQRYF. In addition. only one type of join operator is allowed for either a left outer or an exception join. For a given dial and keyed access path. the query optimizer looks at the left-most key columns of the access path. join operators. For any given dial. For example: | | | | 430 DB2 UDB for AS/400 SQL Programming V4R4 . After all of the join result rows are written to the temporary table. For each matching row found. if one inner join join specification has a join operator of ’=’ and the other has a join operator of ’>’. This occurs when the query is opened. For a given dial. the optimizer attempts to implement the join with the ’=’ operator. The messages created by the PRTSQLINF CL command to describe this hash join query in an SQL program would appear as follows: SQL402A SQL402B SQL402B SQL402C Hashing algorithm used to process join. multiple join specifications that use the same operator are implemented together. For example. 4. and dial ordering for a join query. processed as row selection. the temporary hash table will be probed for the matching join values. the join operation is performed only on column EMPNO. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 431 . After the join is processed. the left-most key columns are the usable join columns in that dial position. an existing index may be used or a temporary index may be created. EMP_ACT.EMPNO AND EMPLOYEE. EMSTDATE or EMSTDATE. and EMSTDATE. the temporary access path would have key fields of EMP_ACT and EMSTDATE (to match the join selection).PROJNO = '123456' OPTIMIZE FOR 99999 ROWS | | | | | | OPNQRYF example: OPNQRYF FILE((EMPLOYEE. However.EMPNO = EMP_ACT. PROJNO. The temporary index for the previous example would have key fields of EMPNO and EMSTDATE. as happens when the temporary access path is created)..EMSTDATE OPTIMIZE FOR 99999 ROWS | | | | | OPNQRYF example: OPNQRYF FILE((EMPLOYEE. 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. PROJNO.. | | | | | | | | | | | | | | | Since the OS/400 query optimizer attempts a combination of join and local record selection when determining access path usage. A temporary keyed access path is similar to the access path created for a select/omit keyed logical file. row selection is done using column EMSTDATE. If.EMPNO = EMP_ACT. A temporary access path would have been built with the local row selection on PROJNO applied during the access path’s creation. the use of the existing keyed Chapter 24. If the previous example had been expressed with a local predicate as: DECLARE BROWSE2 CURSOR FOR SELECT * FROM EMPLOYEE.EMPNO AND EMPLOYEE.DECLARE BROWSE2 CURSOR FOR SELECT * FROM EMPLOYEE. EMP_ACT WHERE EMPLOYEE. PROJNO. EMP_ACT)) FORMAT(FORMAT1) JFLD((1/EMPNO 2/EMP_ACT *EQ)(1/HIREDATE 2/EMSTDATE *EQ)) For the keyed access path over EMP_ACT with key columns EMPNO.EMSTDATE AND EMP_ACT. EMP_ACT)) FORMAT(FORMAT2) QRYSLT('2/PROJNO *EQ ''123456''') JFLD((1/EMPNO 2/EMP_ACT *EQ)(1/HIREDATE 2/EMSTDATE *EQ)) the keyed access path with key columns EMPNO. EMP_ACT or . and EMSTDATE are fully utilized by combining join and selection into one operation against all three key columns. using either implementation. it is possible to achieve almost all of the same advantages of a temporary keyed access path by use of an existing access path. In the above example. instead. The query optimizer also uses local row selection when choosing the best use of the keyed access path for the secondary dial. When creating a temporary keyed access path. an existing keyed access path was used with key fields of EMP_ACT.HIREDATE = EMP_ACT. EMSTDATE (or PROJNO. EMP_ACT WHERE EMPLOYEE.) the local record selection could be applied at the same time as the join selection (rather than prior to the join selection. PROJNO.HIREDATE = EMP_ACT. All local row selection for that dial is processed when selecting keys for inclusion into the temporary keyed access path. | | | | access path may have just slightly slower I/O processing than the temporary access path because the local selection is run many times rather than once. If the join query with row ordering or group by processing is being processed in one step. 3. This costing value is a combination of CPU and I/O time and is based on the following assumptions: v Table pages and keyed access path pages must be retrieved from auxiliary storage. 2. and determines the lowest cost access methods. Choose the secondary table with the lowest join cost. As the query optimizer compares the various possible access choices. 7. Choose the combination with the lowest join cost. Repeat steps 4 through 7 until the lowest cost join order is determined. Determine an access method. 8. When a join logical file is referenced. the following join ordering algorithm is used to determine the order of the tables: 1. choose the combination which selects the fewest rows. cost. The choices made are similar to those for row selection except that a keyed access path must be used. Join Order Optimization | | | | | | | | | | | | | | | | | | | | | | | | | | | | | The join order is fixed if any join logical files are referenced or a left outer or an exception join is used to implement any of the dials of the join. Otherwise. Select an access method for each table that has the lowest cost for that table. The join order is also fixed if the OPNQRYF JORDER(*FILE) parameter is specified or the query options file (QAQQINI) FORCE_JOIN_ORDER parameter is *YES. the query optimizer is not aware that an entire table may be loaded into active memory as the result of a SETOBJACC CL command. Determine an access method for each individual table as candidates for the primary dial. 432 DB2 UDB for AS/400 SQL Programming V4R4 . and expected number of rows for each remaining table joined to the previous secondary table. access method. 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 4. and expected number of rows returned for each join combination of candidate tables as primary and first secondary tables. Estimate the number of rows returned for each table based on local row selection. the query optimizer loops through all of the dials in the order specified. In general. If the cost is nearly the same. 6. Determine the cost. Costing and Selecting Access Paths for Join Secondary dials In step 3 and in step 5. For example. 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. the query optimizer has to estimate a cost and choose an access method for a given dial combination. then choose the combination which selects the fewest rows. If the cost is nearly the same. a left outer or an excpetion join. then the table with the ordering or grouping columns is the primary table. or the join order is forced to the specified file order. it must assign a numeric cost value to each candidate and use that value to determine the implementation which consumes the least amount of processing time. 5. the cartesian product is assumed to be the operator. 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. the expected number of matching rows is . An index that contains fixed length character keys defined over varying length data supplies average number of duplicate values statistics. each of the rows selected from previous dials. No allowance is given for system CPU utilization or I/O waits which occur because of other processes using the same resources. Chapter 24. v The values in a column are independent from the values in any other columns in a row. Note: If you have varying length character columns used as join columns.33 * (number of rows in the dial). you can create an index which maps the varying length character column to a fixed character key using the CRTLF CL command. The query optimizer uses these statistics when it is optimizing a query.Usage of this command may significantly improve the performance of a query. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 433 . For example. v Were created or rebuilt on an AS/400 system on which Version 2 Release 3 or a later version is installed. 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. 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. then it is assumed that every tenth row in the table contains that value. if 10% of the rows in a table have the same value. the expected number of matching rows is based on the following default filter factors: v 33% for less-than. but the query optimizer does not change the query implementation to take advantage of the memory resident state of the table. or greater-than-equal-to v 90% for not equal | | v 25% for BETWEEN range (OPNQRYF %RANGE) v 10% for each IN list value (OPNQRYF %VALUES) For example. These statistics are bound with the index object and are always maintained. then it is expected that a query which selects rows where A = 1. when the join operator is less-than. For cartesian products. This statistical information is only available for indexes which: v Contain no varying length character keys. v The values in a column are uniformly distributed across the table. the number of matching rows is every row in the dial. CPU related costs are scaled to the relative processing speed of the system running the query. When the join operator is something other than equal. on average. Both of these factors can be derived by estimating the number of matching rows for a given dial. unless local row selection can be applied to the keyed access path. Maintaining these statistics adds no measurable amount of overhead to index maintenance. When the join operator is equal. the expected number of rows is the average number of duplicate rows for a given value. less-than-equal-to. If no join specifications are active for the current dial. v The query is the only process running on the system. For example. greater-than. Key2. The number of matching rows for dial n.. Three Field Key ┌───────┬───────┬───────┐ │ Key 1 │ Key 2 │ Key 3 │ └───┬───┴───┬───┴───┬───┘ │ │ │ │ │ Number │ │ of unique │ │ keys for │ │ Key 1 │ │ │ │ │ └───┬───┘ │ │ Number of │ unique keys │ for Key1 │ and Key 2 │ combination │ │ │ └─────┬─────┘ Number of unique keys for Key 1. and Key 3 combination (the full key) Figure 14. Using the average number of duplicate values for equal joins or the default filter value for the other join operators. 434 DB2 UDB for AS/400 SQL Programming V4R4 . additional keys in the index cause matching row estimates through that index to not be valid.. This is particularly important if some of the join columns are somewhat unique (low average number of duplicate values). *Mn * FFn . Rp M2 FF2 Mn The number of rows selected from the primary dial...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. Average number of duplicate values statistics are maintained only for the first 4 left-most keys of the index.. 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. NPREV = Rp * M2 * FF2 * .. the estimate is done based on the size of the index. Average number of duplicate values of a 3 key index These statistics are maintained as part of index rebuild and creation. The following formula is used to compute the number of join rows from previous dials. The number of matching rows for dial 2. NPREV The number of join rows from all previous dials.. Filtering reduction factor for predicates local to dial 2 that are not already applied using M2 above.. For queries which specify more than 4 join columns. In many cases. The performance of some join queries may be improved by rebuilding these access paths. we now have the number of matching rows. If the index is defined with only the join keys. This method can be better than using any existing access path because the row selection is completed when the keyed access path or hash table is created if any of the following are true: v The number of matches (MATCH) is high. For more information. Temporary Keyed Access Path or Hash Temporary Result Table from Table The first access method choice analyzed by the query optimizer is building a temporary keyed access path or hash temporary result table from the table. The basic formula for costing access of a join secondary dial through a temporary keyed access path built from the table or hash table follows: JSCOST = 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) 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. see “Cost Estimation” on page 423. v There is some filtering reduction (FF < 100%).FFn Filtering reduction factor for predicates local to dial n that are not already applied using Mn above. This secondary dial access method is used if no usable keyed access path is found or if the temporary keyed access path or hash table performs better than any existing keyed access path. v The number of join rows from all previous dials (NPREV) is high. the optimizer is ready to generate a cost for the access method. Chapter 24. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 435 . Now that it has calculated the number of join rows from previous dials. Note: Multiply the pair of matching rows (Mn) and filter reduction filter factors (FFn) for each secondary dial preceding the current dial. the query optimizer may do some special processing to generate additional selection. For more information. the query optimizer generates additional predicates. this may be the most efficient method. The basic formula for costing access of a join secondary dial through an existing keyed access path is: JSCOST = NPREV *((MATCH * KeyAccess) + (MATCH * FCost)) * FirstIO 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. CRTDSI. if the number of join rows from all previous dials (NPREV). and the number of matching keys (MATCH) is low. Also. 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. The purpose is to provide more information during join optimization. the creation from a keyed access path might be less costly. this is a likely access method because the entire cost is reduced. v The number of rows being selected from the previous dials is small. This access method is used for join secondary dial access for the same reason. with one exception.Temporary Keyed Access Path or Hash Table from Keyed Access Path The basic cost formula for this access method choice is the same as that of using a temporary keyed access path or hash table built from a table. is calculated to include the selection of the rows through an existing keyed access path. However. OPNQRYF OPTIMIZE(*FIRSTIO)). see “Cost Estimation” on page 423. 436 DB2 UDB for AS/400 SQL Programming V4R4 . Use an Existing Keyed Access Path The final access method is to use an existing keyed access path. When the set of predicates that belong to a query logically infer extra predicates. Predicates Generated Through Transitive Closure For join queries. The cost to build the temporary keyed access path. If I/O optimization is used (that is. *LT. Note: This section does not apply to OPNQRYF.EMPNO = '000010'OPNQRYF example: | | | | | | | | | | | OPNQRYF example: OPNQRYF FILE((EMPLOYEE EMP_ACT)) FORMAT(FORMAT1) QRYSLT('1/EMPNO *EQ ''000010''') JFLD((1/EMPNO 2/EMPNO *EQ)) The optimizer will modify the query to be: OPNQRYF FILE((EMPLOYEE EMP_ACT)) FORMAT(FORMAT1) QRYSLT('1/EMPNO *EQ ''000010'' *AND 2/EMPNO *EQ ''000010''') JFLD((1/EMPNO 2/EMPNO *EQ)) The following rules determine which predicates are added to other join dials: v The dials affected must have join operators of equal.Example of Predicates being Added Because of Transitive Closure SELECT * FROM EMPLOYEE. Some predicates are redundant. EMP_ACT WHERE EMPLOYEE. v The predicate is not connected to other predicates by OR. *LE. EMP_ACT WHERE EMPLOYEE.EMPNO AND EMPLOYEE. | | | | | | | | | | The query optimizer generates a new predicate. >. This requires the optimizer to determine what the overall join type for the query should be. or BETWEEN (OPNQRYF *EQ. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 437 .EMPNO = '000010' The optimizer will modify the query to be: SELECT * FROM EMPLOYEE.EMPNO = '000010' AND EMP_ACT. v One operand of the predicate is an equal join column and the other is a literal or host variable. <=. or %RANGE) are merged into a single predicate to reflect the most selective range. This occurs when a previous evaluation of other predicates in the query already determines the result that predicate provides.EMPNO = EMP_ACT. v The predicate is isolatable.EMPNO = EMP_ACT. or *CT). which means that a false condition from this predicate would omit the row. the AS/400 Licensed Internal Code can only support one join type for the entire query. >=. *GE. Chapter 24. v The join type for the dial is an inner join. v The predicate operator is not LIKE or IN (OPNQRYF %WLDCRD. Redundant predicates with predicate operators of =. left outer and exception) can be specified in the query using the JOIN syntax. <. *GT. Multiple Join Types for a Query Even though multiple join types (inner. whether or not a predicate already exists in the WHERE clause (OPNQRYF QRYSLT parameter). Redundant predicates can be specified by you or generated by the query optimizer during predicate manipulation. %VALUES.EMPNO AND EMPLOYEE. EMPNO = YYY.PROJECT ZZZ ON XXX. XXX. This means that the number of resulting rows that satisfy the join criteria can become quite large before any selection is applied that will either select or omit the unmatched rows based on that individual dial’s join type. In the following example a left outer join is specified between the tables EMPLOYEE and DEPARTMENT. This occurs when: v An access path is not available which provides average number of duplicate values statistics for the potential join columns.The optimizer will evaluate the join criteria along with any record selection that may be specified in order to determine the join type for each dial and for the entire query. PROJNO FROM CORPDATA. SELECT EMPNO. 'E11') The first selection predicate.EMPNO = YYY. For more information on how to use the JOIN syntax see either “Joining Data from More Than One Table” on page 75 or the DB2 UDB for AS/400 SQL Reference book. LASTNAME. Note: Care must be taken when specifying multiple join types since they are supported by appending selection to the query for any unmatched rows. DEPTNAME. will cause all of the unmatched records to be eliminated (unless the selection is for an IS NULL predicate). is an additional join condition that will be added to the join criteria and evaluated as an ″inner join″ join condition.EMPNO = ZZZ. Once this information is known the optimizer will generate additional selection using the relative record number of the tables to simulate the different types of joins that may occur within the query. 438 DB2 UDB for AS/400 SQL Programming V4R4 . Either one of these selection predicates will cause the join type for the DEPARTMENT table to be changed from a left outer join to an inner join. Note: “Costing and Selecting Access Paths for Join Secondary dials” on page 432 provides suggestions on how to avoid the restrictions about indexes statistics or create additional indexes over the potential join columns if they do not exist. Since null values are returned for any unmatched rows for either a left outer or an exception join. In the WHERE clause there are two selection predicates that also apply to the DEPARTMENT table.RESPEMP WHERE XXX.WORKDEPT = YYY. The second is an isolatable selection predicate that will eliminate any unmatched records.DEPTNO LEFT OUTER JOIN CORPDATA. 'D11'. any isolatable selection specified for that dial. Even though the join between the EMPLOYEE and the DEPARTMENT table was changed to an inner join the entire query will still need to remain a left outer join to satisfy the join condition for the PROJECT table.MGRNO. This will cause the join type for that dial to be changed to an inner join (or an exception join) if the IS NULL predicate was specified. 'D01'. including any additional join criteria that may be specified in the WHERE clause.EMPLOYEE XXX LEFT OUTER JOIN CORPDATA.DEPARTMENT YYY ON XXX.DEPTNO IN ('A00'. but the performance of a few queries may be degraded.MGRNO AND YYY. 'D21'. Sources of Join Query Performance Problems The optimization algorithms described above benefit most join queries. Chapter 24. This step helps if the statistical characteristics are not uniform for the entire table. Check the query to see whether some complex predicates should be added to other dials to allow the optimizer to get a better idea of the selectivity of each dial. Note: The optimizer can better determine from the select/omit access path that the data is not uniformly distributed. v The particular values selected for the join columns yield a significantly greater number of matching rows than the average number of duplicate values for all values of the join columns in the table (i. specifying the precompile option ALWCPYDTA(*YES) makes it more likely that the queries in that program will use an existing index. Make sure that there are indexes available over all of the join columns and/or row selection columns. | | | | Improving Performance of Join Queries If you are looking at a join query which is performing poorly or you are about to create a new application which uses join queries. modifying the query by adding these predicates may help.e. make sure that the index is not shared. the data is not uniformly distributed). DB2 UDB for AS/400 Data Management and Query Optimizer Tips 439 . specifying ALWCPYDTA(*OPTIMIZE) makes it more likely that the queries in that program will create a temporary index. Many queries may be able to use the existing index to implement the query and avoid the cost of creating a temporary index. the following checklist may be useful. How It Helps This gives the query optimizer a better opportunity to select an efficient access method because it can determine the average number of duplicate values. This provides the query optimizer with a more accurate estimate of the number of matching rows for the keys which are selected. Since the query optimizer does not add predicates for predicates connected by OR or non-isolatable predicates. Table 39. Specify *ALLIO to make the creation of a temporary index more likely. Specify *FIRSTIO to make the use of an existing index more likely. Likewise. Checklist for Creating an Application that Uses Join Queries What to Do Check the database design. then a select/omit keyed access path allows the optimizer to skew the distribution of values for that key and make the right optimization for the selected values.v The query optimizer uses default filter factors to estimate the number of rows being selected when applying local selection to the table because indexes do not exist over the selection columns. Use DDS to build a logical file with a keyed access path with select/omit specifications matching the local row selection. the wrong performance option for the OPTIMIZE keyword may have been specified. v The query optimizer makes the wrong assumption about the number of rows which will be retrieved from the answer set. if there is one value which has a high duplication factor and the rest of the column values are unique. If using CRTLF. Create a keyed access path which includes Select/Omit specifications which match that of the query using CRTLF CL command. For SQL programs. For the OPNQRYF command. Creating indexes over the selection columns allows the query optimizer to make a more accurate filtering estimate by using key range estimates. For example. or predicate operators of LIKE or IN. The SQL clause OPTIMIZE FOR n ROWS can also be used to influence the query optimizer. | | | | For OPNQRYF. To do this set n to a large number. specify ALWCPYDTA(*OPTIMIZE). 440 DB2 UDB for AS/400 SQL Programming V4R4 .Table 39. If the query is creating a temporary keyed access path and you feel that the processing time would be better if it would only use the existing access path. specify ALWCPYDTA(*YES). specify the OPTIMIZE FOR n ROWS to inform the optimizer of the application has intention to read every resulting row. and you feel that the processing time would be better if the optimizer only used the existing access path. then specify OPTIMIZE(*FIRSTIO). Checklist for Creating an Application that Uses Join Queries (continued) What to Do Specify ALWCPYDTA(*OPTIMIZE) or ALWCPYDTA(*YES) How It Helps If the query is creating a temporary keyed access path. and you feel that the processing time would be better if a temporary keyed access path was created. specify | OPTIMIZE(*FIRSTIO) or | OPTIMIZE(*ALLIO) | | Alternatively. If the query is not creating a temporary keyed access path and you feel that the processing time would be better if a temporary keyed access path was created then specify OPTIMIZE(*ALLIO). You could also set n to a small number before ending the query. If the query is not creating a temporary keyed access path. The reason for forcing the file into the first position is to avoid random I/O processing.EMPNO=EMPLOYEE. This allows the query optimizer to choose the best order for the remaining files. The query should be changed to force EMPLOYEE into join position one by using the query options file (QAQQINI) FORCE_JOIN_ORDER parameter of *YES or OPNQRYF JORDER(*FILE) as shown in example B. DEPARTMENT.DEPTNO OPNQRYF Example A: Start join query OPNQRYF FILE((DEPARTMENT EMP_ACT EMPLOYEE PROJECT)) FORMAT(FORMAT1) JFLD((1/DEPTNO 3/WORKDEPT *EQ) (2/EMPNO 3/EMPNO *EQ) (3/WORKDEPT 4/DEPTNO *EQ)) Example B: Start join query with JORDER(*FILE) parameter OPNQRYF FILE((EMPLOYEE DEPARTMENT EMP_ACT PROJECT)) FORMAT(FORMAT1) JFLD((2/DEPTNO 1/WORKDEPT *EQ) (3/EMPNO 1/EMPNO *EQ) (1/WORKDEPT 4/DEPTNO *EQ)) JORDER(*FILE) Note: Specifying fields from EMPLOYEE in the ORDER BY clause (OPNQRYF KEYFLD parameter) may also have the effect of placing EMPLOYEE in join position 1. By forcing EMPLOYEE to the first position. Chapter 24.EMPNO AND EMPLOYEE. EMP_ACT. If EMPLOYEE is fairly large. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 441 . all files are joined to file EMPLOYEE. Checklist for Creating an Application that Uses Join Queries (continued) What to Do How It Helps A join in which one file is joined with all secondary files consecutively is sometimes called a star join (star join should be in bold). PROJECT WHERE DEPARTMENT. Note that in these examples the join type is a join with no default values returned (this is an inner join. EMP_ACT.).WORKDEPT=PROJECT. PROJECT WHERE DEPARTMENT. In the case of a star join where all secondary join predicates contain a field reference to a particular file.EMPNO AND EMPLOYEE. In Example A.Table 39. Specify ALWCPYDTA(*OPTIMIZE) In the cases where ordering is specified and all key columns are from a single to allow the query optimizer to use dial. a sort routine. random I/O processing is minimized. this allows the query optimizer to consider all possible join orders. every record in EMPLOYEE could be examined repeatedly during the join process. Example A: Start join query DECLARE C1 CURSOR FOR SELECT * FROM DEPARTMENT.DEPTNO=EMPLOYEE.DEPTNO Example B: Star join query with order forced via FORCE_JOIN_ORDER DECLARE C1 CURSOR FOR SELECT * FROM EMPLOYEE.WORKDEPT=PROJECT. EMPLOYEE. The query optimizer can freely determine the join order.DEPTNO=EMPLOYEE.EMPNO=EMPLOYEE. If EMPLOYEE is not in join position one.WORKDEPT AND EMP_ACT. OPNQRYF users can specify JORDER(*FILE). there may be performance advantages if that file is placed in join position one. considerable random I/O processing occurs resulting in poor performance.WORKDEPT AND EMP_ACT. | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Use a join logical file or use the query options file (QAQQINI) FORCE_JOIN_ORDER parameter of *YES. Table 39. If you give the optimizer extra information to work with when requesting a join. specify: OPNQRYF FILE(CORPDATA/DEPARTMENT CORPDATA/EMPLOYEE CORPDATA/EMP_ACT) FORMAT(FORMAT1) JFLD((1/MGRNO 2/EMPNO *EQ) (2/EMPNO 3/EMP_ACT *EQ)) Provide the optimizer with a little more data and code: EXEC SQL DECLARE EMPACTDATA CURSOR FOR SELECT LASTNAME. | | | | | When using the OPNQRYF command. DEPTNAME.MGRNO = EMPLOYEE. DEPTNAME. The following suggestion is directed specifically to select-statements that access several tables. CORPDATA. Every secondary file should have at least one join predicate that references on of its fields as a ’join-to’ field.EMPNO AND EMPLOYEE. ACTNO FROM CORPDATA. Checklist for Creating an Application that Uses Join Queries (continued) What to Do How It Helps This improves performance by reducing the join fan-out.EMPNO END-EXEC.EMPNO END-EXEC. PROJNO.EMPNO AND DEPARTMENT.EMPNO = EMP_ACT. ACTNO FROM CORPDATA. but is helpful to the optimizer. all the recommendations suggested in “Effectively Using SQL Indexes” on page 446 apply.EMPNO AND EMPLOYEE. For each selected row. instead of coding: EXEC SQL DECLARE EMPACTDATA CURSOR FOR SELECT LASTNAME.EMPLOYEE.EMP_ACT WHERE DEPARTMENT. Grouping Hash Implementation This technique uses the base hash access method to perform grouping or summarization of the selected table rows. CORPDATA.EMPNO = EMP_ACT. For example.EMPLOYEE.MGRNO = EMP_ACT. | | | | Specify join predicates to prevent all of the records from one file from being joined to every record in the other file.DEPARTMENT.DEPARTMENT. CORPDATA. Improving Performance When Selecting Data from More than Two Tables If the select-statement you are considering accesses two or more tables. The additional information might seem redundant. PROJNO. CORPDATA. For joins that involve more than two tables. specify: OPNQRYF FILE(CORPDATA/DEPARTMENT CORPDATA/EMPLOYEE CORPDATA/EMP_ACT) FORMAT(FORMAT1) JFLD((1/MGRNO 2/EMPNO *EQ) (2/EMPNO 3/EMP_ACT *EQ) (1/MGRNO 3/EMPNO *EQ)) Grouping Optimization This section describes how DB2 UDB for AS/400 implements grouping techniques and how optimization choices are made by the query optimizer.EMP_ACT WHERE DEPARTMENT.MGRNO = EMPLOYEE. It can determine the best way to do the join. | | | | | | When using the OPNQRYF command. you might want to provide redundant information about the join columns. the specified 442 DB2 UDB for AS/400 SQL Programming V4R4 . Since the index. The computed hash value and grouping value are used to quickly find the entry in the hash table corresponding to the grouping value.grouping value is run through the hash function. Before returning any results. by definition. As mentioned earlier. The time required to receive the first group result for this implementation will most likely be longer than other grouping implementations because the hash table must be built and populated first. This in turn will slow down the hashing access method. then the hash table will become too large. specifying grouping value columns that are not associated with the variable length and null column attributes allows the hash function to perform more effectively. already has all of the key values grouped together. Indexes improve the accuracy because they contain statistics that include the average number of duplicate values for the key columns. If every database table row has its own unique grouping value. This is because of the temporary result that is required for the hashing method. If the current grouping value already has a row in the hash table. The optimizer also uses the expected number of groups estimate to compute the number of partitions in the hash table. the first group result can be returned in less time than the hashing method. The database manager accesses the individual groups through the keyed access path and performs the requested summary functions. The optimizer then examines the total number of rows in the table and the specified selection criteria and uses the result of this examination to estimate the consolidation ratio. This Chapter 24. the database manager uses the table to start returning the grouping results. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 443 . The grouping hash method is most effective when the consolidation ratio is high. The consolidation ratio is the ratio of the selected table rows to the computed grouping results. the database manager must apply any specified grouping selection criteria or ordering to the summary entries in the hash table. Indexes over the grouping columns can help make the optimizer’s ratio estimate more accurate. In addition. with the exception of the integer (binary) data type. An index is required that contains all of the grouping columns as contiguous leftmost key fields. The number of hash table partitions directly affects how entries are distributed across the hash table and the uniformity of this distribution. the hash table entry is retrieved and summarized (updated) with the current table row values based on the requested grouping column operations (such as SUM or COUNT). Once the hash table is completely populated. Grouping with Keyed Sequence Implementation This implementation utilizes the key selection or key positioning access methods to perform the grouping. a new entry is inserted into the hash table and initialized with the current grouping value. If a hash table entry is not found for the current grouping value. the expected number of groups in the database table). The hash function performs better when the grouping values consist of columns that have non-numeric data types. the hashing access method is more effective when the hash table is well-balanced. The optimizer estimates the consolidation ratio by first determining the number of unique values in the specified grouping columns (that is. LASTNAME. the optimizer can remove EMPNO from the list of grouping fields because of the EMPNO = '000190' selection predicate. WORKDEPT OPNQRYF example: OPNQRYF FILE(EMPLOYEE) FORMAT(FORMAT1) QRYSLT('EMPNO *EQ ''000190''') GRPFLD(EMPNO LASTNAME WORKDEPT) In this example. WORKDEPT) DECLARE DEPTEMP CURSOR FOR SELECT LASTNAME. Note: Even though EMPNO can be removed from the list of grouping columns. Eliminating Grouping Columns All of the grouping columns are evaluated to determine if they can be removed from the list of grouping columns. WORKDEPT FROM CORPDATA. WORKDEPT 444 DB2 UDB for AS/400 SQL Programming V4R4 . | | | | | | DECLARE DEPTEMP CURSOR FOR SELECT EMPNO. | | | | | | | | | | CREATE INDEX X1 ON EMPLOYEE (LASTNAME. LASTNAME. The following example illustrates a query where the optimizer could eliminate a grouping column. EMPNO. Adding Additional Grouping Columns The same logic that is applied to removing grouping columns can also be used to add additional grouping columns to the query. This is only done when you are trying to determine if an index can be used to implement the grouping.EMPLOYEE WHERE EMPNO = '000190' GROUP BY LASTNAME. 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. a temporary index is created. Only those grouping columns that have isolatable selection predicates with an equal operator specified can be considered. WORKDEPT FROM CORPDATA.EMPLOYEE WHERE EMPNO = '000190' GROUP BY EMPNO. the optimizer might still choose to use that index if a permanent index exists with all three grouping columns. This processing is done to allow the optimizer to consider more indexes to implement the query and to reduce the number of columns that will be added as key fields to a temporary index or hash table. The grouping columns specified within the query are used as the key fields for this index. This guarantees that the column can only match a single value and will not help determine a unique group.implementation can be beneficial if an application does not need to retrieve all of the group results or if an index already exists that matches the grouping columns. When the grouping is implemented with an index and a permanent index does not already exist that satisfies grouping columns. The following example illustrates a query where the optimizer could add an additional grouping column. Uses the index to position to a group and 2. the key field must be a descending key. and if specified the first non-null MIN or MAX value in the group 3. Example 1. MIN(SALARY) FROM EMPLOYEE WHERE JOB='CLERK' GROUP BY DEPT Chapter 24. the runtime code will position to the first index key and return that key value as the MAX of salary. The SLIC runtime code will scan the index until it finds the first non-null value for SALARY. JOB. Assuming that SALARY is not null. There can be no other grouping functions in the query. Example 1. No more index keys will be processed. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 445 . the optimizer can add EMPNO as an additional grouping column when considering X1 for the query. using SQL: CREATE INDEX IX2 ON EMPLOYEE (DEPT. or – There is only a single MIN or MAX column function in the query and the operand of the MIN or MAX is the next key field in the index after the grouping fields. For the MIN function. Example 2.| OPNQRYF example: OPNQRYF FILE ((EMPLOYEE)) FORMAT(FORMAT1) QRYSLT('EMPNO *EQ ''000190''') GRPFLD(LASTNAME WORKDEPT) | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | For this query request. finds the first record matching the selection criteria for the group. the key field must be an ascending key. Index skip key processing can be used: v For single file queries using the keyed sequence grouping implementation when: – There are no column functions in the query. The index skip key processing algorithm: 1. ″Skip″ to the next group and repeat processing This will improve performance by potentially not processing all index key values for a group. the operand of the MIN or MAX must be the first key field. using SQL: CREATE INDEX IX1 ON EMPLOYEE (SALARY DESC) DECLARE C1 CURSOR FOR SELECT MAX(SALARY) FROM EMPLOYEE.SALARY) DECLARE C1 CURSOR FOR SELECT DEPT. Grouping using Index Skip Key Processing Index Skip Key processing can be used when grouping with the keyed sequence implementation algorithm which uses an existing index. If the query is whole file grouping. using the OPNQRYF command: OPNQRYF FILE(EMPLOYEE) FORMAT(FORMAT1) MAPFLD((MAXSAL '%MAX(SALARY)')) The query optimizer will chose to use the index IX1. Returns the group to the user 4. for the MAX function. EMPLOYEE WHERE DEPARTMENT.WORKDEPT GROUP BY DEPARTMENT. Example 1. try to specify the same data types and attributes. v For join queries: – All grouping columns must be from a single file. table scan is more efficient than index-based retrieval. The SLIC runtime code will position to the first group for DEPT where JOB equals ’CLERK’ and will return the SALARY.| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Example 2. 1. – If the MIN or MAX function operand is from the same dial as the grouping columns. when a very large percentage of pages are retrieved. When a column value and a host variable (or literal value) are being compared. Example 1. – For each dial there can be at most one MIN or MAX column function operand that references the dial and no other column functions can exist in the query. using the OPNQRYF command: OPNQRYF FILE(DEPARTMENT EMPLOYEE) FORMAT(FORMAT1) JFLD((1/DEPTNO 2/WORKDEPT *EQ)) GRPFLD((1/DEPTNO)) MAPFLD((MINSAL '%MIN(SALARY)')) Effectively Using SQL Indexes DB2 UDB for AS/400 provides two basic means for accessing tables: a table scan (sequential) and an index-based (direct) retrieval. using SQL: CREATE INDEX IX1 ON DEPARTMENT(DEPTNAME) CREATE INDEX IX2 ON EMPLOYEE(WORKDEPT. MIN(SALARY) FROM DEPARTMENT. If DB2 UDB for AS/400 cannot use an index to access the data in a table.DEPTNO=EMPLOYEE. The code will then skip to the next DEPT group where JOB equals ’CLERK’. DB2 UDB for AS/400 does not use an index for the named column if the host variable or literal value has a greater precision than the precision of the column. Avoid numeric conversions. However. it will have to read all the data in the table. If the two items being compared have different data types. The following suggestions help you to design code that allows DB2 UDB for AS/400 to take advantage of available indexes. using the OPNQRYF command: OPNQRYF FILE(EMPLOYEE) FORMAT(FORMAT2) QRYSLT('JOB *EQ ''CLERK''') GRPFLD((DEPT)) MAPFLD((MINSAL '%MIN(SALARY)')) The query optimizer will chose to use Index IX2. Very large tables present a special performance problem: the high cost of retrieving all the data in the table. DB2 UDB for AS/400 will have to convert | | | | | 446 DB2 UDB for AS/400 SQL Programming V4R4 . – If the MIN or MAX function operand is from a different dial then the join field for that dial must join to one of the grouping fields and the index for that dial must contain the join fields followed by the MIN or MAX operand. Index-based retrieval is usually more efficient than table scan.DEPTNO. then it uses the same rules as single file queries. SALARY) DECLARE C1 CURSOR FOR SELECT DEPTNAME. . Try to use the same data length when comparing a fixed-length character string column value to a host variable or literal value. which can result in inaccuracies (because of limited machine precision). WHERE EMPNO > '000300 ' AND DEPTNO < 'E20 ' When using the OPNQRYF command.. When using SQL. The optimizer does not use an index on a field that is being compared to an arithmetic expression. if applicable For example. Avoid arithmetic expressions You should never have an arithmetic expression as an operand to be compared to a column in a row selection predicate. 2. specify: .. WHERE EDUCLVL < 1. QRYSLT('EDUCLVL *LT 1. EMPNO is CHAR(6) and DEPTNO is CHAR(3)...1E1 AND EDUCLVL > 1.. QRYSLT('EDUCLVL *LT 11 *AND ENUCLVL *GE 2') instead of .1E1 *AND EDUCLVL *GT 1. because the precisions are equal. WHERE SALARY > 16500 instead of . QRYSLT('EMPNO *GT "000300" *AND DEPTNO *LT "E20"') instead of . Avoid character string padding. To avoid problems for columns and constants being compared.. specify: . When using SQL.. use the: v same data type v same scale.| | | | | | | | | | | one or the other of the values. WHERE EMPNO > '000300' AND DEPTNO < 'E20' | | | | instead of .3') | | | | | | | | | | | If an index was created over the EDUCLVL column. WHERE EDUCLVL < 11 AND EDUCLVL >= 2 instead of .3 | | | | | When using the OPNQRYF command. if applicable v same precision.. QRYSLT('EMPNO *GT "000300" *AND DEPTNO *LT "E20"') Chapter 24. specify: . DB2 UDB for AS/400 does not use an index if the literal value or host variable is longer than the column length. then the optimizer does not use the index in the second example because the precision of the constant is greater than the precision of the column. the optimizer considers using the index. Specify: .. EDUCLVL is a halfword integer value (SMALLINT).....1 3.. In the first example. WHERE SALARY > 15000*1..... DB2 UDB for AS/400 Data Management and Query Optimizer Tips 447 . For example.. specify: . they can prevent DB2 UDB for AS/400 from using any indexes that might be defined on the LASTNAME column to limit the number of rows scanned. Therefore. 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. your program might include EXEC SQL DECLARE DEPTEMP CURSOR FOR SELECT EMPNO.EMPLOYEE WHERE (WORKDEPT = 'D11' OR WORKDEPT = 'D21') AND EMPNO = '000190' FOR UPDATE OF EMPNO. They can take advantage of indexes when used to denote characters in the middle or at the end of a character string. DB2 UDB 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. WORKDEPT FROM CORPDATA. QRYSLT('LASTNAME *EQ WLDCRD(''J*SON*'')') However. OPNQRYF example: OPNQRYF FILE((CORPDATA/EMPLOYEE)) OPTION(*ALL) QRYSLT('(WORKDEPT *EQ ''D11'' *OR WORKDEPT *EQ ''D21'') *AND EMPNO *EQ ''000190''') Even if you do not intend to update the employee’s department. In the previous example DB2 UDB for AS/400 would use an index with a key of EMPNO. especially if you are accessing a particularly large table.4. When using SQL: .. LASTNAME. WHERE LASTNAME LIKE 'J%SON%' | When using the OPNQRYF command. WORKDEPT END-EXEC. specify: . QRYSLT('LASTNAME *EQ WLDCRD(''*SON'')') You should therefore avoid using these symbols at the beginning of character strings. specify a character string that is similar to the column value of rows you want to select.. 448 DB2 UDB for AS/400 SQL Programming V4R4 . when used at the beginning of a character string. Avoid the use of like patterns beginning with % or _. The percent sign (%). and the underline (_). WHERE LASTNAME LIKE '%SON' | When using the OPNQRYF command. When using SQL: . do not specify a column in the FOR UPDATE OF column list unless you intend to update the column. specify: . for example.. when used in the pattern of a LIKE (OPNQRYF %WLDCRD) predicate... DB2 UDB for AS/400 can operate more efficiently if the FOR UPDATE OF column list only names the column you intend to update: WORKDEPT.. as in the following.. Be aware that DB2 UDB for AS/400 does not use an index in the following instances: v For a column that is expected to be updated. DB2 UDB for AS/400 cannot use an index with a key of WORKDEPT.. 5. join. If they do not match. see the DB2 UDB for AS/400 SQL Reference book. Joins. DB2 UDB for AS/400 compares the sort sequence tables. Using Indexes and Sort Sequence With Selection. If two or more indexes have a common key field between Chapter 24. or grouping columns that use the following operators and predicates: v v v v equal (=) operator not equal (|= or <>) operator LIKE predicate (OPNQRYF %WLDCRD and *CT) IN predicate (OPNQRYF %VALUES) | | When these conditions are true. DEPTNAME FROM CORPDATA. If the sort sequence table associated with the query is a unique-weight sequence table (including *HEX). OPNQRYF example: OPNQRYF FILE (EMPLOYEE) FORMAT(FORMAT1) QRYSLT('WORKDEPT *EQ ADMRDEPT') Even though there is an index for WORKDEPT and another index for ADMRDEPT.v For a column being compared with another column from the same row. Using Indexes With Sort Sequence The following sections provide useful information about how indexes work with sort sequence tables. or Grouping Before using an existing index. or grouping columns) match the attributes of the key fields in the existing index. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 449 . DB2 UDB for AS/400 is free to use any existing index where the key fields match the columns and either: v The index does not contain a sort sequence table or v The index contains a unique-weight sort sequence table Note: The table does not have to match the unique-weight sort sequence table associated with the query. however. Note: Bitmap processing has a special consideration when multiple indexes are used for a table. DB2 UDB for AS/400 acts as though no sort sequence table is specified for selection. The sort sequence table associated with the query (specified by the SRTSEQ and LANGID parameters) must match the sort sequence table with which the existing index was built. The sort sequence table is an additional attribute that must be compared. For example: EXEC SQL DECLARE DEPTDATA CURSOR FOR SELECT WORKDEPT. There is an exception to this. the existing index cannot be used. For more information on how Sort Sequence tables work. DB2 UDB 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. join.EMPLOYEE WHERE WORKDEPT = ADMRDEPT END-EXEC. DB2 UDB for AS/400 ensures the attributes of the columns (selection. specify: OPNQRYF FILE((STAFF)) QRYSLT('JOB *EQ ''MGR''') SRTSEQ(*LANGIDUNQ) LANGID(ENU) DB2 UDB for AS/400 could use either index HEXIX or index UNQIX. CREATE INDEX HEXIX ON STAFF (JOB) Assume an index UNQIX was created with a unique-weight sort sequence. Example Indexes For the purposes of the examples. SELECT * FROM STAFF WHERE JOB = 'MGR' | | | | | When using the OPNQRYF command. Ordering Unless the optimizer chooses to do a sort to satisfy the ordering request. Since the sort is handling the sort sequence requirement. Example 2 Equals selection with a unique-weight sort sequence table (SRTSEQ(*LANGIDUNQ) LANGID(ENU)). this allows DB2 UDB for AS/400 to use any existing index that meets the selection criteria. CREATE INDEX UNQIX ON STAFF (JOB) Assume an index SHRIX was created with a shared-weight sort sequence. CREATE INDEX SHRIX ON STAFF (JOB) Example 1 Equals selection with no sort sequence table (SRTSEQ(*HEX)). 450 DB2 UDB for AS/400 SQL Programming V4R4 . SELECT * FROM STAFF WHERE JOB = 'MGR' When using the OPNQRYF command. the sort sequence table associated with the index must match the sort sequence table associated with the query. Assume an index HEXIX was created with *HEX as the sort sequence. then those indexes must either use the same sort sequence table or use no sort sequence table. When a sort is used. the translation is done during the sort. specify: OPNQRYF FILE((STAFF)) QRYSLT('JOB *EQ ''MGR''') SRTSEQ(*HEX) DB2 UDB for AS/400 could use either index HEXIX or index UNQIX.them that is also referenced in the query selection. assume three indexes are created. Example 6 Join selection with a shared-weight sort sequence table (SRTSEQ(*LANGIDSHR) LANGID(ENU)). SELECT * FROM STAFF WHERE JOB > 'MGR' | | | | | When using the OPNQRYF command. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 451 . SELECT * FROM STAFF S1.JOB | | | | | | When using the OPNQRYF command. Chapter 24.JOB or the same query using the JOIN syntax.JOB = S2. Example 4 Greater than selection with a unique-weight sort sequence table (SRTSEQ(*LANGIDUNQ) LANGID(ENU)).Example 3 Equal selection with a shared-weight sort sequence table (SRTSEQ(*LANGIDSHR) LANGID(ENU)). specify: OPNQRYF FILE(STAFF STAFF) FORMAT(FORMAT1) JFLD((1/JOB 2/JOB *EQ)) SRTSEQ(*LANGIDUNQ) LANGID(ENU) DB2 UDB for AS/400 could use either index HEXIX or index UNQIX for either query. SELECT * FROM STAFF S1.JOB = S2. SELECT * FROM STAFF WHERE JOB = 'MGR' | | | | | When using the OPNQRYF command. specify: OPNQRYF FILE((STAFF)) QRYSLT('JOB *GT ''MGR''') SRTSEQ(*LANGIDUNQ) LANGID(ENU) DB2 UDB for AS/400 could only use index UNQIX. STAFF S2 WHERE S1. specify: OPNQRYF FILE((STAFF)) QRYSLT('JOB *EQ ''MGR''') SRTSEQ(*LANGIDSHR) LANGID(ENU) DB2 UDB for AS/400 could only use index SHRIX. Example 5 Join selection with a unique-weight sort sequence table (SRTSEQ(*LANGIDUNQ) LANGID(ENU)).JOB or the same query using the JOIN syntax. STAFF S2 WHERE S1.JOB = S2. SELECT * FROM STAFF S1 INNER JOIN STAFF S2 ON S1. JOB | | | | | When using the OPNQRYF command.SELECT * FROM STAFF S1 INNER JOIN STAFF S2 ON S1. SELECT * FROM STAFF WHERE JOB = 'MGR' ORDER BY JOB | | | | | | When using the OPNQRYF command. Example 7 Ordering with no sort sequence table (SRTSEQ(*HEX)). SELECT * FROM STAFF WHERE JOB = 'MGR' ORDER BY JOB | | | | | When using the OPNQRYF command. specify: OPNQRYF FILE((STAFF)) QRYSLT('JOB *EQ ''MGR''') KEYFLD(JOB) SRTSEQ(*LANGIDSHR) LANGID(ENU) DB2 UDB for AS/400 could only use index SHRIX. SELECT * FROM STAFF WHERE JOB = 'MGR' ORDER BY JOB | | | | | When using the OPNQRYF command. Example 9 Ordering with a shared-weight sort sequence table (SRTSEQ(*LANGIDSHR) LANGID(ENU)). 452 DB2 UDB for AS/400 SQL Programming V4R4 . specify: OPNQRYF FILE(STAFF STAFF) FORMAT(FORMAT1) JFLD((1/JOB 2/JOB *EQ)) SRTSEQ(*LANGIDSHR) LANGID(ENU) DB2 UDB for AS/400 could only use index SHRIX for either query.JOB = S2. specify: OPNQRYF FILE((STAFF)) QRYSLT('JOB *EQ ''MGR''') KEYFLD(JOB) SRTSEQ(*HEX) DB2 UDB for AS/400 could only use index HEXIX. Example 8 Ordering with a unique-weight sort sequence table (SRTSEQ(*LANGIDUNQ) LANGID(ENU)). specify: OPNQRYF FILE((STAFF)) QRYSLT('JOB *EQ ''MGR''') KEYFLD(JOB) SRTSEQ(*LANGIDUNQ) LANGID(ENU) DB2 UDB for AS/400 could only use index UNQIX. specify: OPNQRYF FILE((STAFF)) FORMAT(FORMAT2) GRPFLD((JOB)) SRTSEQ(*HEX) DB2 UDB for AS/400 could use either index HEXIX or index UNQIX. SELECT JOB FROM STAFF GROUP BY JOB | | | | When using the OPNQRYF command. SELECT JOB FROM STAFF GROUP BY JOB | | | | | When using the OPNQRYF command. SELECT JOB FROM STAFF GROUP BY JOB | | | | | When using the OPNQRYF command. Example 11 Grouping with no sort sequence table (SRTSEQ(*HEX)). specify: OPNQRYF FILE((STAFF)) QRYSLT('JOB *EQ ''MGR''') KEYFLD(JOB) SRTSEQ(*LANGIDUNQ) LANGID(ENU) ALWCPYDTA(*OPTIMIZE) DB2 UDB for AS/400 could use either index HEXIX or index UNQIX for selection.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 | | | | | | | When using the OPNQRYF command. Example 12 Grouping with a unique-weight sort sequence table (SRTSEQ(*LANGIDUNQ) LANGID(ENU)). specify: OPNQRYF FILE((STAFF)) FORMAT(FORMAT2) GRPFLD((JOB)) SRTSEQ(*LANGIDSHR) LANGID(ENU) Chapter 24. Example 13 Grouping with a shared-weight sort sequence table (SRTSEQ(*LANGIDSHR) LANGID(ENU)). DB2 UDB for AS/400 Data Management and Query Optimizer Tips 453 . Ordering would be done during the sort using the *LANGIDUNQ sort sequence table. specify: OPNQRYF FILE((STAFF)) FORMAT(FORMAT2) GRPFLD((JOB)) SRTSEQ(*LANGIDUNQ) LANGID(ENU) DB2 UDB for AS/400 could use either index HEXIX or index UNQIX. | DB2 UDB for AS/400 could only use index SHRIX. The following examples assume 3 more indexes are created over columns JOB and SALARY. The CREATE INDEX statements precede the examples. Assume an index HEXIX2 was created with *HEX as the sort sequence. CREATE INDEX HEXIX2 ON STAFF (JOB, SALARY) Assume an index UNQIX2 was created and the sort sequence is a unique-weight sort sequence. CREATE INDEX UNQIX2 ON STAFF (JOB, SALARY) Assume an index SHRIX2 was created with a shared-weight sort sequence. CREATE INDEX SHRIX2 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 JOB, SALARY FROM STAFF GROUP BY JOB, SALARY ORDER BY JOB, SALARY | | | | | | When using the OPNQRYF command, specify: OPNQRYF FILE((STAFF)) FORMAT(FORMAT3) GRPFLD(JOB SALARY) KEYFLD(JOB SALARY) SRTSEQ(*LANGIDUNQ) LANGID(ENU) DB2 UDB for AS/400 could use UNQIX2 to satisfy both the grouping and ordering requirements. If index UNQIX2 did not exist, DB2 UDB for AS/400 would create an index using a sort sequence table of *LANGIDUNQ. Example 15 Ordering and grouping on the same columns with ALWCPYDTA(*OPTIMIZE) and a unique-weight sort sequence table (SRTSEQ(*LANGIDUNQ) LANGID(ENU)). SELECT JOB, SALARY FROM STAFF GROUP BY JOB, SALARY ORDER BY JOB, SALARY | | | | | | | When using the OPNQRYF command, specify: OPNQRYF FILE((STAFF)) FORMAT(FORMAT3) GRPFLD(JOB SALARY) KEYFLD(JOB SALARY) SRTSEQ(*LANGIDUNQ) LANGID(ENU) ALWCPYDTA(*OPTIMIZE) DB2 UDB for AS/400 could use UNQIX2 to satisfy both the grouping and ordering requirements. If index UNQIX2 did not exist, DB2 UDB 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 454 DB2 UDB for AS/400 SQL Programming V4R4 Example 16 Ordering and grouping on the same columns with a shared-weight sort sequence table (SRTSEQ(*LANGIDSHR) LANGID(ENU)). SELECT JOB, SALARY FROM STAFF GROUP BY JOB, SALARY ORDER BY JOB, SALARY | | | | | | When using the OPNQRYF command, specify: OPNQRYF FILE((STAFF)) FORMAT(FORMAT3) GRPFLD(JOB SALARY) KEYFLD(JOB SALARY) SRTSEQ(*LANGIDSHR) LANGID(ENU) DB2 UDB for AS/400 could use SHRIX2 to satisfy both the grouping and ordering requirements. If index SHRIX2 did not exist, DB2 UDB 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 JOB, SALARY FROM STAFF GROUP BY JOB, SALARY ORDER BY JOB, SALARY | | | | | | | When using the OPNQRYF command, specify: OPNQRYF FILE((STAFF)) FORMAT(FORMAT3) GRPFLD(JOB SALARY) KEYFLD(JOB SALARY) SRTSEQ(*LANGIDSHR) LANGID(ENU) ALWCPYDTA(*OPTIMIZE) DB2 UDB for AS/400 could use SHRIX2 to satisfy both the grouping and ordering requirements. If index SHRIX2 did not exist, DB2 UDB 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 JOB, SALARY FROM STAFF GROUP BY JOB, SALARY ORDER BY SALARY, JOB | | | | | | When using the OPNQRYF command, specify: OPNQRYF FILE((STAFF)) FORMAT(FORMAT3) GRPFLD(JOB SALARY) KEYFLD(SALARY JOB) SRTSEQ(*LANGIDSHR) LANGID(ENU) DB2 UDB 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. Chapter 24. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 455 Example 19 Ordering and grouping on different columns with ALWCPYDTA(*OPTIMIZE) and a unique-weight sort sequence table (SRTSEQ(*LANGIDUNQ) LANGID(ENU)). SELECT JOB, SALARY FROM STAFF GROUP BY JOB, SALARY ORDER BY SALARY, JOB | | | | | | | When using the OPNQRYF command, specify: OPNQRYF FILE((STAFF)) FORMAT(FORMAT3) GRPFLD(JOB SALARY) KEYFLD(SALARY JOB) SRTSEQ(*LANGIDUNQ) LANGID(ENU) ALWCPYDTA(*OPTIMIZE) DB2 UDB 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 JOB, SALARY FROM STAFF GROUP BY JOB, SALARY ORDER BY SALARY, JOB | | | | | | | When using the OPNQRYF command, specify: OPNQRYF FILE((STAFF)) FORMAT(FORMAT3) GRPFLD(JOB SALARY) KEYFLD(SALARY JOB) SRTSEQ(*LANGIDSHR) LANGID(ENU) ALWCPYDTA(*OPTIMIZE) DB2 UDB for AS/400 could use index SHRIX2 to satisfy the grouping requirements. A sort would be performed to satisfy the ordering requirements. Tips for using VARCHAR and VARGRAPHIC data types Variable-length column (VARCHAR or VARGRAPHIC) support allows you to define any number of columns in a table as variable length. If you use VARCHAR or VARGRAPHIC support, the size of a table can usually be reduced. Data in a variable-length column is stored internally in two areas: a fixed-length or ALLOCATE area and an overflow area. If a default value is specified, the allocated length is at least as large as the value. The following points help you determine the best way to use your storage area. When you define a table with variable-length data, you must decide the width of the ALLOCATE area. If the primary goal is: v Space saving: use ALLOCATE(0). v Performance: the ALLOCATE area should be wide enough to incorporate at least 90% to 95% of the values for the column. It is possible to balance space savings and performance. In the following example of an electronic phone book, the following data is used: 456 DB2 UDB for AS/400 SQL Programming V4R4 v 8600 names identified by: last, first, and middle name v The Last, First, and Middle columns are variable length. v The shortest last name is 2 characters; the longest is 22 characters. This example shows how space can be saved by using variable-length columns. The fixed-length column table uses the most space. The table with the carefully calculated allocate sizes uses less disk space. The table that was defined with no allocate size (with all of the data stored in the overflow area) uses the least disk space. Number of Total Records in Middle Name Physical File Overflow Max/Alloc Size Space 22 40/7 40/0 567 K 408 K 373 K 0 73 8600 Variety of Support Fixed Length Variable Length VariableLength Default Last Name Max/Alloc 22 40/10 40/0 First Name Max/Alloc 22 40/10 40/0 In many applications performance must be considered. If you use the default ALLOCATE(0), it will double the disk unit traffic. ALLOCATE(0) requires two reads; one to read the fixed-length portion of the row and one to read the overflow space. The variable-length implementation, with the carefully chosen ALLOCATE, minimizes overflow and space and maximizes performance. The size of the physical file is 28% smaller than the fixed-length implementation. Because 1% of rows are in the overflow area, the access requiring two reads is minimized. The variable-length implementation performs about the same as the fixed-length implementation. To create the table using the ALLOCATE keyword: CREATE TABLE PHONEDIR (LAST VARCHAR(40) ALLOCATE(10), FIRST VARCHAR(40) ALLOCATE(10), MIDDLE VARCHAR(40) ALLOCATE(7)) 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 LAST-NAME PIC X(40). ... MOVE "SMITH" TO LAST-NAME. EXEC SQL INSERT INTO PHONEDIR VALUES(:LAST-NAME, :FIRST-NAME, :MIDDLE-NAME, :PHONE) END-EXEC. The host-variable LAST-NAME is not variable length. The string “SMITH”, followed by 35 blanks, is inserted into the VARCHAR column LAST. The value is longer than the allocate size of 10. Thirty of thirty-five trailing blanks are in the overflow area. In this example, variable-length host variables are used to insert a row into a table: Chapter 24. DB2 UDB for AS/400 Data Management and Query Optimizer Tips 457 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. For more information about using variable-length host variables, see Chapter 12. Coding SQL Statements in C and C++ Applications, through Chapter 17. 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. 458 DB2 UDB for AS/400 SQL Programming V4R4 Chapter 25. Additional SQL performance considerations The SQL data manipulation language statements must do database open operations in order to create an open data path (ODP) to the data. An open data path is the path through which all input/output operations for the file are performed. In a sense, it connects the SQL application to a file. The number of open operations in a program can significantly affect performance. A database open operation occurs on: v An OPEN statement v SELECT INTO statement v An INSERT statement with a VALUES clause v An UPDATE statement with a WHERE condition v 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 UDB 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. 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. v v v v DB2 UDB 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. © Copyright IBM Corp. 1997, 1999 459 The ODPs opened by DB2 UDB 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 or when a COBOL program issues the STOP RUN COBOL statement. RCLRSC will not close ODPs created for programs precompiled using CLOSQLCSR(*ENDJOB). For interaction of RCLRSC with non-default activation groups, see the following books: – ILE C for AS/400 Programmer’s Guide – ILE COBOL for AS/400 Programmer’s Guide – ILE RPG for AS/400 Programmer’s Guide 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 UDB 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 UDB 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 UDB 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. Instead, use the following coding technique to avoid opens: EXEC SQL FETCH EMPT INTO :SALARY END EXEC. ADD 1000 TO SALARY. EXEC SQL 460 DB2 UDB for AS/400 SQL Programming V4R4 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. Improving Performance by Using Database Manager Blocking Considerations To improve performance, the SQL run-time attempts to retrieve and insert records from the database manager a block at a time whenever possible. You can control blocking, if desired, by using the SEQONLY parameter on the CL command Override Database File (OVRDBF) prior to calling the application program that contains the SQL statements or by specifying the ALWBLK parameter on the CRTSQLxxx commands. The database manager does not allow blocking in the following situations: v The cursor is update or delete capable. v The length of the row plus the feedback information is greater than 32767. The minimum size for the feedback information is 11 bytes. The feedback size is increased by the number of bytes in the key fields for the index used by the cursor and by the number of key fields, if any, that are null capable. v COMMIT(*CS) is specified and ALWBLK(*ALLREAD) is not specified. v COMMIT(*ALL) is specified and the following are true: – A SELECT INTO statement or a blocked FETCH statement is not used – The query does not use column functions or specify group by columns. – A temporary result table does not have to be created. v COMMIT(*CHG) is specified and ALWBLK(*ALLREAD) is not specified. v The cursor contains at least one subquery and the outermost subselect provided a correlated reference for a subquery or the outermost subselect processed a subquery with an IN, = ANY, or < > ALL subquery predicate operator, which is treated as a correlated reference. The SQL run-time automatically blocks records with the database manager in the following cases: v INSERT If an INSERT statement contains a select-statement, inserted records are blocked and not actually inserted into the target table until the block is full. The SQL run-time automatically does blocking for blocked inserts. Note: If an INSERT with a VALUES clause is specified, the SQL run-time might not actually close the internal cursor used to perform the inserts until the program ends. If the same INSERT statement is run again, a full open is not necessary and the application runs much faster. v OPEN Blocking is done under the OPEN statement when the records are retrieved if all of the following conditions are true: – The cursor is only used for FETCH statements. – No EXECUTE or EXECUTE IMMEDIATE statements are in the program, or ALWBLK(*ALLREAD) was specified, or the cursor is declared with the FOR FETCH ONLY clause. Chapter 25. Additional SQL performance considerations 461 – COMMIT(*CHG) and ALWBLK(*ALLREAD) are specified, COMMIT(*CS) and ALWBLK(*ALLREAD) are specified, or COMMIT(*NONE) is specified. Improving Performance Using FETCH FOR n ROWS Applications that perform many FETCH statements in succession may be improved by using FETCH FOR n ROWS. With this clause, you can retrieve multiple rows of data from a table and put them into a host structure array or row storage area with a single FETCH. For more information on declaring arrays of host structures or row storage areas, see the DB2 UDB for AS/400 SQL Reference book or the individual programming chapters. An SQL application that uses a FETCH statement, without the FOR n ROWS clause, can be improved by using the multiple-row FETCH statement to retrieve multiple rows. After the host structure array or row storage area has been filled by the FETCH, the application can loop through the data in the array or storage area to process each of the individual records. The statement runs faster because the SQL run-time was called only once and all the data was simultaneously returned to the application program. You can change the application program to allow the database manager to block the records that the SQL run-time retrieves from the tables. For more information, see “Improving Performance by Using Database Manager Blocking Considerations” on page 461. In the following table, the program attempted to FETCH 100 rows into the application. Note the differences in the table for the number of calls to SQL run-time and the database manager when blocking can be performed. Table 40. Number of Calls Using a FETCH Statement Database Manager Not Using Database Manager Using Blocking Blocking Single-Row FETCH Statement Multiple-Row FETCH Statement 100 SQL calls 100 database calls 1 SQL run-time call 100 database calls 100 SQL calls 1 database call 1 SQL run-time call 1 database call Improving Performance with SQL Blocking Special performance considerations should be made for the following points when using FETCH FOR n ROWS. You can improve SQL blocking performance with the following: v The attribute information in the host structure array or the descriptor associated with the row storage area matches the attributes of the columns retrieved. v The application should retrieve as many rows as possible with a single multiple-row FETCH call. The blocking factor for a multiple-row FETCH request is not controlled by the system page sizes or the SEQONLY parameter on the OVRDBF command. It is controlled by the number of rows requested on the multiple-row FETCH request. v Do not mix single- and multiple-row FETCH requests against the same cursor within a program. If one FETCH against a cursor is treated as a multiple-row 462 DB2 UDB for AS/400 SQL Programming V4R4 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. Improving Performance Using INSERT n ROWS Applications that perform many INSERT statements in succession may be improved by using INSERT n ROWS. With this clause, you can insert one or more rows of data from a host structure array into a target table. This array must be an array of structures where the elements of the structure correspond to columns in the target table. An SQL application that loops over an INSERT...VALUES statement (without the n ROWS clause) can be improved by using the INSERT n ROWS statement to insert multiple rows into the table. After the application has looped to fill the host array with records, a single INSERT n ROWS statement can be run to insert the entire array into the table. The statement runs faster because the SQL run-time was only called once and all the data was simultaneously inserted into the target table. In the following table, the program attempted to INSERT 100 rows into a table. Note the differences in the number of calls to SQL run-time and to the database manager when blocking can be performed. Table 41. Number of Calls Using an INSERT Statement Database Manager Not Using Database Manager Using Blocking Blocking Single-Row INSERT Statement Multiple-Row INSERT Statement 100 SQL run-time calls 100 database calls 1 SQL run-time call 100 database calls 100 SQL run-time calls 1 database call 1 SQL run-time call 1 database call Improving Performance When Paging Interactively Displayed Data In large tables, paging performance is usually degraded because of the REFRESH(*ALWAYS) parameter on the STRSQL command which dynamically retrieves the latest data directly from the table. Paging performance can be improved by specifying REFRESH(*FORWARD). When interactively displaying data using REFRESH(*FORWARD), the results of a select-statement are copied to a temporary file as you page forward through the display. Other users sharing the table can make changes to the rows while you are displaying the select-statement results. If you page backward or forward to rows that have already been displayed, the rows shown are those in the temporary file instead of those in the updated table. The refresh option can be changed on the Session Services display. Chapter 25. Additional SQL performance considerations 463 Improving Performance by Using SELECT Statements Effectively The number of columns specified in the select list of a SELECT statement causes the database manager to retrieve the data from the underlying tables and map the data into host variables in the application programs. By minimizing the number of columns specified, processing unit resource usage can be conserved. Even though it is convenient to code SELECT *, it is far better to explicitly code the columns actually required for the application. This is especially important if index-only access is desired or if all of the columns will participate in a sort operation (as happens for SELECT DISTINCT and for SELECT UNION). Improving Performance by Using Live Data The term live data refers to the type of access that the database manager uses when it retrieves data without making a copy of the data. Using this type of access, the data, which is returned to the program, always reflects the current values of the data in the database. The programmer can control whether the database manager uses a copy of the data or retrieves the data directly. This is done by specifying the allow copy data (ALWCPYDTA) parameter on the precompiler commands or on the Start SQL (STRSQL) command. Specifying ALWCPYDTA(*NO) instructs the database manager to always use live data. Live data access can be used as a performance advantage because the cursor does not have to be closed and opened again to refresh the data being retrieved. An example application demonstrating this advantage is one that produces a list on a display. If the display screen can only show 20 elements of the list at a time, then, after the initial 20 elements are displayed, the application programmer can request that the next 20 rows be displayed. A typical SQL application designed for an operating system other than the OS/400 operating system, might be structured as follows: EXEC SQL DECLARE C1 CURSOR FOR SELECT EMPNO, LASTNAME, WORKDEPT FROM CORPDATA.EMPLOYEE ORDER BY EMPNO END-EXEC. EXEC SQL OPEN C1 END-EXEC. * PERFORM FETCH-C1-PARA 20 TIMES. MOVE EMPNO to LAST-EMPNO. EXEC SQL CLOSE C1 END-EXEC. * * 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. 464 DB2 UDB for AS/400 SQL Programming V4R4 EXEC SQL OPEN C2 END-EXEC. * * PERFORM FETCH-C21-PARA 20 TIMES. Show the display with these 20 rows of data. EXEC SQL CLOSE C2 END-EXEC. In the above example, notice that an additional cursor had to be opened to continue the list and to get current data. This could result in creating an additional ODP that would increase the processing time on the AS/400 system. In place of the above example, the programmer could design the application specifying ALWCPYDTA(*NO) with the following SQL statements: EXEC SQL DECLARE C1 CURSOR FOR SELECT EMPNO, LASTNAME, WORKDEPT FROM CORPDATA.EMPLOYEE ORDER BY EMPNO END-EXEC. EXEC SQL OPEN C1 END-EXEC. * * * * * Display the screen with these 20 rows of data. PERFORM FETCH-C1-PARA 20 TIMES. Show the display and wait for the user to indicate that the next 20 rows should be displayed. PERFORM FETCH-C1-PARA 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. Improving Performance by Using the ALWCPYDTA Parameter Some complex queries can perform better by using a sort or hashing method to evaluate the query instead of using or creating an index. By using the sort or hash, the database manager is able to separate the row selection from the ordering and grouping process. This separation allows the use of the most efficient index for the selection. For example, consider the following SQL statement: EXEC SQL DECLARE C1 CURSOR FOR SELECT EMPNO, LASTNAME, WORKDEPT FROM CORPDATA.EMPLOYEE WHERE WORKDEPT = 'A00' ORDER BY LASTNAME END-EXEC. Chapter 25. Additional SQL performance considerations 465 In the above example when ALWCPYDTA(*NO) or ALWCPYDTA(*YES) is specified, the database manager may try to create an index from the first index with a column named LASTNAME, if such an index exists. The rows in the table are scanned, using the index, to select only the rows matching the WHERE condition. If ALWCPYDTA(*OPTIMIZE) is specified, the database manager uses an index with the first index column of WORKDEPT. It then makes a copy of all of the rows that match the WHERE condition. Finally, it may sort the copied rows by the values in LASTNAME. This row selection processing is significantly more efficient, because the index used immediately locates the rows to be selected. ALWCPYDTA(*OPTIMIZE) optimizes the total time required to process the query. However, the time required to receive the first row may be increased because a copy of the data must be made prior to returning the first row of the result table. This initial change in response time may be important for applications presenting interactive displays or that retrieve only the first few rows of the query. The DB2 UDB for AS/400 query optimizer can be influenced to avoid sorting by using the OPTIMIZE clause. Refer to “Improving Performance by Using the Optimize Clause” for more information. Queries that involve a join operation may also benefit from ALWCPYDTA(*OPTIMIZE) because the join order can be optimized regardless of the ORDER BY specification. Note: The hashing method cannot be used to implement the grouping on queries that involve a nested loop join implementation and do not require a temporary result to be created. Improving Performance by Using the Optimize Clause If an application is not going to retrieve the entire result table for a cursor, using the OPTIMIZE clause can improve performance. The query optimizer modifies the cost estimates to retrieve the subset of rows using the value specified on the OPTIMIZE clause. Assume the following query returns 1000 rows: EXEC SQL DECLARE C1 CURSOR FOR SELECT EMPNO, LASTNAME, WORKDEPT FROM CORPDATA.EMPLOYEE WHERE WORKDEPT = 'A00' ORDER BY LASTNAME OPTIMIZE FOR 100 ROWS END EXEC. The optimizer calculates the following costs. The optimize ratio = optimize for n rows value / estimated number of rows in answer set. Cost using a temporarily created index: + + Cost to Cost to Cost to with retrieve answer set rows create the index retrieve the rows again a temporary index * optimize ratio 466 DB2 UDB for AS/400 SQL Programming V4R4 Cost using a SORT: + + Cost to retrieve answer set rows Cost for SORT input processing Cost for SORT output processing * optimize ratio Cost using an existing index: Cost to retrieve answer set rows using an existing index * 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 DECLARE CURSOR Embedded Select INTERACTIVE Select output to display INTERACTIVE Select output to printer or database file ALWCPYDTA(*OPTIMIZE) The number or rows in the result table. 2 3% or the number of rows in the result table. The number of rows in the result table. ALWCPYDTA(*YES or *NO) 3% or the number of rows in the result table. 2 3% or the number of rows in the result table. The number of rows in the result table. The OPTIMIZE clause influences the optimization of a query: v To use an existing index (by specifying a small number). v To enable the creation of an index or to run a sort or a hash by specifying a large number of possible rows in the answer set. Improving Performance by Retaining Cursor Positions You can improve performance by retaining cursor positions. The next two sections provide information on retaining cursors for non-ILE and ILE program calls. Improving Performance by Retaining Cursor Positions for Non-ILE Program Calls For non-ILE program calls, the close SQL cursor (CLOSQLCSR) parameter allows you to specify the scope of the following: v The cursors v The prepared statements v The locks When used properly, the CLOSQLCSR parameter can reduce the number of SQL OPEN, PREPARE, and LOCK statements needed. It can also simplify applications by allowing you to retain cursor positions across program calls. Chapter 25. Additional SQL performance considerations 467 *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. Improving Performance by Retaining Cursor Positions across ILE Program Calls For ILE program calls, the close SQL cursor (CLOSQLCSR) parameter allows you to specify the scope of the following: v The cursors v The prepared statements v The locks When used properly, the CLOSQLCSR parameter can reduce the number of SQL OPEN, PREPARE, and LOCK statements needed. It can also simplify applications by allowing you to retain cursor positions across program calls. *ENDACTGRP This is the default for the ILE precompilers. With this option, SQL cursors and prepared statements remain open until the activation group that the program is running under ends. They cannot be used by other programs, only by a different call to the same program. Locks remain until the activation group ends. *ENDMOD With this option, a cursor remains open and accessible only while the module that opened it is active. When the module ends, the SQL cursor can no longer be used. Prepared statements will also be lost when the module ends. Locks, however, remain until the last SQL program in the call stack completes. 468 DB2 UDB for AS/400 SQL Programming V4R4 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. If this program is precompiled with the *ENDJOB option or the *ENDACTGRP option and the activation group remains active, the cursor position is maintained. The cursor position is also maintained when the following occurs: Chapter 25. Additional SQL performance considerations 469 v The program is precompiled with the *ENDSQL option. v SQL remains active between program calls. The result of this strategy is that each call to the program retrieves the next record in the cursor. On subsequent data requests, the OPEN statement is unnecessary and, in fact, fails with a -502 SQLCODE. You can ignore the error, or add code to skip the OPEN. This can be done by using a FETCH statement first, and only running the OPEN statement if the FETCH operation failed. This technique also applies to prepared statements. A program could first try the EXECUTE, and if it fails, perform the PREPARE. The result is that the PREPARE would only be needed on the first call to the program, assuming the correct CLOSQLCSR option was chosen. Of course, if the statement can change between calls to the program, it should perform the PREPARE in all cases. The main program could also control this by sending a special parameter on the first call only. This special parameter value would indicate that because it is the first call, the subprogram should perform the OPENs, PREPAREs, and LOCKs. Note: If you are using COBOL programs, do not use the STOP RUN statement. When the first COBOL program on the call stack ends or a STOP RUN statement runs, a reclaim resource (RCLRSC) operation is done. This operation closes the SQL cursor. The *ENDSQL option does not work as desired. Improving Performance of SQL PREPARE Statements The processing which occurs when an SQL PREPARE statement is run is similar to the processing which occurs during precompile processing. The statement being prepared is: v Syntax checked v Validated to ensure that the usage of objects are valid. v Has an access plan built Again when the statement is executed or opened, the database manager will revalidate that the access plan is still valid. Much of this open processing validation is redundant with the validation which occurred during the PREPARE processing. The DLYPRP(*YES) parameter specifies whether PREPARE statements in this program will completely validate the dynamic statement. The validation will be completed when the dynamic statement is opened or executed. This parameter can provide a significant performance enhancement for programs which use the PREPARE SQL statement because it eliminates redundant validation. Programs specifying this precompile option should check the SQLCODE and SQLSTATE after running the OPEN or EXECUTE statement to ensure the statement is valid. DLYPRP(*YES) will not provide any performance improvement 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. Effects on Performance When Using Long Object Names Long object names are converted internally to system object names when used in SQL statements. This conversion can have some performance impacts. If the long object name is qualified with a library name, then the conversion to the short name happens at precompile time. In this case, there is no performance impact when the 470 DB2 UDB for AS/400 SQL Programming V4R4 statement is executed. However, if the long object name is unqualified, the conversion is done at execution time, and has a small performance impact. Improving Performance Using the Precompile Options Several precompile options are available for creating programs with improved performance. They are only options because using them may impact the function of the application. For this reason, the default values for these parameters is the value that will ensure successful migration of applications from prior releases. However, performance may be improved by specifying other options. The following table shows these precompile options and their performance impacts: Precompile Option ALWCPYDTA Optimal Value *OPTIMIZE Improvements Queries where the ordering or grouping criteria conflicts with the selection criteria. Additional read-only cursors use blocking. Considerations A copy of the data may be made when the query is opened. Related Topics See “Improving Performance by Using the ALWCPYDTA Parameter” on page 465. See “Improving Performance by Using Database Manager Blocking Considerations” on page 461. See “Improving Performance by Retaining Cursor Positions for Non-ILE Program Calls” on page 467. See “Improving Performance of SQL PREPARE Statements” on page 470. See “Improving Performance by Using Structure Parameter Passing Techniques” on page 472. ALWBLK *ALLREAD ROLLBACK HOLD may not change the position of a read-only cursor.Dynamic processing of positioned updates or deletes might fail. Implicit closing of SQL cursor is not done when the program invocation ends. CLOSQLCSR *ENDJOB *ENDSQL or *ENDACTGRP Cursor position can be retained across program invocations. DLYPRP *YES Programs using SQL Complete validation of PREPARE statements the prepared may run faster. statement is delayed until the statement is run or opened. The precompiler can generate code that will take advantage of performance enhancements available in the current release. The program object cannot be used on a system from a previous release. TGTRLS *CURRENT (the default) 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. Chapter 25. Additional SQL performance considerations 471 the indicators for the input host variables. the structure is created as a static variable. the SQL run-time support can check for a match with the I/O buffer (each result column attribute is checked for a matching host variable attribute) and move the data with one instruction if they all match. The SQL header on the structure contains information unique to the statement so that SQL does not have to reconstruct the information on each call. code is added that moves the data from the structure to the output host variables. For example: CALL QSQROUTE (SQLCA. Note: The structure parameter passing technique is not used for SQL statements for special cases in PL/I and RPG for AS/400 programs (see “Differences in PL/I Because of Structure Parameter Passing Techniques” on page 294 and “Differences in RPG for AS/400 Because of Structure Parameter Passing Techniques” on page 307.Improving Performance by Using Structure Parameter Passing Techniques The SQL precompiler uses two methods of passing host variables to the SQL run time. Some of this information is added and processed by the SQL run-time support. The original method was to pass each host variable as a separate parameter. hostvariable3) The second method is to create a data structure with an element for each host variable referenced in the statement. hostvariable2. the output host variables. and saves the SQLDA so it can be used on future calls of the statement. followed by the input host variables. With the 472 DB2 UDB for AS/400 SQL Programming V4R4 . Then that data structure could be passed as a parameter. SQL run-time support builds the SQLDA the first time the statement is called. hostvariable1. For example: CALL QSQROUTE (SQLCA. With structure parameter passing. and the indicators for the output host variables. With the original type of parameter passing. and the address of the elements will not change. the host variable address could be different for each call of the statement and. the number of host variables that could be referred to in a program was approximately 4000 because of an architecture limit of 4100 pointers in a program. Because the output host variables are created in a contiguous storage space. Background Information on Parameter Passing Additional code is created in the program to move the input host variable data to the structure before the call to the SQL program. therefore. SQL run-time support creates an SQLDA internally for each statement that uses host variables. hostvariable structure) The second method will provide better performance. Each parameter required a pointer. After the call to the SQL program. With the original parameter list. The precompiler creates the structure so that the SQL header is first. SQL run-time support rebuilds the SQLDA for each call of the statement. if ATABLE has only one or two columns.Attention: This could cause incorrect results when the extra output host variables overlap with other host variables. the contents of A and B will be blank instead of the value of the column corresponding to A and B. using RPG for AS/400. At a job level. or the optimizer might choose a non-parallel Chapter 25. If existing programs use variable names starting with SQL. Controlling Parallel Processing This section describes how parallel processing can be turned on and off. but with the structure parameter passing technique. When the assignment to C from the SQL structure is done. An example of this problem. the host variable is set to the value in the SQL created structure (blanks are used for character host variables and zeros are used for numeric host variables). SQL does not detect this error.structure parameter passing. v The structure created by SQL uses names that start with the letters SQL. the individual queries that run in a job might not actually use a parallel method. Some Differences Because of Structure Parameter Passing Techniques You need to be aware of the following differences in the parameter passing techniques when embedding SQL statements into application programs: v SQLCODE +326 is returned when the structure parameter passing technique is used and the number of host variables specified is greater than the number of columns in the select list. follows: ISTRUC I I I DS 1 2 1 1 A 2 B 2 C SELECT * INTO :STRUC FROM ATABLE In the above example. However.2) input host variable contains the invalid data ’FFFFFF’X. 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. the SQLCODE will be set to +326. the limit of 4000 pointers does not apply. if a DECIMAL(5. therefore. For example. The conversion error occurs in the host language statements that reference the host variable. v The contents of the SQL-created data structure must not be changed by the application programs. Even though parallelism has been enabled for a system or given job. this control is available using the DEGREE parameter on the CHGQRYA command. an error will occur in the host language when the data is moved into the data structure. Additional SQL performance considerations 473 . The extra output host variables are ignored by the original parameter passing technique. This control is available for system wide control through the system value QQRYDEGREE. only two parameters are passed for each SQL statement. This might be because of functional restrictions. with the structure parameter passing technique. If the DB2 UDB Symmetric Multiprocessing feature is installed. v With the original parameter passing technique. those names may conflict with the SQL-created names. then symmetric multiprocessing (SMP) can also be turned on and off. The current value of the system value can be displayed or modified using the following CL commands: v v v v WRKSYSVAL . optionally. Changing this system value affects all jobs that will be run or are currently running on the system whose DEGREE query attribute is *SYSVAL. Controlling Parallel Processing for a Job Query parallel processing can also be controlled at the job level using the DEGREE parameter of the Change Query Attributes (CHGQRYA) command.Change System Value DSPSYSVAL . CPU. The possible values are: *NONE No parallel processing is allowed for database query processing. SMP parallel processing is used only if the DB2 UDB Symmetric Multiprocessing feature is installed. See the previous sections that describe the performance characteristics and restrictions of each of the parallel access methods. The parallel processing option allowed and. SMP parallel processing can be used only if the DB2 UDB Symmetric Multiprocessing feature is installed. *MAX The query optimizer can choose to use either I/O or SMP parallel processing to process the query. the number of tasks that can be used 474 DB2 UDB for AS/400 SQL Programming V4R4 . Because queries being processed with parallel access methods aggressively use main storage. *IO I/O parallel processing is allowed for queries. the number of queries that use parallel processing should be limited and controlled. *OPTIMIZE The query optimizer can choose to use any number of tasks for either I/O or SMP parallel processing to process the queries.method because it runs faster. The choices made by the query optimizer are similar to those made for parameter value *OPTIMIZE. so the value must be changed if parallel query processing is desired as the default for jobs run on the system. Controlling Parallel Processing System Wide The QQRYDEGREE system value can be used to control parallel processing for a system. except the optimizer assumes that all active memory in the pool can be used to process the query.Retrieve System Value The special values for QQRYDEGREE control whether parallel processing is allowed by default for all jobs on the system.Display System Value RTVSYSVAL . The query optimizer chooses to use parallel processing to minimize elapsed time based on the job’s share of the memory in the pool. The default value of the QQRYDEGREE system value is *NONE. and disk resources.Work with System Value CHGSYSVAL . queries that have already been started or queries using reusable ODPs are not affected. However. Additional SQL performance considerations 475 . and whether the expected elapsed time for the query is limited by CPU processing or I/O resources. SMP parallel processing is not allowed. *IO Any number of tasks can be used when the database query optimizer chooses to use I/O parallel processing for queries. *OPTIMIZE The query optimizer can choose to use any number of tasks for either I/O or SMP parallel processing to process the query. 2.I (1) CHGQRYA * JOB( job-number/ *SAME *NOMAX *SYSVAL seconds *SAME *NONE *IO *OPTIMIZE *MAX *SYSVAL *ANY *NBRTASKS number-of-tasks user-name/ job-name ) Pgm: B. You can prompt on the CHGQRYA command in an interactive job to display the current values of the DEGREE query attribute. the job’s share of the amount of active memory available in the pool in which the job is run. The query optimizer chooses an implementation that minimizes elapsed time based on the job’s share of the memory in the pool. All parameters preceding this point can be specified in positional form. *NONE No parallel processing is allowed for database query processing. Use of parallel processing and the number of tasks used is determined with respect to the number of processors available in the system. Value *ANY is equivalent to value *IO. Chapter 25. Changing the DEGREE query attribute does not affect queries that have already been started or queries using reusable ODPs. Job: B.when running database queries in the job can be specified.I (2) REXX: B.I Exec QRYTIMLMT( ) DEGREE ( ) ASYNCJ ( *SAME *LOCAL *DIST *NONE *ANY ) APYRMT ( *SAME *YES *NO ) Notes: 1. SMP parallel processing can be used only if the DB2 UDB Symmetric Multiprocessing feature is installed. The parameter values for the DEGREE keyword are: *SAME The parallel degree query attribute does not change. | | | | | | 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. *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. SMP parallel processing can be used only if the DB2 UDB Symmetric Multiprocessing feature is installed. Too many tasks can degrade performance because of the over commitment of active memory and the overhead cost of managing all of the tasks. See the CL Reference (Abridged) book for more information about the CHGQRYA command. 476 DB2 UDB for AS/400 SQL Programming V4R4 . SMP parallel processing can be used only if the DB2 UDB Symmetric Multiprocessing feature is installed. The *ANY value is maintained for compatibility with prior releases. *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. I/O parallelism is also allowed.*MAX The query optimizer can choose to use either I/O or SMP parallel processing to process the query. The initial value of the DEGREE attribute for a job is *SYSVAL. 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. and all AS/400 HLLs. you may want to refer to a list of “General Optimization Tips” on page 395. Monitoring and Optimizing Query Performance Tools Optimizing Query Performance Using Query Optimization Tools | | | | | You can use query optimization tools to improve data retrieval time. These messages explain what happened during the query optimization process. 1997. To view the messages. For example. You may want to quickly check out the “Comparison table of query optimization tools” on page 542 to learn: v What information each tool can yield about your query v When in the process a specific tool can analyze your query v The tasks each tool can perform to improve your query If you are experienced with query optimization. embedded SQL. interactive SQL. 1999 477 . you can learn: v v v v v v v Why an index was or was not used Why a temporary result was required Whether joins and blocking are used What type of index was advised by the optimizer Status of the job’s queries Access paths used Status of the cursor The optimizer automatically logs messages for OPNQRYF. SQL Query Manager. put your job into debug mode using one of the following methods: v Use the following command: STRDBG PGM(Library/program) UPDPROD(*YES) © Copyright IBM Corp. Use the results of the tools to: v Change the “Data Access Methods” on page 420 chosen by the system v Create the correct indexes The query optimization tools to use in this iterative process include: v “Query optimizer debug messages” v “Print SQL information” on page 478 v “Database monitor statistics” on page 478 v “Change query attributes” on page 543 v “Query Options File QAQQINI” on page 543 v “Memory Resident Database Monitor APIs” on page 524 v You can use the Operations Navigator SQL Performance monitor to work with “Memory Resident Database Monitor APIs” on page 524.Chapter 26. Query optimizer debug messages | | | | | | | | | | | | | | | Query optimizer debug messages issue informational messages to the joblog about the implementation of a query. So. You can monitor a specific job or all jobs on the system. Print SQL information | | | | | | | | | | | | | | | | | | | | | The PRTSQLINF command gathers information about the embedded SQL statements in a program. but PRTSQLINF must be run against a saved access plan. PRTSQLINF provides information about: v The SQL statements being executed v The type of access plan used during execution. whether a database scan is sued. It then puts the information in a spooled file. This includes information about how the query will be implemented. query debug messages work at runtime while PRTSQLINF works retroactively. Database monitor statistics | | | | | | | | | | | | Database monitor statistics provide the most complete information about a query. The query optimizer automatically logs information messages about the current query processing when your job is in debug mode. press F1 (Help). To gather this information. Pressing F10 from the command Entry panel displays the message text. or service program. The STRDBMON and ENDDBMON CL commands start and end the collection of database performance statistics. You can log all information and statistics for queries that you run on a particular job or at a system level. See “Performance Information Messages” on page 382 for the specific meanings of the debug messages. 478 DB2 UDB for AS/400 SQL Programming V4R4 . v A list of the command parameters used to precompile the source member for the object. run PRTSQLINF against a saved access plan. Set the parameter on the QAQQINI file to MESSAGES_DEBUG. PRTSQLINF gives output that is similar to the information you can get from debug messages. Each job in the system can be monitored concurrently by two monitors: v One started specifically on that job v One started for all jobs in the system When a job is monitored by two monitors. You can identify records in the output database file by each record’s unique identification number. and whether an index is created. the join order. To see the second-level text. PRTSQLINF’s requirement of a saved access plan means the command cannot be used with OPNQRYF. whether a sort is done. and set the value to *YES. SQL package (the object normally used to store the access plan for a remote query). The statistics gathered are placed in the output database file specified on the command. the indexes used.| | | | | | v Set the QRYOPTLIB parameter on the Change Query Attributes (CHGQRYA) command to a user library where the QAQQINI file exists. This means you must execute or at least prepare the query (using SQL’s PREPARE statement) before you use the command. It is best to execute the query because the access paln created as a result of PREPARE is relatively sparse and may well change after the first run. The second-level text sometimes offers hints for improving query performance. each monitor is logging records to a different output file. If the output file and/or member exist. There are a variety of ways of gathering the statistics: v “Start Database Monitor (STRDBMON) Command” and “End Database Monitor (ENDDBMON) Command” on page 480 v Start Performance Monitor (STRPFRMON) command with the STRDBMON parameter v “Memory Resident Database Monitor APIs” on page 524 v You can use “Optimizing Query Performance Using Query Optimization Tools” on page 477 to improve data retrieval time. Database monitor statistics provide the most complete information about a query. Monitoring and Optimizing Query Performance Tools 479 . You can use these performance statistics to generate various reports. Chapter 26. If the output file and/or member does not exist. you can include reports that show queries that: v v v v Use an abundance of the system resources. You can gather performance statistics for a specific query or for every query on the system. Start Database Monitor (STRDBMON) Command The STRDBMON command starts the collection of database performance statistics for a specific job or all jobs on the system. The statistics are placed in an output database file and member specified on the command.| | | | | | | | | | | | | | | | STRDBMON provides the same information as the two earlier tools (Query optimizer debug messages (STRDBG) and Print SQL information (PRTSQLINF)) along with the following information: v System and job name v SQL statement and sub-select number v Start and end timestamp v v v v v v v Estimated processing time Total rows in file queried Number of rows selected Estimated number of rows selected Estimated number of joined rows Key fields for advised index Total optimization time v Join type and method v ODP implementation This chapter discusses monitoring database query performance. Did not run because of the query governor time limit. one is created based upon the file and format definition of model file QSYS/QAQQDBMN. For instance. Note: A query that is cancelled by an end request generally does not generate performance statistics. the record format of the output file must be named QQQDBMN. Take an extremely long time to execute. Create a temporary keyed access path during execution v Use the query sort during execution v Could perform faster with the creation of a keyed logical file containing keys suggested by the query optimizer. However. By specifying a larger number for the FRCRCD parameter. While the detail record contains valuable information it creates a slight performance degradation for each block of records returned. If both monitors have selected the same output file then the monitor records are not duplicated in the output file. If the monitor is started on all jobs. as well as summary records. that job must be active in the system when the command is issued. The DDS for this record is shown in Figure 32 on page 523. Start monitoring a specific job. When a job is monitored by two monitors and each monitor is logging to a different output file. In the following sequence: 480 DB2 UDB for AS/400 SQL Programming V4R4 . Currently the only detail record is QQQ3019. FRCRCD(1) also ensures that the physical sequence of the records are most likely.You can specify a replace/append option that allows you to clear the member of information before writing records or to just append new information to the end of the existing file. any jobs waiting on job queues or any jobs started during the monitoring period will have statistics gathered from them once they begin. It continues to run until an ENDDBMON on the specific job is issued. are to be collected. but not guaranteed. those queries which do not generate a QQQ1000 record. For non-SQL queries the only way to determine the number of records returned and the total time to return those records is to collect detail records. 3. there must have been a previous STRDBMON issued for all jobs. By specifying a force record write value of 1. In the following sequence: 1. If an attempt to end the monitor on all jobs is issued. You can also specify a force record write option that allows you to control how many records are kept in the record buffer of each job being monitored before forcing the records to be written to the output file. to be in time sequence. the job must have the monitor started explicitly and specifically on that job. Each job in the system can be monitored concurrently by only two monitors: v One started specifically on that job. the performance impact of monitoring can be lessened. v One started on all jobs in the system. End Database Monitor (ENDDBMON) Command The ENDDBMON command ends the Database Monitor for a specific job or all jobs on the system. End monitoring on all jobs. Specifying *DETAIL on the TYPE parameter of the STRDBMON command indicates that detail records. monitor records will be written to both logs for this job. FRCRCD(1) will cause the most negative performance impact on the jobs being monitored. FRCRCD(1). If the monitor is started on a specific job. 2. monitor records will appear in the log as soon as they are created. Therefore its use should be closely monitored. This is only useful for non-SQL queries. Start monitoring all jobs in the system. The specific job monitor continues to run because an explicit start of the monitor was done on it. If a particular job is specified on this command. End monitoring on all jobs. In 1. CL command to see that all of the monitored jobs no longer hold locks on the output file before assuming the monitoring is complete. you are merely delaying the maintenance cost until the database monitor logical file is either created or opened. Start monitoring all jobs in the system. These records are defined in several different logical files which are not shipped with the system and must be created by the user. Start monitoring a specific job. the ENDDBMON command can complete before all of the monitored jobs have written their final performance records to the log. especially if monitoring all jobs. until an ENDDBMON for all jobs is issued. v Create the database monitor logical files using dynamic select/omit criteria (DYNSLT keyword on logical file’s DDS). When an all job monitor is ended. The logical files can be created with the DDS shown in “Database Monitor Logical File DDS” on page 493. Start monitoring a specific job. End monitoring on the specific job. 3. including the specific job. In the following sequence: 1. Chapter 26. 2. Use the work with object locks. there will be some maintenance overhead associated with these files while the database monitor is active. the following sequence: Start monitoring a specific job. When monitoring all jobs the number of records generated could be quite large. The all job monitor continues to run. Database Monitor Performance Records The records in the database file are uniquely identified by their record identification number.1. Therefore. Start monitoring all jobs in the system. 2. The user may wish to minimize this overhead while the database monitor is active. 3. The all job monitor continues to run for all jobs. The field descriptions are explained in the tables following each figure. Possible ways to minimize maintenance overhead associated with database monitor logical files: v Do not create the database monitor logical files until the database monitor has completed. 2. all of the jobs on the system will be triggered to close the output file. if desired. even over the specific job. v Create the database monitor logical files with rebuild access path maintenance specified on the CRTLF command (*REBLD option on MAINT parameter). Start monitoring all jobs in the system. 3. The specific job monitor continues to run until an ENDDBMON for the specific job is issued. Monitoring and Optimizing Query Performance Tools 481 . By minimizing the maintenance overhead at run time. End monitoring on the specific job. however. WRKOBJLCK. Note: The database monitor logical files are keyed logical files that contain some select/omit criteria. QQIDXK and QQIDXD. The remaining 3 key fields would be the suggested secondary key fields. Primary key fields are fields that should significantly reduce the number of keys selected based on the corresponding query selection. The advisor information is stored in fields QQIDXA. Note: After creating the suggested index and executing the query again. If the optimizer determines that a permanent index would be beneficial. The following examples show how you might collect and analyze data using STRDBMON and ENDDBMON. The optimizer will use key selection with any of the remaining secondary key fields. Therefore it is important that the first secondary key field be the most selective secondary key field. For example. It is up to the user to determine the true selectivity of any secondary key fields and to determine whether those key fields should be included when creating the index. 482 DB2 UDB for AS/400 SQL Programming V4R4 . if creation of a permanent index would improve performance. These are the left-most suggested key fields. The index advisor information can be found in the Database Monitor logical files QQQ3000. it returns the key fields necessary to create the suggested index. based on default values. When the QQIDXA field contains a value of ’Y’ the optimizer is advising you to create an index using the key fields shown in field QQIDXD. Query Optimizer Index Advisor The query optimizer analyzes the record selection in the query and determines. The optimizer is able to perform key positioning over any combination of the primary key fields.The choice is to either spend the time while the database monitor is active or spend the time after the database monitor has completed. Database Monitor Examples Suppose you have an application program with SQL statements and you want to analyze and performance tune these queries. When building the index the primary key fields should be the left-most key fields followed by any of the secondary key fields the user chooses and they should be prioritized by selectivity. QQQ3001 and QQQ3002. The first step in analyzing the performance is collection of data. secondary key fields that are fairly selective should be included. assuming QQIDXK contains the value of 4 and QQIDXD specifies 7 key fields. In the list of key fields contained in field QQIDXD the optimizer has listed what it considers the suggested primary and secondary key fields. The intention of creating this index is to improve the performance of the query. While key selection is not as fast as key positioning it can still reduce the number of keys selected. Field QQIDXK contains the number of suggested primary key fields that are listed in field QQIDXD. The remaining key fields are considered secondary key fields and are listed in order of expected selectivity based on the query. it is possible that the query optimizer will choose not to use the suggested index. Secondary key fields are fields that may or may not significantly reduce the number of keys selected. Hence. plus one additional secondary key field. then the first 4 key fields specified in QQIDXK would be the primary key fields. the SQL information record (QQQ1000) is not created. If this file does not already exist. LIB/QQQ1000 B WHERE A.QQUCNT = B. The following sequence collects performance data and prepares to analyze it. Output for SQL Queries that Performed Table Total Index Lib Name Name Rows Advised LIB1 TBL1 20000 Y LIB1 LIB1 TBL2 TBL1 100 20000 N Y Table Scans Rows Returned TOT_TIME Statement Text 10 6. STRDBMON FILE(LIB/PERFDATA).QQUCNT A lot of data about many queries is contained in multiple records in file LIB/PERFDATA. which contains data about queries performing table scans.QQSTTX FROM LIB/QQQ3000 A.1 SELECT * FROM LIB1/TBL1 WHERE FLD1 = 'B' AND FLD2 > 9000 If the query does not use SQL. A. connects the query implementation to the query statement information.QQUCNT = B. Run your application 3. (B. 2. Chapter 26.QQUCNT Sample output of this query is shown in Table 42. Create logical files over LIB/PERFDATA using the DDS shown in “Database Monitor Logical File DDS” on page 493. You should closely study the physical and logical file DDS to understand all the data being collected so you can create queries that give the best information for your applications.Performance data is collected in LIB/PERFDATA for an application running in your current job.QQETIM . A.QQIDXA.2 SELECT * FROM LIB1/TBL1 WHERE FLD1 = 'A' 100 0. ENDDBMON 4.9 SELECT * FROM LIB1/TBL2 32 7. which contains information about the SQL statements. B. It is not uncommon for data about a single query to be contained in 10 or more records within the file.QQTOTR. The combination of the two.QQTLN. You are now ready to analyze the data. The combination of defining the logical files and then joining the files together allows you to piece together all the data for a query or set of queries.QQJFLD = B. When using SQL. the command will create one from the skeleton file in QSYS/QAQQDBMN. record QQQ1000 contains the actual SQL statement text that matches the performance records to the corresponding query. This makes it more difficult to determine which records in LIB/PERFDATA pertain to which query. The critical thing to understand is the join criteria WHERE A. 1. B.QQJFLD = B.QQROWR. The complete information can be obtained by joining two logical files: QQQ1000.QQSTIM) AS TOT_TIME. when referenced in the context of the logical files.QQJFLD AND A. Performance Analysis Example 1 Determine which queries in your SQL application are implemented with table scans.B. The following SQL query could be used: SELECT A. field QQUCNT is unique at the query level. The following examples give you a few ideas on how to use this data.QQTFN. Field QQJFLD uniquely identifies all data common to a job. and QQQ3000. A. Monitoring and Optimizing Query Performance Tools 483 . scale=’table-scale-factor’ Table 42.QQJFLD AND A. 9 7. the following example shows all queries that are implemented with table scans.2 724 * * If the SQL statement text is not needed. Performance Analysis Example 2 Similar to the preceding example that showed which SQL applications were implemented with table scans.QQROWR. A Y (yes) in this field is a hint from the query optimizer that the query may perform better with an index to access the data.QQSTIM) AS TOT_TIME.QQUCNT) LEFT OUTER JOIN LIB/QQQ1000 D ON (A. A.1 LIB1 TBL4 4000 N QRY04 1.QQOPID. A. joining to file QQQ1000 is not necessary.2 Statement Text SELECT * FROM LIB1/TBL1 WHERE FLD1 = 'A' SELECT * FROM LIB1/TBL2 SELECT * FROM LIB1/TBL1 WHERE FLD1 = 'A' AND FLD2 > 9000 LIB1 LIB1 TBL2 TBL1 100 20000 N Y 0.1 2. D. Performance Analysis Example 3 Your next step may include further analysis of the table scan data. 484 DB2 UDB for AS/400 SQL Programming V4R4 .QQUCNT = B.QQCLKT. For queries executed using the OPNQRYF command.6 0.QQUCNT) LEFT OUTER JOIN LIB/QQQ3019 C ON (A. (D. For the queries where an index is advised.1 4. the output for all queries that performed table scans are shown in Table 43.QQTTIM. For this example assume the default value for character data is blanks and the default value for numeric data is an asterisk (*).QQJFLD AND A.Only through SQL is the statement text captured. C.QQETIM .QQUCNT = C.QQJFLD = B.QQJFLD AND A.QQUCNT = D. Finally.7 Recs Rtned 10 Rows Rtned 10 TOT_ TIME 6. The previous examples contained a field titled Index Advised.D.QQIDXA. B.QQJFLD AND A.4 100 32 100 32 0. B.QQTOTR. Table 43. This is another indication that a table scan may not be optimal.7 4.QQTFN.QQJFLD = C.QQUCNT) In this example. Note: The fields selected from file QQQ1000 do return NULL default values if the query was not executed using SQL. C.QQSTTX FROM LIB/QQQ3000 A INNER JOIN LIB/QQQ3014 B ON (A.QQJFLD = D.QQRCDR. D. Output for All Queries that Performed Table Scans ODP Lib Table Total Index Query Open Clock Name Name Rows Advised OPNID Time Time LIB1 TBL1 20000 Y 1. The OPNID is contained in field QQOPID of record QQQ3014. You can determine the total time and rows selected from data in the QQQ3014 and QQQ3019 records. the OPNID parameter is captured and can be used to tie the records to the query.2 4. SELECT A. a long execution time may highlight queries that may be improved by performance tuning. A.QQTLN. notice that the records selected by the query are low in comparison to the total number of records in the table. B. Table 44. How many queries are performing dynamic replans? Chapter 26.QQIDXA. 4.QQIDXA = ’Y’).QQTLN. A. The following query could be used for this: SELECT A.QQIDXK. 3.The next logical step is to look into the index advised optimizer hint. A. FLD2. The frequency these queries are run and the overhead of maintaining an additional index over the file should be considered when deciding whether or not to create the suggested index. Output with Recommended Key Fields Advised Table Index Key Lib Name Name Advised Fields LIB1 TBL1 Y FLD1 LIB1 TBL1 Y FLD1.QQJFLD AND A.QQIDXA = 'Y' There are two slight modifications from the first example. Start the performance monitor again Re-run the application End the performance monitor Re-evaluate the data.QQJFLD = C. the selected fields have been changed. 1. If you create a permanent index over FLD1. Monitoring and Optimizing Query Performance Tools 485 . By creating one index over LIB1/TBL1 with key fields FLD1. FLD2 the next sequence of steps would be to: 1. creating one index over LIB1/TBL1 would satisfy all three queries since each use a primary or left-most key field of FLD1. 2. A. It is likely that the three index-advised queries are no longer performing table scans.QQSTTX FROM LIB/QQQ3000 A INNER JOIN LIB/QQQ3014 B ON (A.QQJFLD AND A. C. Most important is the selection of field QQIDXD that contains a list of possible key fields to use when creating the index suggested by the query optimizer. there is potential to improve the performance of the second query even more.QQUCNT) LEFT OUTER JOIN LIB/QQQ1000 C ON (A. First.QQTFN.QQUCNT) WHERE A. All of the examples assume data has been collected in LIB/PERFDATA and the documented logical files have been created. Second. Table 44 shows what the results might look like.QQUCNT = B. FLD4 Advised Primary Key 1 1 Query OPNID Statement Text SELECT * FROM LIB1/TBL1 WHERE FLD1 = 'A' SELECT * FROM LIB1/TBL1 WHERE FLD1 = 'B' AND FLD2 > 9000 LIB1 TBL4 Y 1 QRY04 At this point you should determine whether it makes sense to create a permanent index as advised by the optimizer. Additional Database Monitor Examples The following are additional ideas or examples on how to extract information from the performance monitor statistics.QQOPID.QQJFLD = B.QQIDXD.QQUCNT = C. FLD2 FLD1. A. the query selection limits the output to those table scan queries where the optimizer advises that an index be created (A. In this example. QQJFLD A. A. A.C.QQJFLD = C.QQUCNT = B. QQSTTX FROM LIB/QQQ1000 ORDER BY 1 DESC 8.QQIDXD. B. What key fields are used for all indexes created over LIB1/TBL1 and what was the associated SQL statement text or query open ID? SELECT A. C.QQJFLD = B.QQJFLD AND A. A.QQUCNT = B.QQUCNT) LEFT OUTER JOIN LIB/QQQ1000 C ON (A.QQTLN.QQUCNT = B.QQUCNT) LEFT OUTER JOIN LIB/QQQ1000 C ON (A.QQOPID. What key fields are used for all indexes created over LIB1/TBL1 and what is the associated SQL statement text? SELECT FROM WHERE AND AND AND A. How many indexes have been created over LIB1/TBL1? SELECT FROM WHERE AND COUNT(*) LIB/QQQ3002 QQTLN = 'LIB1' QQTFN = 'TBL1' 4. B.QQTFN = 'TBL1' Note: This query shows key fields only from queries executed using SQL. LIB/QQQ1000 B A.QQUCNT A.QQIDXD. A. Which SQL queries are the most time consuming? Which user is running these queries? SELECT (QQETIM .QQUCNT) ORDER BY 1 DESC 486 DB2 UDB for AS/400 SQL Programming V4R4 . 5.QQCLKT).QQTLN = 'LIB1' AND A.QQJFLD AND A. 6.QQJFLD AND A.QQSTTX FROM LIB/QQQ3014 A LEFT OUTER JOIN LIB/QQQ3019 B ON (A.QQTFN = 'TBL1' Note: This query shows key fields from all queries on the system.QQSTTX LIB/QQQ3002 A.QQJFLD AND A.QQUCNT = C.QQSTTX FROM LIB/QQQ3002 A INNER JOIN LIB/QQQ3014 B ON (A. COUNT(*) FROM LIB/QQQ1000 GROUP BY QQSTOP ORDER BY 2 DESC 7. What types of SQL statements are being performed? Which are performed most frequently? SELECT QQSTOP. QQSTTX FROM LIB/QQQ1000 WHERE QQDYNR <> 'NA' Note: You have to refer to the description of field QQDYNR for definitions of the dynamic replan reason codes.QQSTIM).SELECT COUNT(*) FROM LIB/QQQ1000 WHERE QQDYNR <> 'NA' 2.QQJFLD = C. Which queries are the most time consuming? SELECT (A. A. 3.QQUCNT = C. What is the statement text and the reason for the dynamic replans? SELECT QQDYNR. QQUSER.QQTLN = 'LIB1' A.QQJFLD = B.QQOPID.QQTFN.QQJFLD = B.QQTFN.QQTLN.QQTTIM + B.QQUCNT) WHERE A. QQTTIM + B. 15. the PTF should be applied.QQJFLD AND A. A comparison between the two releases would be interesting. Which SQL queries were implemented with nonreusable ODPs? SELECT FROM WHERE AND AND B.QQJFLD A.QQUCNT = B. C.QQEPT/1000 > (A.e. 13.QQTTIM. A.QQUCNT = B.QQJFLD = C.QQJFLD = B. C. What is the estimated time for all queries stopped by the query governor? SELECT QQEPT.Note: This example assumes detail data has been collected into record QQQ3019.QQUCNT Note: This might be used within a report that will format the the interesting data into a more readable format. Monitoring and Optimizing Query Performance Tools 487 .QQOPID.QQUCNT = B. physical field QQRCOD = ’T1’ means a table scan was performed because no indexes exist over the queried file). LIB/QQQ1000 B A. (A. Which queries estimated time exceeds actual time? SELECT A.QQTTIM + B.QQJFLD AND A. SELECT FROM WHERE AND A. Do any of the queries perform this function? SELECT COUNT(*) FROM QQQ3014 WHERE QQUNIN = 'Y' Note: If result is greater than 0.QQJFLD A. LIB/QQQ1000 B A.QQUCNT A.QQCLKT) Note: This example assumes detail data has been collected into record QQQ3019.QQJFLD = B. 14. Should a PTF for queries that perform UNION exists be applied. Show the data for all SQL queries with the data for each SQL query logically grouped together. For example. It should be applied if any queries are performing UNION. QQOPID FROM LIB/QQQ3014 WHERE QQGVNS = 'Y' Note: This example assumes detail data has been collected into record QQQ3019..QQSTTX LIB/QQQ3010 A. all reason code fields could be expanded by the report to print the definition of the reason code (i.QQUCNT) LEFT OUTER JOIN LIB/QQQ1000 C ON (A.QQCLKT).QQJFLD = B.QQUCNT = C.QQSTTX FROM LIB/QQQ3014 A LEFT OUTER JOIN LIB/QQQ3019 B ON (A.QQUCNT) WHERE A.* LIB/PERFDATA A. 9. Chapter 26. 10.QQODPI = 'N' 12. How many queries are being implemented with temporary files because a key length of greater than 2000 bytes or more than 120 key fields was specified for ordering? SELECT COUNT(*) FROM LIB/QQQ3004 WHERE QQRCOD = 'F6' 11. You are a system administrator and an upgrade to the next release is planned.QQEPT. v Collect data from your application on the current release and save this data in LIB/CUR_DATA v Move to the next release v Collect data from your application on the new release and save this data in a different file: LIB/NEW_DATA v Write a program to compare the results. 488 DB2 UDB for AS/400 SQL Programming V4R4 . You will need to compare the statement text between the records in the two files to correlate the data. .+...................+.........3...2.6..8 A* A* Database Monitor physical file record format A* A R QQQDBMN TEXT('Database + Monitor') A QQRID 15P TEXT('Record + ID') + EDTCDE(4) + COLHDG('Record' 'ID') A QQTIME Z TEXT('Time record was + created') + COLHDG('Created' 'Time') A QQJFLD 46H TEXT('Join Field') + COLHDG('Join' 'Field') A QQRDBN 18A TEXT('Relational + Database Name') + COLHDG('Relational' + 'Database' 'Name') A QQSYS 8A TEXT('System Name') + COLHDG('System' 'Name') A QQJOB 10A TEXT('Job Name') + COLHDG('Job' 'Name') A QQUSER 10A TEXT('Job User') + COLHDG('Job' 'User') A QQJNUM 6A TEXT('Job Number') + COLHDG('Job' 'Number') A QQUCNT 15P TEXT('Unique Counter') + ALWNULL + COLHDG('Unique' 'Counter') A QQUDEF 100A VARLEN TEXT('User Defined + Field') + ALWNULL + COLHDG('User' 'Defined' + 'Field') A QQSTN 15P TEXT('Statement Number') + ALWNULL + COLHDG('Statement' + 'Number') A QQQDTN 15P TEXT('Subselect Number') + ALWNULL + COLHDG('Subselect' 'Number') A QQQDTL 15P TEXT('Nested level of + subselect') + ALWNULL + COLHDG('Nested' + 'Level of' + 'Subselect') A QQMATN 15P TEXT('Subselect of + materialized view') + ALWNULL + COLHDG('Subselect of' + 'Materialized' 'View') A QQMATL 15P TEXT('Nested level of + Views subselect') + ALWNULL + COLHDG('Nested Level' + 'of View's' + 'Subselect') Figure 15..+...+. Monitoring and Optimizing Query Performance Tools 489 .7.........4.+.1.+.+...+.5.. QSYS/QAQQDBMN Performance Statistics Physical File DDS (1 of 4) Chapter 26....Database Monitor Physical File DDS |. .+..+....3.+.+..4...+....7.1... QSYS/QAQQDBMN Performance Statistics Physical File DDS (2 of 4) 490 DB2 UDB for AS/400 SQL Programming V4R4 ....8 A QQTLN 10A TEXT('Library') + ALWNULL + COLHDG('Library' 'Name') A QQTFN 10A TEXT('File') + ALWNULL + COLHDG('File' 'Name') A QQTMN 10A TEXT('Member') + ALWNULL + COLHDG('Member' 'Name') A QQPTLN 10A TEXT('Physical Library') + ALWNULL + COLHDG('Library of' + 'Physical File') A QQPTFN 10A TEXT('Physical File') + ALWNULL + COLHDG('Name of' + 'Physical File') A QQPTMN 10A TEXT('Physical Member') + ALWNULL + COLHDG('Member of' + 'Physical' 'File') A QQILNM 10A TEXT('Index Library') + ALWNULL + COLHDG('Index' 'Library') A QQIFNM 10A TEXT('Index File') + ALWNULL + COLHDG('Index' 'Name') A QQIMNM 10A TEXT('Index Member') + ALWNULL + COLHDG('Index' 'Member') A QQNTNM 10A TEXT('NLSS Table') + ALWNULL + COLHDG('NLSS' 'Table') A QQNLNM 10A TEXT('NLSS Library') + ALWNULL + COLHDG('NLSS' 'Library') A QQSTIM Z TEXT('Start timestamp') + ALWNULL + COLHDG('Start' 'Time') A QQETIM Z TEXT('End timestamp') + ALWNULL + COLHDG('End' 'Time') A QQKP 1A TEXT('Key positioning') + ALWNULL + COLHDG('Key' 'Positioning') A QQKS 1A TEXT('Key selection') + ALWNULL + COLHDG('Key' 'Selection') A QQTOTR 15P TEXT('Total row in table') + ALWNULL + COLHDG('Total' 'Rows') A QQTMPR 15P TEXT('Number of rows in + temporary') + ALWNULL + COLHDG('Number' 'of Rows' + 'in Temporary') A QQJNP 15P TEXT('Join Position') + ALWNULL + COLHDG('Join' 'Position') Figure 16..............+.......+.....+..2..6.|.....5... .+... Monitoring and Optimizing Query Performance Tools 491 ..5.....7..+.+...+......+...3......4......|.+...8 A QQEPT 15P TEXT('Estimated processing + time') + ALWNULL + COLHDG('Estimated' + 'Processing' 'Time') A QQDSS 1A TEXT('Data space + selection') ALWNULL COLHDG('Data' 'Space' + 'Selection') A QQIDXA 1A TEXT('Index advised') + ALWNULL + COLHDG('Index' 'Advised') A QQORDG 1A TEXT('Ordering') ALWNULL COLHDG('Ordering') A QQGRPG 1A TEXT('Grouping') + ALWNULL + COLHDG('Grouping') A QQJNG 1A TEXT('Join') ALWNULL COLHDG('Join') A QQUNIN 1A TEXT('Union') + ALWNULL + COLHDG('Union') A QQSUBQ 1A TEXT('Subquery') + ALWNULL + COLHDG('Subquery') A QQHSTV 1A TEXT('Host Variables') + ALWNULL + COLHDG('Host' 'Variables') A QQRCDS 1A TEXT('Record Selection') + ALWNULL + COLHDG('Record' 'Selection') A QQRCOD 2A TEXT('Reason Code') + ALWNULL + COLHDG('Reason' 'Code') A QQRSS 15P TEXT('Number of rows + selected or sorted') + ALWNULL + COLHDG('Number' + 'of Rows' 'Selected') A QQREST 15P TEXT('Estimated number + of rows selected') + ALWNULL + COLHDG('Estimated' + 'Number of' + 'Rows Selected') A QQRIDX 15P TEXT('Number of entries + in index created') + ALWNULL + COLHDG('Number of' + 'Entries in' + 'Index Created') A QQFKEY 15P TEXT('Estimated keys for + key positioning') + ALWNULL + COLHDG('Estimated' + 'Entries for' + 'Key Positioning') Figure 17...+.+...6. QSYS/QAQQDBMN Performance Statistics Physical File DDS (3 of 4) Chapter 26.1.............2.. 5...+...+........+.....+...+.....+..+......6......|....4..7...1.8 A QQKSEL 15P TEXT('Estimated keys for + key selection') + ALWNULL + COLHDG('Estimated' + 'Entries for' + 'Key Selection') A QQAJN 15P TEXT('Estimated number + of joined rows') + ALWNULL + COLHDG('Estimated' + 'Number of' + 'Joined Rows') A QQIDXD 1000A VARLEN TEXT('Key fields + for the index advised') + ALWNULL + COLHDG('Advised' 'Key' + 'Fields') A QQC11 1A ALWNULL A QQC12 1A ALWNULL A QQC13 1A ALWNULL A QQC14 1A ALWNULL A QQC15 1A ALWNULL A QQC16 1A ALWNULL A QQC18 1A ALWNULL A QQC21 2A ALWNULL A QQC22 2A ALWNULL A QQC23 2A ALWNULL A QQI1 15P ALWNULL A QQI2 15P ALWNULL A QQI3 15P ALWNULL A QQI4 15P ALWNULL A QQI5 15P ALWNULL A QQI6 15P ALWNULL A QQI7 15P ALWNULL A QQI8 15P ALWNULL A QQI9 15P ALWNULL TEXT('Thread + Identifier') + COLHDG('Thread' + 'Identifier') A QQIA 15P ALWNULL A QQF1 15P ALWNULL A QQF2 15P ALWNULL A QQF3 15P ALWNULL A QQC61 6A ALWNULL A QQC81 8A ALWNULL A QQC82 8A ALWNULL A QQC83 8A ALWNULL A QQC84 8A ALWNULL A QQC101 10A ALWNULL A QQC102 10A ALWNULL A QQC103 10A ALWNULL A QQC104 10A ALWNULL A QQC105 10A ALWNULL A QQC106 10A ALWNULL A QQC181 18A ALWNULL A QQC182 18A ALWNULL A QQC183 18A ALWNULL A QQC301 30A VARLEN ALWNULL A QQC302 30A VARLEN ALWNULL A QQC303 30A VARLEN ALWNULL A QQ1000 1000A VARLEN ALWNULL A QQTIM1 Z ALWNULL A QQTIM2 Z ALWNULL Figure 18..+....2... QSYS/QAQQDBMN Performance Statistics Physical File DDS (4 of 4) 492 DB2 UDB for AS/400 SQL Programming V4R4 ..3... .. Monitoring and Optimizing Query Performance Tools 493 ..3... Summary record for SQL Information (Part 1 of 2) Chapter 26.+.......+......+..........+...6..+.2..1.5..4....+..7..........Database Monitor Logical File DDS |....+.+..8 A* A* Database Monitor logical file 1000 A* A R QQQ1000 PFILE(*CURLIB/QAQQDBMN) A QQRID A QQTIME A QQJFLD A QQRDBN A QQSYS A QQJOB A QQUSER A QQJNUM A QQUCNT A QQRCNT RENAME(QQI5) + COLHDG('Refresh' + 'Counter') A QQUDEF A QQSTN A QQSTF RENAME(QQC11) + COLHDG('Statement' + 'Function') A QQSTOP RENAME(QQC21) + COLHDG('Statement' + 'Operation') A QQSTTY RENAME(QQC12) + COLHDG('Statement' 'Type') A QQPARS RENAME(QQC13) + COLHDG('Parse' 'Required') A QQPNAM RENAME(QQC103) + COLHDG('Package' 'Name') A QQPLIB RENAME(QQC104) + COLHDG('Package' 'Library') A QQCNAM RENAME(QQC181) + COLHDG('Cursor' 'Name') A QQSNAM RENAME(QQC182) + COLHDG('Statement' 'Name') Figure 19. Summary record for SQL Information (Part 2 of 2) Table 45.Insert D .Delete L . QQQ1000 .Select U .Summary record for SQL Information Logical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB QQUSER QQJNUM QQTHRD QQUCNT QQRCNT QQUDEF QQSTN QQSTF Physical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB QQUSER QQJNUM QQI9 QQUCNT QQI5 QQUDEF QQSTN QQC11 Description Record identification Time record was created Join field (unique per job) Relational database name System name Job name Job user Job number Thread identifier Unique count (unique per query) Unique refresh counter User defined field Statement number (unique per statement) Statement function S .Update I .Data definition language O .A A A A A A A A A A A A A QQSTIM QQSTTX QQSTOC QQROWR QQDYNR QQDACV QQTTIM QQTTMM QQTSLM QQROWF QQETIM K QQJFLD S QQRID RENAME(QQ1000) + COLHDG('Statement' 'Text') RENAME(QQC14) + COLHDG('Statement' + 'Outcome') RENAME(QQI2) + COLHDG('Rows' 'Returned') RENAME(QQC22) + COLHDG('Dynamic' 'Replan') RENAME(QQC16) + COLHDG('Data' 'Conversion') RENAME(QQI4) + COLHDG('Total' 'Time') RENAME(QQI6) + COLHDG('Total' 'Time' + 'Microseconds') RENAME(QQI7) + COLHDG('Total' 'Statement' 'Length') RENAME(QQI3) + COLHDG('Rows' 'Fetched') CMP(EQ 1000) Figure 19.Other 494 DB2 UDB for AS/400 SQL Programming V4R4 . Create function CI .Set result sets ST .Create procedure CS .Rollback SI .Set path SR .Lock MT .Insert LO .Prepare RE .Alter table CA .Describe table DI .Connect CP .Static statement Parse required.Rename table RV .Update VI .Create type DP . if applicable QQSTTY QQC12 QQPARS QQC13 QQPNAM QQPLIB QQCNAM QQC103 QQC104 QQC181 Chapter 26.Close CO .Yes N . Y .Open PR .Dynamic statement S .Release RT .Comment on CM .Execute immediate FE . Monitoring and Optimizing Query Performance Tools 495 .No Name of the package or name of the program that contains the current SQL statement Name of the library containing the package Name of the cursor corresponding to this SQL statement.Fetch FL .Set connection SE .More text OP .Value information Statement type D .Execute EI .Select into SC . QQQ1000 .Create view CY .Set transaction UP .Create index CL .Table 45.Create collection or Create schema CF .Delete DE .Label on LK .Summary record for SQL Information (continued) Logical Field Name QQSTOP Physical Field Name QQC21 Description Statement operation AL .Set variable SP .Disconnect DR .Free locator GR .Declare procedure DL .Create alias CT .Grant IN .Call CC .Describe DT .Revoke RO .Commit CN .Drop EX .Create table CV . .The CCSID of the current job is different than the CCSID of the job that last created the access plan. A4 . A2 .Object was renamed. A6 . .Object was overridden to a different object.The value of one or more of the following is different for the current job than it was for the job that last created this access plan: .Summary record for SQL Information (continued) Logical Field Name QQSNAM QQSTIM QQSTTX QQSTOC Physical Field Name QQC182 QQSTIM QQ1000 QQC14 Description Name of statement for SQL statement.Access plan was built to use a reusable Open Data Path (ODP) and the optimizer chose to use a non-reusable ODP for this call. QQQ1000 .A file or member is not the same object as the one referenced when the access plan was last built.A new access path exists over one of the files in the query.time separator. NR . if applicable Time this statement entered Statement text Statement outcome S . QQROWR QQDYNR QQI2 QQC22 496 DB2 UDB for AS/400 SQL Programming V4R4 . A8 . . . . A5 .Library list was changed. A7 .SQL QDT rebuilt for new release.Table 45.This is the first run of this query after the object containing the query has been restored. .Object was deleted and recreated.An access path that was used for this access plan no longer exists or is no longer valid. A1 .Object was moved.OS/400 Query requires the access plan to be rebuilt because of system programming changes.Access plan was built to use a non-reusable Open Data Path (ODP) and the optimizer chose to use a reusable ODP for this call.Unsuccessful Number of result rows returned Dynamic replan (access plan rebuilt) NA .Successful U .The number of records in the file member has changed by more than 10% since the access plan was last built. A9 .time format.date format.Object was saved and restored. . . . Some reasons they could be different are: . A3 .No replan.date separator. in microseconds. B0 . 9 .Host variable or column is variable length and the other is not variable length.Target table of an insert is not an SQL table.Storage pool changed or DEGREE parameter of CHGQRYA command changed. 7 . Total time (Universal Time Coordinated) for this statement. time. 0 .The system feature DB2 multisystem has been installed or removed.C host variable is NUL-terminated 4 . or timestamp column. AD . QQDACV QQC16 Data conversion N . contained in a partial row. this includes all fetches for this OPEN of the cursor. variable length. AB .Too many host variables. this includes all fetches for this OPEN of the cursor. in this record and any other records. 3 . 2 .Data.A view is either being opened by a high level language or a view is being materialized. Total time (Universal Time Coordinated) for this statement. in milliseconds.The sort sequence table specified is different than the sort sequence table that was used when this access plan was created. or blocked fetch with not enough host variables.Not applicable.The options specified have changed as a result of the query options file QAQQINI. 6 . AF .Table 45. 8 . derived expression. For fetches.No.DRDA and NULL capable.. AE . 5 . AC .Numeric types do not match.The value of the degree query attribute has changed. 1 . For fetches.A user-defined type or user-defined function is not the same object as the one referred to in the access plan. Total text length includes the length of the text.Lengths do not match. Monitoring and Optimizing Query Performance Tools 497 . which are related because of the ’MT’ operation type.CCSID conversion. Total rows fetched for cursor Time SQL request completed QQTTIM QQI4 QQTTMM QQI6 QQTSLM QQI7 QQROWF QQETIM QQI3 QQETIM Chapter 26.Summary record for SQL Information (continued) Logical Field Name Physical Field Name Description AA . QQQ1000 . 2.7....+...+.....3...... Summary record for Arrival Sequence Table 46..|. QQQ3000 .....8 A* A* Database Monitor logical file 3000 A* A R QQQ3000 PFILE(*CURLIB/QAQQDBMN) A QQRID A QQTIME A QQJFLD A QQRDBN A QQSYS A QQJOB A QQUSER A QQJNUM A QQTHRD RENAME(QQI9) + COLHDG('Thread' + 'Identifier') A QQUCNT A QQUDEF A QQQDTN A QQQDTL A QQMATN A QQMATL A QQTLN A QQTFN A QQTMN A QQPTLN A QQPTFN A QQPTMN A QQTOTR A QQREST A QQAJN A QQEPT A QQJNP A QQJNDS RENAME(QQI1) + COLHDG('Data Space' 'Number') A QQJNMT RENAME(QQC21) + COLHDG('Join' 'Method') A QQJNTY RENAME(QQC22) + COLHDG('Join' 'Type') A QQJNOP RENAME(QQC23) + COLHDG('Join' 'Operator') A QQIDXK RENAME(QQI2) + COLHDG('Advised' 'Primary' 'Keys') A QQDSS A QQIDXA A QQRCOD A QQIDXD A K QQJFLD A S QQRID CMP(EQ 3000) Figure 20...4.....5..+.6..1.....Summary record for Arrival Sequence Logical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB Physical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB Description Record identification Time record was created Join field (unique per job) Relational database name System name Job name 498 DB2 UDB for AS/400 SQL Programming V4R4 ..+.....+..+.....+..+...... Nested loop MF .No QQJNTY QQC22 QQJNOP QQC23 QQIDXK QQDSS QQI2 QQDSS QQIDXA QQIDXA Chapter 26.Equal NE .Less than LE .Exception join Join operator .Table 46.when available Data space number Join method .Greater than or equal LT .Not equal GT .when available IN . QQQ3000 .Yes N . Monitoring and Optimizing Query Performance Tools 499 .Hash join Join type .Yes N .Nested loop with selection HJ .Cartesian product Number of advised key fields that use key positioning Data space selection Y .when available EQ .Left partial outer join EX .Less than or equal CP .when available NL . in seconds Join position .No Index advised Y .Greater than GE .Inner join PO .Summary record for Arrival Sequence (continued) Logical Field Name QQUSER QQJNUM QQTHRD QQUCNT QQUDEF QQQDTN QQQDTL QQMATN QQMATL QQTLN QQTFN QQTMN QQPTLN QQPTFN QQPTMN QQTOTR QQREST QQAJN QQEPT QQJNP QQJNDS QQJNMT Physical Field Name QQUSER QQJNUM QQI9 QQUCNT QQUDEF QQQDTN QQQDTL QQMATN QQMATL QQTLN QQTFN QQTMN QQPTLN QQPTFN QQPTMN QQTOTR QQREST QQAJN QQEPT QQJNP QQI1 QQC21 Description Job user Job number Thread identifier Unique count (unique per query) User defined field QDT number (unique per QDT) QDT subquery nested level Materialized view QDT number Materialized view nested level Library File Member Physical library Physical file Physical member Total rows in table Estimated number of rows selected Estimated number of joined rows Estimated processing time. Indexes exist. T2 .Summary record for Arrival Sequence (continued) Logical Field Name QQRCOD Physical Field Name QQRCOD Description Reason code T1 . QQQ3000 .No indexes exist. Key fields for the index advised QQIDXD QQIDXD 500 DB2 UDB for AS/400 SQL Programming V4R4 . but none could be used.Optimizer chose table scan over available indexes. T3 .Table 46. ..+....+..........+.....+.1.7...2.. Monitoring and Optimizing Query Performance Tools 501 .....+.6....5...4..........+.+.3..+..|... Summary record for Using Existing Index (Part 1 of 2) Chapter 26....8 A* A* Database Monitor logical file 3001 A* A R QQQ3001 PFILE(*CURLIB/QAQQDBMN) A QQRID A QQTIME A QQJFLD A QQRDBN A QQSYS A QQJOB A QQUSER A QQJNUM A QQUCNT A QQUDEF A QQQDTN A QQQDTL A QQMATN A QQMATL A QQMATL A QQTLN A QQTFN A QQTMN A QQPTLN A QQPTFN A QQPTMN A QQILNM A QQIFNM A QQIMNM A QQTOTR A QQREST A QQFKEY A QQKSEL A QQAJN A QQEPT A QQJNP A QQJNDS RENAME(QQI1) + COLHDG('Data Space' + 'Number') A QQJNMT RENAME(QQC21) + COLHDG('Join' 'Method') A QQJNTY RENAME(QQC22) + COLHDG('Join' 'Type') A QQJNOP RENAME(QQC23) + COLHDG('Join' 'Operator') A QQIDXK RENAME(QQI2) + COLHDG('Advised' + 'Primary' + 'Keys') Figure 21.. QQQ3001 . Summary record for Using Existing Index (Part 2 of 2) Table 47.A A QQKP QQKPN A A A A A A A A A QQKS QQDSS QQIDXA QQRCOD QQCST QQIDXD QQCSTN K QQJFLD S QQRID RENAME(QQI3) + COLHDG('Number of Key' + 'Positioning' + 'Fields') RENAME(QQC11) + COLHDG('Constraint' + 'Indicator') RENAME(QQ1000) + COLHDG('Constraint' + 'Name') CMP(EQ 3001) Figure 21.Summary record for Using Existing Index Logical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB QQUSER QQJNUM QQTHRD QQUCNT QQUDEF QQQDTN QQQDTL QQMATN QQMATL QQTLN QQTFN QQTMN QQPTLN QQPTFN QQPTMN QQILNM QQIFNM QQIMNM QQTOTR QQREST Physical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB QQUSER QQJNUM QQI9 QQUCNT QQUDEF QQQDTN QQQDTL QQMATN QQMATL QQTLN QQTFN QQTMN QQPTLN QQPTFN QQPTMN QQILNM QQIFNM QQIMNM QQTOTR QQREST Description Record identification Time record was created Join field (unique per job) Relational database name System name Job name Job user Job number Thread identifier Unique count (unique per query) User defined field QDT number (unique per QDT) QDT subquery nested level Materialized view QDT number Materialized view nested level Library File Member Physical library Physical file Physical member Index library Index file Index member Total rows in table Estimated number of rows selected 502 DB2 UDB for AS/400 SQL Programming V4R4 . Not equal GT .Yes N .Cartesian product Number of advised key fields that use key positioning Key positioning Y .Greater than GE .when available NL .Record selection and Ordering/Grouping I4 .Table 47. QQQ3001 .Exception join Join operator .Yes N . in seconds Join position .Ordering/Grouping I3 .Nested loop MF .Yes N .Nested loop join I5 .Summary record for Using Existing Index (continued) Logical Field Name QQFKEY QQKSEL QQAJN QQEPT QQJNP QQJNDS QQJNMT Physical Field Name QQFKEY QQKSEL QQAJN QQEPT QQJNP QQI1 QQC21 Description Keys selected thru key positioning Keys selected thru key selection Estimated number of joined rows Estimated processing time.when available EQ .Greater than or equal LT .Record selection using bitmap processing Constraint indicator Y .Less than LE .No Key fields for index advised Constraint name QQJNTY QQC22 QQJNOP QQC23 QQIDXK QQKP QQI2 QQKP QQKS QQKS QQDSS QQDSS QQIDXA QQIDXA QQRCOD QQRCOD QQCST QQC11 QQIDXD QQCSTN QQIDXD QQC1000 Chapter 26.Less than or equal CP .Hash join Join type .Nested loop with selection HJ .No Key selection Y .Yes N .when available IN .Record selection I2 .No Reason code I1 .Equal NE .Yes N .when available Data space number Join method .No Data space selection Y .No Index advised Y . Monitoring and Optimizing Query Performance Tools 503 .Inner join PO .Left partial outer join EX . +.+.8 A* Database Monitor logical file 3002 A R QQQ3002 PFILE(*CURLIB/QAQQDBMN) A QQRID A QQTIME A QQJFLD A QQRDBN A QQSYS A QQJOB A QQUSER A QQJNUM A QQTHRD RENAME(QQI9) + COLHDG('Thread' + 'Identifier') A QQUCNT A QQUDEF A QQQDTN A QQQDTL A QQMATN A QQMATL A QQTLN A QQTFN A QQTMN A QQPTLN A QQPTFN A QQPTMN A QQILNM A QQIFNM A QQIMNM A QQNTNM A QQNLNM A QQSTIM A QQETIM A QQTOTR A QQRIDX A QQREST A QQFKEY A QQKSEL A QQAJN A QQJNP Figure 22...4....... Summary record for Index Created (Part 1 of 2) 504 DB2 UDB for AS/400 SQL Programming V4R4 ......2.3..7..|......5.....+.+.....1..+...........+...6.......+.+. A A A A A A A A A A A A A A A A QQJNDS QQJNMT QQJNTY QQJNOP QQIDXK QQEPT QQKP QQKPN QQKS QQDSS QQIDXA QQRCOD QQIDXD QQCRTK K QQJFLD S QQRID RENAME(QQI1) + COLHDG('Data Space' 'Number') RENAME(QQC21) + COLHDG('Join' 'Method') RENAME(QQC22) + COLHDG('Join' 'Type') RENAME(QQC23) + COLHDG('Join' 'Operator') RENAME(QQI2) + COLHDG('Advised' 'Primary' 'Keys') RENAME(QQI3) + COLHDG('Number of Key' + 'Positioning' + 'Fields') RENAME(QQ1000) + COLHDG('Key Fields' + 'of Index' 'Created') CMP(EQ 3002) Figure 22. Summary record for Index Created (Part 2 of 2) Table 48.Summary record for Index Created Logical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB QQUSER QQJNUM QQTHRD QQUCNT QQUDEF QQQDTN QQQDTL QQMATN QQMATL QQTLN QQTFN QQTMN QQPTLN QQPTFN QQPTMN Physical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB QQUSER QQJNUM QQI9 QQUCNT QQUDEF QQQDTN QQQDTL QQMATN QQMATL QQTLN QQTFN QQTMN QQPTLN QQPTFN QQPTMN Description Record identification Time record was created Join field (unique per job) Relational database name System name Job name Job user Job number Thread identifier Unique count (unique per query) User defined field QDT number (unique per QDT) QDT subquery nested level Materialized view QDT number Materialized view nested level Library File Member Physical library Physical file Physical member Chapter 26. QQQ3002 . Monitoring and Optimizing Query Performance Tools 505 . Table 48.when available NL .Yes N .Cartesian product Number of advised key fields that use key positioning Key positioning Y .Yes N .Less than LE .Exception join Join operator .No Data space selection Y .Equal NE .Summary record for Index Created (continued) Logical Field Name QQILNM QQIFNM QQIMNM QQNTNM QQNLNM QQSTIM QQETIM QQTOTR QQRIDX QQREST QQFKEY QQKSEL QQAJN QQEPT QQJNP QQJNDS QQJNMT Physical Field Name QQILNM QQIFNM QQIMNM QQNTNM QQNLNM QQSTIM QQETIM QQTOTR QQRIDX QQREST QQFKEY QQKSEL QQAJN QQEPT QQJNP QQI1 QQC21 Description Index library Index file Index member NLSS library NLSS table Start timestamp End timestamp Total rows in table Number of entries in index created Estimated number of rows selected Keys selected thru key positioning Keys selected thru key selection Estimated number of joined rows Estimated processing time.Nested loop with selection HJ .when available Data space number Join method .No Index advised Y .No QQJNTY QQC22 QQJNOP QQC23 QQIDXK QQKP QQI2 QQKP QQKS QQKS QQDSS QQDSS QQIDXA QQIDXA 506 DB2 UDB for AS/400 SQL Programming V4R4 .Less than or equal CP .Yes N . QQQ3002 .Inner join PO .Hash join Join type .Yes N .Left partial outer join EX .Not equal GT . in seconds Join position .Greater than or equal LT .Nested loop MF .when available IN .Greater than GE .No Key selection Y .when available EQ . ....+.6.. Monitoring and Optimizing Query Performance Tools 507 .Summary record for Index Created (continued) Logical Field Name QQRCOD Physical Field Name QQRCOD Description Reason code I1 ...+......Nested loop join Key fields for index advised Key fields for index created QQIDXD QQCRTK QQIDXD QQ1000 |..+... QQQ3002 .......+....3..Table 48.Ordering/Grouping I3 .+...8 A* A* Database Monitor logical file 3003 A* A R QQQ3003 PFILE(*CURLIB/QAQQDBMN) A QQRID A QQTIME A QQJFLD A QQRDBN A QQSYS A QQJOB A QQUSER A QQJNUM A QQTHRD RENAME(QQI9) + COLHDG('Thread' + 'Identifier') A QQUCNT A QQUDEF A QQQDTN A QQQDTL A QQMATN A QQMATL A QQSTIM A QQETIM A QQRSS A QQSSIZ RENAME(QQI1) + COLHDG('Size of' + 'Sort' + 'Space') A QQPSIZ RENAME(QQI2) + COLHDG('Pool' + 'Size') A QQPID RENAME(QQI3) + COLHDG('Pool' + 'ID') A QQIBUF RENAME(QQI4) + COLHDG('Internal' + 'Buffer' + 'Length') A QQEBUF RENAME(QQI5) + COLHDG('External' + 'Buffer' + 'Length') A QQRCOD A K QQJFLD A S QQRID CMP(EQ 3003) Figure 23.....2.Record selection and Ordering/Grouping I4 ... Summary record for Query Sort Chapter 26......+......+.1....+.4.7.Record selection I2 .5.. or contains grouping fields from a secondary file of a join query that cannot be reordered. Query optimizer chose to use a sort rather than an access path to order the results of the query. Key length of more than 2000 bytes or more than 120 key fields specified for ordering. or contains ordering fields from a secondary file of a join query that cannot be reordered. F2 F3 F4 F5 F6 F7 F8 508 DB2 UDB for AS/400 SQL Programming V4R4 . Perform specified record selection to minimize I/O wait time. UNION was specified for the query. Query contains ordering fields (ORDER BY) from more that one file. Query had to be implemented using a sort. QQQ3003 .Summary record for Query Sort Logical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB QQUSER QQJNUM QQTHRD QQUCNT QQUDEF QQQDTN QQQDTL QQMATN QQMATL QQSTIM QQETIM QQRSS QQSSIZ QQPSIZ QQPID QQIBUF QQEBUF QQRCOD Physical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB QQUSER QQJNUM QQI9 QQUCNT QQUDEF QQQDTN QQQDTL QQMATN QQMATL QQSTIM QQETIM QQRSS QQI1 QQI2 QQI3 QQI4 QQI5 QQRCOD Description Record identification Time record was created Join field (unique per job) Relational database name System name Job name Job user Job number Thread identifier Unique count (unique per query) User defined field QDT number (unique per QDT) QDT subquery nested level Materialized view QDT number Materialized view nested level Start timestamp End timestamp Number of rows selected or sorted Size of sort space Pool size Pool id Internal sort buffer length External sort buffer length Reason code F1 Query contains grouping fields (GROUP BY) from more that one file. DISTINCT was specified for the query. The grouping and ordering fields are not compatible.Table 49. ...3.4..2...+.. Monitoring and Optimizing Query Performance Tools 509 ..+..+....1......Summary record for Temporary File Logical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB QQUSER QQJNUM QQTHRD QQUCNT QQUDEF QQQDTN QQQDTL QQMATN QQMATL QQTLN Physical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB QQUSER QQJNUM QQI9 QQUCNT QQUDEF QQQDTN QQQDTL QQMATN QQMATL QQTLN Description Record identification Time record was created Join field (unique per job) Relational database name System name Job name Job user Job number Thread identifier Unique count (unique per query) User defined field QDT number (unique per QDT) QDT subquery nested level Materialized view QDT number Materialized view nested level Library Chapter 26..5.8 A* A* Database Monitor logical file 3004 A* A R QQQ3004 PFILE(*CURLIB/QAQQDBMN) A QQRID A QQTIME A QQJFLD A QQRDBN A QQSYS A QQJOB A QQUSER A QQJNUM A QQTHRD RENAME(QQI9) + COLHDG('Thread' + 'Identifier') A QQUCNT A QQUDEF A QQQDTN A QQQDTL A QQMATN A QQMATL A QQTLN A QQTFN A QQTMN A QQSTIM A QQETIM A QQDFVL RENAME(QQC11) + COLHDG('Default' + 'Values') A QQTMPR A QQRCOD A K QQJFLD A S QQRID CMP(EQ 3004) Figure 24...6.....+...... QQQ3004 .....|...+....7...+.......+. Summary record for Temporary File Table 50.+.. Query contains ordering fields (ORDER BY) from more that one file.No Number of rows in the temporary Reason code F1 Query contains grouping fields (GROUP BY) from more that one file. Key length of more than 2000 bytes or more than 120 key fields specified for ordering. File is a JLF and its join type does not match the join type specified in the query.Summary record for Temporary File (continued) Logical Field Name QQTFN QQTMN QQSTIM QQETIM QQDFVL Physical Field Name QQTFN QQTMN QQSTIM QQETIM QQC11 Description File Member Start timestamp End timestamp Default values may be present in temporary Y . QQQ3004 .Yes N . File is a complex SQL view or derived table requiring a temporary file to contain the result of the SQL view or derived table. or contains grouping fields from a secondary file of a join query that cannot be reordered. Format specified for the logical file references more than 1 physical file. Perform specified record selection to minimize I/O wait time. DISTINCT was specified for the query. The grouping and ordering fields are not compatible. Query optimizer chose to use a sort rather than an access path to order the results of the query. or contains ordering fields from a secondary file of a join query that cannot be reordered. UNION was specified for the query Query had to be implemented using a sort.Table 50. QQTMPR QQRCOD QQTMPR QQRCOD F2 F3 F4 F5 F6 F7 F8 F9 FA FB 510 DB2 UDB for AS/400 SQL Programming V4R4 . 6......+.....4....7.. Summary record for Table Locked Table 51...+.....+.+........ Monitoring and Optimizing Query Performance Tools 511 ..2.|.. QQQ3005 .+..Summary record for Table Locked Logical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB QQUSER QQJNUM QQTHRD QQUCNT QQUDEF QQQDTN QQQDTL QQMATN QQMATL QQTLN Physical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB QQUSER QQJNUM QQI9 QQUCNT QQUDEF QQQDTN QQQDTL QQMATN QQMATL QQTLN Description Record identification Time record was created Join field (unique per job) Relational database name System name Job name Job user Job number Thread identifier Unique count (unique per query) User defined field QDT number (unique per QDT) QDT subquery nested level Materialized view QDT number Materialized view nested level Library Chapter 26.........8 A* A* Database Monitor logical file 3005 A* A R QQQ3005 PFILE(*CURLIB/QAQQDBMN) A QQRID A QQTIME A QQJFLD A QQRDBN A QQSYS A QQJOB A QQUSER A QQJNUM A QQTHRD RENAME(QQI9) + COLHDG('Thread' + 'Identifier') A QQUCNT A QQUDEF A QQQDTN A QQQDTL A QQMATN A QQMATL A QQTLN A QQTFN A QQTMN A QQLCKF RENAME(QQC11) + COLHDG('Lock' + 'Indicator') A QQULCK RENAME(QQC12) + COLHDG('Unlock' + 'Request') A QQRCOD A K QQJFLD A S QQRID CMP(EQ 3005) Figure 25...+..+...1.+.....3.5.. 4.....System File with *ALL or *CS with Keep Locks L6 .. QQQ3005 ..Orderby > 2000 bytes with *ALL or *CS with Keep Locks L9 .6.+.1.....UNION with *ALL or *CS with Keep Locks L2 .+..No Unlock request Y ..Summary record for Table Locked (continued) Logical Field Name QQTFN QQTMN QQLCKF Physical Field Name QQTFN QQTMN QQC11 Description File Member Successful lock indicator Y ........+....+.+.No duplicate keys with *ALL or *CS with Keep Locks L4 ...7.8 A* A* Database Monitor logical file 3006 A* A R QQQ3006 PFILE(*CURLIB/QAQQDBMN) A QQRID A QQTIME A QQJFLD A QQRDBN A QQSYS A QQJOB A QQUSER A QQJNUM A QQTHRD RENAME(QQI9) + COLHDG('Thread' + 'Identifier') A QQUCNT A QQUDEF A QQQDTN A QQQDTL A QQMATN A QQMATL A QQTLN A QQTFN A QQTMN A QQPTLN A QQPTFN A QQPTMN A QQRCOD A K QQJFLD A S QQRID CMP(EQ 3006) Figure 26......+.No Reason code L1 .Yes N ..5...Table 51.+..+...Unknown QQULCK QQC12 QQRCOD QQRCOD |. Summary record for Access Plan Rebuilt 512 DB2 UDB for AS/400 SQL Programming V4R4 .....Yes N ..DISTINCT with *ALL or *CS with Keep Locks L3 ....2.Temporary needed with *ALL or *CS with Keep Locks L5 .3..... Monitoring and Optimizing Query Performance Tools 513 . QQQ3006 .Table 52.Summary record for Access Plan Rebuilt Logical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB QQUSER QQJNUM QQTHRD QQUCNT QQUDEF QQQDTN QQQDTL QQMATN QQMATL QQTLN QQTFN QQTMN QQPTLN QQPTFN QQPTMN Physical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB QQUSER QQJNUM QQI9 QQUCNT QQUDEF QQQDTN QQQDTL QQMATN QQMATL QQTLN QQTFN QQTMN QQPTLN QQPTFN QQPTMN Description Record identification Time record was created Join field (unique per job) Relational database name System name Job name Job user Job number Thread identifier Unique count (unique per query) User defined field QDT number (unique per QDT) QDT subquery nested level Materialized view QDT number Materialized view nested level Library File Member Physical library Physical file Physical member Chapter 26. The value of the degree query attribute has changed. v Library list was changed. Access plan was built to use a non-reusable Open Data Path (ODP) and the optimizer chose to use a reusable ODP for this call. OS/400 Query requires the access plan to be rebuilt because of system programming changes. A view is either being opened by a high level language or a view is being materialized. The number of records in the file member has changed by more than 10% since the access plan was last built. v Object was moved. v Object was saved and restored. v Object was renamed. 514 DB2 UDB for AS/400 SQL Programming V4R4 . An access path that was used for this access plan no longer exists or is no longer valid. The options specified have changed as a result of the query options file QAQQINI. Some reasons they could be different are: v Object was deleted and recreated. A user-defined type or user-defined function is not the same object as the one referred to in the access plan. A2 A3 A4 A5 A6 A7 A8 A9 Access plan was built to use a reusable Open Data Path (ODP) and the optimizer chose to use a non-reusable ODP for this call. v Object was overridden to a different object.Summary record for Access Plan Rebuilt (continued) Logical Field Name QQRCOD Physical Field Name QQRCOD Description Reason code why access plan was rebuilt A1 A file or member is not the same object as the one referenced when the access plan was last built. Storage pool changed or DEGREE parameter of CHGQRYA command changed. A new access path exists over one of the files in the query. The value of one or more of the following is different for the current job than it was for the job that last created this access plan: v date format v date separator v time format v time separator AA AB AC AD AE AF B0 The sort sequence table specified is different than the sort sequence table that was used when this access plan was created. QQQ3006 . The CCSID of the current job is different than the CCSID of the job that last created the access plan. v This is the first run of this query after the object containing the query has been restored. The system feature DB2 multisystem has been installed or removed.Table 52. ..4......+.. Summary record for Optimizer Timed Out Table 53.7. Monitoring and Optimizing Query Performance Tools 515 ......Summary record for Access Plan Rebuilt (continued) Logical Field Name QQINLN QQINFN Physical Field Name QQC101 QQC102 Description Query Options Library Name Query Options File Name |..2....3......6....+.+.....+..+.....5. QQQ3007 . QQQ3006 .....1....+.+.Summary record for Optimizer Timed Out Logical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB QQUSER QQJNUM QQTHRD Physical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB QQUSER QQJNUM QQI9 Description Record identification Time record was created Join field (unique per job) Relational database name System name Job name Job user Job number Thread identifier Chapter 26..Table 52.+..8 A* A* Database Monitor logical file 3007 A* A R QQQ3007 PFILE(*CURLIB/QAQQDBMN) A QQRID A QQTIME A QQJFLD A QQRDBN A QQSYS A QQJOB A QQUSER A QQJNUM A QQTHRD RENAME(QQI9) + COLHDG('Thread' + 'Identifier') A QQUCNT A QQUDEF A QQQDTN A QQQDTL A QQMATN A QQMATL A QQTLN A QQTFN A QQTMN A QQPTLN A QQPTFN A QQPTMN A QQIDXN RENAME(QQ1000) + COLHDG('Index' + 'Names') A QQTOUT RENAME(QQC11) + COLHDG('Optimizer' + 'Timed Out') A K QQJFLD A S QQRID CMP(EQ 3007) Figure 27..... ....No |.3...1...............+.+....Table 53..Summary record for Optimizer Timed Out (continued) Logical Field Name QQUCNT QQUDEF QQQDTN QQQDTL QQMATN QQMATL QQTLN QQTFN QQTMN QQPTLN QQPTFN QQPTMN QQIDXN QQTOUT Physical Field Name QQUCNT QQUDEF QQQDTN QQQDTL QQMATN QQMATL QQTLN QQTFN QQTMN QQPTLN QQPTFN QQPTMN QQ1000 QQC11 Description Unique count (unique per query) User defined field QDT number (unique per QDT) QDT subquery nested level Materialized view QDT number Materialized view nested level Library File Member Physical library Physical file Physical member Index names Optimizer timed out Y ....7.....8 A* A* Database Monitor logical file 3008 A* A R QQQ3008 PFILE(*CURLIB/QAQQDBMN) A QQRID A QQTIME A QQJFLD A QQRDBN A QQSYS A QQJOB A QQUSER A QQJNUM A QQTHRD RENAME(QQI9) + COLHDG('Thread' + 'Identifier') A QQUCNT A QQUDEF A QQQDTN A QQQDTL A QQMATN A QQMATL A QQORGQ RENAME(QQI1) + COLHDG('Original' + 'Number' + 'of QDTs') A QQMRGQ RENAME(QQI2) + COLHDG('Number' + 'of QDTs' + 'Merged') A K QQJFLD A S QQRID CMP(EQ 3008) Figure 28.+.6..+... Summary record for Subquery Processing 516 DB2 UDB for AS/400 SQL Programming V4R4 .+...Yes N .+.+....+...2.. QQQ3007 ..4...5... Summary record for Subquery Processing Logical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB QQUSER QQJNUM QQTHRD QQUCNT QQUDEF QQQDTN QQQDTL QQMATN QQMATL QQORGQ QQMRGQ Physical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB QQUSER QQJNUM QQI9 QQUCNT QQUDEF QQQDTN QQQDTL QQMATN QQMATL QQI1 QQI2 Description Record identification Time record was created Join field (unique per job) Relational database name System name Job name Job user Job number Thread identifier Unique count (unique per query) User defined field QDT number (unique per QDT) QDT subquery nested level Materialized view QDT number Materialized view nested level Original number of QDTs Number of QDTs merged Chapter 26. Monitoring and Optimizing Query Performance Tools 517 . QQQ3008 .Table 54. 6.+..Field not used 518 DB2 UDB for AS/400 SQL Programming V4R4 .+..Summary record for Host Variable and ODP Implementation Logical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB QQUSER QQJNUM QQTHRD QQUCNT QQRCNT QQUDEF QQODPI Physical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB QQUSER QQJNUM QQI9 QQUCNT QQRCNT QQUDEF QQC11 Description Record identification Time record was created Join field (unique per job) Relational database name System name Job name Job user Job number Thread identifier Unique count (unique per query) Unique refresh counter User defined field ODP implementation R .....8 A* A* Database Monitor logical file 3010 A* A R QQQ3010 PFILE(*CURLIB/QAQQDBMN) A QQRID A QQTIME A QQJFLD A QQRDBN A QQSYS A QQJOB A QQUSER A QQJNUM A QQTHRD RENAME(QQI9) + COLHDG('Thread' + 'Identifier') A QQUCNT A QQRCNT RENAME(QQI5) + COLHDG('Refresh' + 'Counter') A QQUDEF A QQODPI RENAME(QQC11) + COLHDG('ODP' + 'Implementation') A QQHVI RENAME(QQC12) + COLHDG('Host Variable' + 'Implementation') A QQHVAR RENAME(QQ1000) + COLHDG('Host Variable' + 'Values') A K QQJFLD A S QQRID CMP(EQ 3010) Figure 29....Nonreusable ODP (V2) ’ ’ ...+......5.+....+..2...7..+.|...4.......+....+.......1.3. QQQ3010 .....Reusable ODP (ISV) N .... Summary record for Host Variable and ODP Implementation Table 55. ..+...4..+..+.2...+. Monitoring and Optimizing Query Performance Tools 519 ..8 A* A* Database Monitor logical file 3014 A* A R QQQ3014 PFILE(*CURLIB/QAQQDBMN) A QQRID A QQTIME A QQJFLD A QQRDBN A QQSYS A QQJOB A QQUSER A QQJNUM A QQTHRD RENAME(QQI9) + COLHDG('Thread' + 'Identifier') A QQUCNT A QQUDEF A QQQDTN A QQQDTL A QQMATN A QQMATL A QQREST A QQEPT A QQTTIM RENAME(QQI1) + COLHDG('ODP' + 'Open' 'Time') A QQORDG A QQGRPG A QQJNG A QQJNTY RENAME(QQC22) + COLHDG('Join' + 'Type') Figure 30.....7..+...Table 55.Interface supplied values (ISV) V .....+...Summary record for Host Variable and ODP Implementation (continued) Logical Field Name QQHVI Physical Field Name QQC12 Description Host variable implementation I .File management row positioning (UP) Host variable values QQHVAR QQ1000 |... QQQ3010 ......+......5.......3.6....1....Host variables treated as literals (V2) U . Summary record for Generic Query Information (Part 1 of 2) Chapter 26.+.. QQQ3014 .Summary record for Generic Query Information Logical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB QQUSER QQJNUM QQTHRD QQUCNT QQUDEF QQQDTN QQQDTL QQMATN QQMATL QQREST QQEPT QQTTIM Physical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB QQUSER QQJNUM QQI9 QQUCNT QQUDEF QQQDTN QQQDTL QQMATN QQMATL QQREST QQEPT QQI1 Description Record identification Time record was created Join field (unique per job) Relational database name System name Job name Job user Job number Thread identifier Unique count (unique per query) User defined field QDT number (unique per query) QDT subquery nested level Materialized view QDT number Materialized view nested level Estimated number of rows selected Estimated processing time. Summary record for Generic Query Information (Part 2 of 2) Table 56. in milliseconds 520 DB2 UDB for AS/400 SQL Programming V4R4 . in seconds Time spent to open cursor.A A A A A QQUNIN QQSUBQ QQHSTV QQRCDS QQGVNE A QQGVNS A A QQOPID QQINFN A QQINLN A QQIDXSK A A K QQJFLD S QQRID RENAME(QQC11) + COLHDG('Query' + 'Governor' + 'Enabled') RENAME(QQC12) + COLHDG('Stopped' + 'by Query' + 'Governor') RENAME(QQC101) + COLHDG('Query' + 'Open ID') RENAME(QQC102) + COLHDG('Query' + 'Options' + 'File Name') RENAME(QQC103) + COLHDG('Query' + 'Options' + 'Library') RENAME(QQC13) + COLHDG('Index' + 'Skip Key') + "Processing') CMP(EQ 3014) Figure 30. Yes N .Yes N . QQQ3014 .No Query governor stopped the query Y .Inner join PO .No Join type .No Joining Y .Table 56.Yes N . Monitoring and Optimizing Query Performance Tools 521 .Yes N .No Record selection Y .Yes N .Left partial outer join EX .Yes N .Yes N .No Grouping Y .Exception join Union Y .No Subquery Y .Yes N .Yes N .Yes N .Summary record for Generic Query Information (continued) Logical Field Name QQORDG Physical Field Name QQORDG Description Ordering Y .when available IN .No Query open ID Query Options Library Name Query Options File Name Index skip key processing indicator Y .No QQGRPG QQGRPG QQJNG QQJNG QQJNTY QQC22 QQUNIN QQUNIN QQSUBQ QQSUBQ QQHSTV QQHSTV QQRCDS QQRCDS QQGVNE QQC11 QQGVNS QQC12 QQOPID QQINLN QQINFN QQIDXSK QQC101 QQC102 QQC103 QQC13 Chapter 26.No Query governor enabled Y .No Host variables Y . ..+....+...+.5.......Current J .... QQQ3018 ...4...All Command type S .Job name A ...STRDBMON E .....7..+....2....All jobs QQCMDT QQC12 QQJOBI QQC301 522 DB2 UDB for AS/400 SQL Programming V4R4 .8 A* A* Database Monitor logical file 3018 A* A R QQQ3018 PFILE(*CURLIB/QAQQDBMN) A QQRID A QQTIME A QQJFLD A QQRDBN A QQSYS A QQJOB A QQUSER A QQJNUM A QQTHRD RENAME(QQI9) + COLHDG('Thread' + 'Identifier') A QQUDEF A QQJOBT RENAME(QQC11)+ COLHDG('Job' + 'Type') A QQCMDT RENAME(QQC12) + COLHDG('Command' + 'Type') A QQJOBI RENAME(QQC301) + COLHDG('Job' + 'Info') A K QQJFLD A S QQRID CMP(EQ 3018) Figure 31..6.Current job Job number/User/Job name *ALL ...Summary record for STRDBMON/ENDDBMON Logical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB QQUSER QQJNUM QQTHRD QQUDEF QQJOBT Physical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB QQUSER QQJNUM QQI9 QQUDEF QQC11 Description Record identification Time record was created Join field (unique per job) Relational database name System name Job name Job user Job number Thread identifier User defined field Type of job monitored C .1.+.....+. Summary record for STRDBMON/ENDDBMON Table 57...+..|.ENDDBMON Monitored job information * ...3.+... QQQ3019 .+......2....6.....Detail record for Records Retrieved Logical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB Physical Field Name QQRID QQTIME QQJFLD QQRDBN QQSYS QQJOB Description Record identification Time record was created Join field (unique per job) Relational database name System name Job name Chapter 26.. Detail record for Records Retrieved Table 58..+....1... Monitoring and Optimizing Query Performance Tools 523 .7...|...4...+......+.8 A* A* Database Monitor logical file 3019 A* A R QQQ3019 PFILE(*CURLIB/QAQQDBMN) A QQRID A QQTIME A QQJFLD A QQRDBN A QQSYS A QQJOB A QQUSER A QQJNUM A QQTHRD RENAME(QQI9) + COLHDG('Thread' + 'Identifier') A QQUCNT A QQUDEF A QQQDTN A QQQDTL A QQMATN A QQCPUT RENAME(QQI1) + COLHDG('Record' + 'Retrieval' + 'CPU Time') A QQCLKT RENAME(QQI2) + COLHDG('Record' + 'Retrieval' + 'Clock Time') A QQSYNR RENAME(QQI3) + COLHDG('Synch' + 'Reads') A QQSYNW RENAME(QQI4) + COLHDG('Synch' + 'Writes') A QQASYR RENAME(QQI5) + COLHDG('Asynch' + 'Reads') A QQASYW RENAME(QQI6) + COLHDG('Asynch' + 'Writes') A QQRCDR RENAME(QQI7) + COLHDG('Records' + 'Returned') A QQGETC RENAME(QQI8) + COLHDG('Number' + 'of GETs') A K QQJFLD A S QQRID CMP(EQ 3019) Figure 32...+....+..5.+.+........3..... The Start Database Monitor (STRDBMON) can constrain system resources when collecting performance information. The memory-based collection mode reduces the system resources consumed by collecting and managing performance results in memory. This overhead is mainly attributed to the fact that performance information is written directly to a database file as the information is collected. This tool is only intended for SQL performance monitoring and is useful for programmers and performance analysts. takes database monitoring statistics and manages them for the user in memory. in milliseconds Number of synchronous database reads Number of synchronous database writes Number of asynchronous database reads Number of asynchronous database writes Number of records returned Number of calls to retrieve records returned Memory Resident Database Monitor APIs The Memory Resident Database Monitor (DBMon) is a tool that provides another method for monitoring database performance. At the expense of some detail.Table 58. The DBMon monitor. This allows the monitor to gather database performance statistics with a minimal impact to the performance of the system as whole (or to the performance of individual SQL statements). 524 DB2 UDB for AS/400 SQL Programming V4R4 . with the help of a new set of APIs. but the performance statistics are kept in memory.Detail record for Records Retrieved (continued) Logical Field Name QQUSER QQJNUM QQTHRD QQUCNT QQUDEF QQQDTN QQQDTL QQMATN QQMATL QQCPUT QQCLKT QQSYNR QQSYNW QQASYR QQASYW QQRCDR QQGETC Physical Field Name QQUSER QQJNUM QQI9 QQUCNT QQUDEF QQQDTN QQQDTL QQMATN QQMATL QQI1 QQI2 QQI3 QQI4 QQI5 QQI6 QQI7 QQI8 Description Job user Job number Thread identifier Unique count (unique per query) User defined field QDT number (unique per query) QDT subquery nested level Materialized view QDT number Materialized view nested level CPU time to return all records. The objective is to get the statistics to memory as fast as possible while deferring any manipulation or conversion of the data until the performance data is dumped to a result file for analysis. information is summarized for identical SQL statements to reduce the amount of information collected. The DBMon monitor collects much of the same information as the STRDBMON monitor. This memory-based monitor reduces CPU overhead as well as resulting file sizes. QQQ3019 . in milliseconds Clock time to return all records. Each SQL statement is identified by the monitor according to the: v statement name v package (or program) v library that contains the prepared statement v cursor name that is used For pure dynamic statements. the system drops the statements that have not been executed recently. the system moves information from the local job space to a common system space. An API supports each of the following activities: v Start the new monitor v Dump statistics to files v Clear the monitor data from memory v Query the monitor status v End the new monitor When you start the new monitor. This means that for each unique SQL statement. see the System API Reference manual. In these cases. the STRDBMON monitor should still be used. External API Description The memory resident database monitor is controlled by a set of APIs. | | | | | | | | | | | | A new set of APIs enable support for the DBMon monitor. the statement text is kept in a separate space and the statement identification will be handled internally via a pointer. information is stored in the local address space of each job that the system monitors. There are circumstances where the loss of detail in the DBMon monitor will not be sufficient to fully analyze an SQL statement. External API Description QQQSSDBM QQQCSDBM QQQDSDBM QQQESDBM QQQQSDBM API to start the SQL monitor API to clear SQL monitor memory API to dump the contents of the SQL monitor to file API to end the SQL monitor API to query status of the database monitor External File Description The memory resident database monitor uses its own set of physical files instead of using the single physical with logical files that the STRDBMON monitor uses. The memory resident database monitor files closely match the suggested logical files of the STRDBMON monitor. For additional information. information is accumulated from each run of the statement and the detail information is only collected for the most expensive statement execution. If more statements are executed than can fit in this amount of common system space. Monitoring and Optimizing Query Performance Tools 525 . As each statement completes.The DBMon monitor is not meant to replace the STRDBMON monitor. The DBMon monitor manages the data in memory combining and accumulating the information into a series of record formats. Chapter 26. Table 59. Summary Record for SQL Information Column Name QQKEY QQTIME QQJOB QQUSER QQJNUM QQTHID QQUDEF QQPLIB QQPNAM QQSNAM QQCNT QQAVGT QQMINT QQMAXT QQOPNT QQFETT QQCLST QQOTHT QQLTU QQMETU QQAPRT QQFULO QQPSUO Description Join field (unique per query) used to link records for a single query together Time record was created Job name Job user Job number Thread Id User defined field Name of the library containing the program or package Name of the package or name of the program that contains the current SQL statement Name of the sttement for SQL statement. External File Description (QAQQQRYI) Table 61. External File Description QAQQQRYI QAQQTEXT QAQQ3000 QAQQ3001 QAQQ3002 QAQQ3003 QAQQ3004 QAQQ3007 QAQQ3008 QAQQ3010 Query (SQL) information SQL statement text Table scan Index used Index created Sort Temporary file Optimizer time out/ all access paths considered Subquery Host variable values The information relating to the locked tables (QQQ3005) was omitted and the replan information was combined with the QAQQQRYI.Table 60. QAQQQRYI . and QQQ3010 (ODP and host variable information) is found in both QAQQ3010 and QAQQQRYI files. if applicable Statement usage count Average runtime (ms) Minimum runtime (ms) Maximum runtime (ms) Open time for most expensive execution (ms) Fetch time for most expensive execution (ms) Close time for most expensive execution (ms) Other time for most expensive execution (ms) Time statement last used Most expensive time used Access plan rebuild time Number of full opens Number of pseudo-opens 526 DB2 UDB for AS/400 SQL Programming V4R4 . Create index CL .Describe table DI .Declare cursor DP .Update I . Monitoring and Optimizing Query Performance Tools 527 .Drop EX .Connect CP .Select into SC .Create collection or Create schema CD .Set path SR .Update QQSTOP Chapter 26.Prepare RE .Open/Fetch/Close/Delete OF .Grant IN .Set transaction UP .Call CC .Create table CV .Execute immediate FE .Set variable SP .Execute EI .Open/Fetch/Close/Update PR .Label on LK .SelectU .Create view DC.Summary Record for SQL Information (continued) Column Name QQTOTR QQRROW QQRROW Description Total rows in file if non-join Number of result rows returned Statement function S .Table 61.Create alias CT .Commit CN .Set results ST .Release RT .Open OC .Create function CI .Close CO .Set connection SV .Free locator GR . QAQQQRYI .Insert D .Insert LO .Lock OP .Fetch FC .Other Statement operation AL .Delete DE .Create procedure CS .Data definition language O .Open/Fetch/Close OD .Create distinct type CF .Rename table RV .Declare procedure DL .Rollback SI .Comment on CM .Disconnect DR .Open/Fetch OU .Revoke RO .Delete L .Alter table CA .Fetch/Close FL .Describe DT . v Object was overridden to a different object. The number of records in the file member has changed by more than 10% since the access plan was last built. v Library list was changed.Summary Record for SQL Information (continued) Column Name QQODPI Description ODP implementation R . v Object was renamed.Table 61. The CCSID of the current job is different than the CCSID of the job that last created the access plan.Interface supplied values (ISV) V .Non-reusable ODP (V2) Host variable implementation I .Reusable ODP (ISV) N . A new access path exists over one of the files in the query. OS/400 Query requires the access plan to be rebuilt because of system programming changes. v Object was saved and restored. A2 A3 A4 A5 A6 A7 A8 A9 Access plan was built to use a reusable Open Data Path (ODP) and the optimizer chose to use a non-reusable ODP for this call. QAQQQRYI . v This is the first run of this query after the object containing the query has been restored.Host variables treated as literals (V2) U . The value of one or more of the following is different for the current job than it was for the job that last created this access plan: v date format v date separator v time format v time separator QQHVI QQAPR 528 DB2 UDB for AS/400 SQL Programming V4R4 . An access path that was used for this access plan no longer exists or is no longer valid. v Object was moved. Access plan was built to use a non-reusable Open Data Path (ODP) and the optimizer chose to use a reusable ODP for this call. Some reasons they could be different are: v Object was deleted and recreated.File management row positioning (UP) Access plan rebuilt A1 A file or member is not the same object as the one referenced when the access plan was last built. derived expression. Target table of an insert is not an SQL table. QQDACV Data conversion N 0 1 2 3 4 5 6 7 8 9 No. Numeric types do not match. DRDA and NULL capable. The system feature DB2 multisystem has been installed or removed. Lengths do not match. QQCTS QQCIU QQCIC QQCSO QQCTF QQCIA QQCAPR QQARSS QQC11 QQCTS QQC12 QQC21 QQC22 QQI1 Statement table scan usage count Statement index usage count Statement index creation count Statement sort usage countr Statement temporary file count Statement index advised count Statement access plan rebuild count Average result set size Statement temporary file count Reserved Reserved Reserved Reserved Reserved Chapter 26. Data. time. variable ength. Not applicable. A view is either being opened by a high level language or a view is being materialized. Too many host variables. A user-defined type or user-defined function is not the same object as the one referred to in the access plan. or blocked fetch with not enough host variables. contained in a partial row. Monitoring and Optimizing Query Performance Tools 529 . Storage pool changed or DEGREE parameter of CHGQRYA command changed. The options specified have changed as a result of the query options file QAQQINI. or timestamp column. CCSID conversion.Summary Record for SQL Information (continued) Column Name Description AA AB AC AD AE AF B0 The sort sequence table specified is different than the sort sequence table that was used when this access plan was created.Table 61. C host variable is NUL-terminated. The value of the degree query attribute has changed. Host variable or column is variable length and the other s not variable length. QAQQQRYI . Table 61.when available Data space number 530 DB2 UDB for AS/400 SQL Programming V4R4 . QAQQ3000 . QAQQTEXT . in seconds Join position . QAQQQRYI .Summary Record for SQL Information (continued) Column Name QQI2 QQC301 QQC302 QQC1000 Description Reserved Reserved Reserved Reserved External File Description (QAQQTEXT) Table 62.Summary Record for Arrival Sequence Column Name QQKEY QQTIME QQQDTN QQQDTL QQMATN QQMATL QQTLN QQPTFN QQTOTR QQREST QQAJN QQEPT QQJNP QQJNDS Description Join field (unique per query) used to link records for a single query togetherecord identification Time record was created QDT number (unique per ODT) QDT subquery nested level Materialized view QDT number Materialized view nested level Physical library Physical file Total rows in table Estimated number of rows selected Estimated number of joined rows Estimated procesing time.Summary Record for SQL Statement Column Name QQKEY QQTIME QQSTTX QQC11 QQC12 QQC21 QQC22 QQQI1 QQI2 QQC301 QQC302 QQ1000 Description Join field (unique per query) used to link records for a single query togetherecord identification Time record was created Statement text Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved External File Description (QAQQ3000) Table 63. QAQQ3000 .Yes N .Less than LE .Summary Record for Arrival Sequence (continued) Column Name QQJNMT Description Join method .when available IN .Hash join Join type .Summary Record for Using Existing Index Column Name QQKEY QQTIME Description Join field (unique per query) used to link records for a single query together Time record was created Chapter 26.Nested loop MF .No Reason code T1 . QQQ3001 . Library-long File-long Physical library-long Physical file-long Key fields for the index advised Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved QQJNTY QQJNOP QQDSS QQIDXA QQRCOD QQLTLN QQLTFN QQLPTL QQLPTF QQIDXD QQC11 QQC12 QQC21 QQC22 QQI1 QQI2 QQC301 QQC302 QQ1000 External File Description (QAQQ3001) Table 64.Equal NE .Cartesian product Data space selection Y . Monitoring and Optimizing Query Performance Tools 531 . T2 .Less than or equal CP .Yes N .when available EQ .No Index advised Y .Left partial outer join EX .No indexes exist.Table 63.Indexes exist. but none could be used.Optimizer chose table scan over available indexes.Nested loop with selection HJ .Greater than GE .Greater than or equal LT .Exception join Join operator .when available NL .Not equal GT .Inner join PO . T3 . when available NL .No QQJNTY QQJNOP QQIDXK QQKP QQKS QQDSS QQIDXA 532 DB2 UDB for AS/400 SQL Programming V4R4 .Greater than or equal LT .No Key selection Y .Hash join Join type .Less than LE .Yes N .No Index advised Y .Yes N .when available EQ .Greater than GE .Table 64.No Data space selection Y .Left partial outer join EX .Yes N .Exception join Join operator .when available IN .Equal NE .Less than or equal CP .Yes N .Nested loop MF .Cartesian product Number of advised key fields that use key positioning Key positioning Y .Inner join PO . in seconds Join method . QQQ3001 .Not equal GT .when available Estimated procesing time.Summary Record for Using Existing Index (continued) Column Name QQQDTN QQQDTL QQMATN QQMATL QQTLN QQTFN QQILNM QQIFNM QQTOTR QQREST QQAJN QQEPT QQJNMT Description QDT number (unique per QDT) RQDT subquery nested levelelational database name Materialized view QDT number Materialized view nested level Library File Index library Index file Total rows in table Estimated number of rows selected Join position .Nested loop with selection HJ . Nested loop join I5 .Record selection I2 . QQQ3001 .Summary Record for Using Existing Index (continued) Column Name QQRCOD Description Reason code I1 .Yes N .Record selection and Ordering/Grouping I4 . QQQ3002 .No Constraint name Library-long File-long Physical library-long Physical file-long Key fields for the index advised Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved QQCST QQCSTN QQLTLN QQLTFN QQLPTL QQLPTF QQIDXD QQC11 QQC12 QQC21 QQC22 QQI1 QQI2 QQC301 QQC302 QQ1000 External File Description (QAQQ3002) Table 65.Table 64.Ordering/Grouping I3 .Summary Rrecord for Index Created Column Name QQKEY QQTIME QQQDTN QQQDTL QQMATN QQMATL QQTLN QQTFN QQILNM QQIFNM QQNTNM QQNLNM QQTOTR Description Join field (unique per query) used to link records for a single query together Time record was created QDT number (unique per QDT) RQDT subquery nested levelelational database name Materialized view QDT number Materialized view nested level Library File Index library Index file NLSS table NLSS library Total rows in table Chapter 26.Record selection using bitmap processing Constraint indicator Y . Monitoring and Optimizing Query Performance Tools 533 . Exception join Join operator .No Reason code I1 .Summary Rrecord for Index Created (continued) Column Name QQRIDX QQREST QQFKEY QQKSEL QQAJN QQJNP QQJNDS QQJNMT Description Number of entries in index created Estimated number of rows selected Number of key positioning keys Number of key selection keys Estimated number of joined rows Join position .Yes N .Ordering/Grouping I3 .when available EQ . in seconds Key positioning Y .when available IN .Table 65.Less than or equal CP .when available NL .No Data space selection Y .No QQJNTY QQJNOP QQIDXK QQEPT QQKP QQKPN QQKS QQDSS QQIDXA QQRCOD QQCST 534 DB2 UDB for AS/400 SQL Programming V4R4 .Yes N .Greater than GE .Hash join Join type .Nested loop with selection HJ .Record selection and Ordering/Grouping I4 .No Number of key positioning fields Key selection Y .No Index advised Y .Left partial outer join EX .Yes N .Nested loop MF .Greater than or equal LT .Record selection using bitmap processing Constraint indicator Y .Cartesian product Number of advised key fields that use key positioning Estimated procesing time. QQQ3002 .Not equal GT .Record selection I2 .Yes N .Yes N .Inner join PO .Equal NE .Nested loop join I5 .Less than LE .when available Data space number Join method . QQQ3002 .Table 65. Monitoring and Optimizing Query Performance Tools 535 .Summary Rrecord for Index Created (continued) Column Name QQCSTN QQTTIM QQLTLN QQLTFN QQLPTL QQLPTF QQLILN QQLIFN QQLNTN QQLNLN QQIDXD QQCRTK QQC11 QQC12 QQC21 QQC22 QQI1 QQI2 QQC301 QQC302 QQ1000 Description Constraint name Index create time Library-long File-long Physical library-long Physical file-long Index library-long Index file-long NLSS table-long NLSS library-long Key fields for the index advised Key fields for index created Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved External File Description (QAQQ3003) Table 66. QQQ3003 .Summary Record for Query Sort Column Name QQKEY QQTIME QQQDTN QQQDTL QQMATN QQMATL QQTTIM QQRSS QQSIZ QQPSIZ QQPID QQIBUF QQEBUF Description Join field (unique per query) used to link records for a single query together Time record was created QDT number (unique per QDT) RQDT subquery nested levelelational database name Materialized view QDT number Materialized view nested level Sort time Number of rows selected or sorted Size of sort space Pool size Pool id Internal sort buffer length External sort buffer length Chapter 26. Query contains ordering fields (Order By) from more than one file. Perform specified record selection to minimize I/O wait time.Summary Record for Temporary File Column Name QQKEY QQTIME QQQDTN QQQDTL QQMATN QQMATL QQTLN QQTFN QQTTIM QQTMPR Description Join field (unique per query) used to link records for a single query together Time record was created QDT number (unique per QDT) RQDT subquery nested levelelational database name Materialized view QDT number Materialized view nested level Library File Temporary file create time Number of rows in temporary 536 DB2 UDB for AS/400 SQL Programming V4R4 . Query had to be implemented using a sort. Key length of more than 2000 bytes or more than 120 fields specified for ordering.Table 66. or contains grouping fields from a secondary file of a join query that cannot be reordered. QQQ3003 . Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved External File Description (QAQQ3004) Table 67. or contains ordering fields from a secondary file of a join query that cannot be reordered.Summary Record for Query Sort (continued) Column Name QQRCOD Description Reason code F1 F2 F3 F4 F5 F6 F7 F8 QQC11 QQC12 QQC21 QQC22 QQI1 QQI2 QQC301 QQC302 QQ1000 Query contains grouping fields (Group By) from more than one file. Query optimizer chose to use a sort rather than an access path to order the results of the query. QQQ3004 . DISTINCT was specified for the query. The grouping and ordering fields are not compatible. UNION was specified for the query. Summary Record for Optimizer Information Column Name QQKEY QQTIME QQQDTN QQQDTL QQMATN Description Join field (unique per query) used to link records for a single query together Time record was created QDT number (unique per QDT) RQDT subquery nested levelelational database name Materialized view QDT number Chapter 26. Query had to be implemented using a sort. or contains ordering fields from a secondary file of a join query that cannot be reordered. Perform specified record selection to minimize I/O wait time. QQQ3004 . Format specified for the logical file references more than one physical file. The grouping and ordering fields are not compatible.No Library-long File-long Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved QQLTLN QQLTFN QQC11 QQC12 QQC21 QQC22 QQI1 QQI2 QQC301 QQC302 QQ1000 External File Description (QAQQ3007) Table 68. UNION was specified for the query.Summary Record for Temporary File (continued) Column Name QQRCOD Description Reason code F1 F2 F3 F4 F5 F6 F7 F8 F9 FA FB Query contains grouping fields (Group By) from more than one file. QQQ3007 . DISTINCT was specified for the query. Key length of more than 2000 bytes or more than 120 fields specified for ordering.Yes N . Monitoring and Optimizing Query Performance Tools 537 . File is a complex SQL view requiring a temporary file to contain the results of the SQL view. Query optimizer chose to use a sort rather than an access path to order the results of the query.Table 67. or contains grouping fields from a secondary file of a join query that cannot be reordered. Query contains ordering fields (Order By) from more than one file. File is a JLF and its join type does not match the join type specified in the query. QQDFVL Default values may be present in temporary Y . Summary Record for Optimizer Information (continued) Column Name QQMATL QQTLN QQTFN QQPTLN QQPTFN QQTOUT Description Materialized view nested level Library File Physical library Physical file Optimizer timed out Y . QQQ3007 .Table 68. Reason code Library-long File-long Physical library-long Physical file-long Index names Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved QQIRSN QQLTLN QQLTFN QQPTL QQPTF QQIDXN QQC11 QQC12 QQC21 QQC22 QQI1 QQI2 QQC301 QQC302 QQ1000 External File Description (QAQQ3008) Table 69. QQQ3008 .Yes N .No.Summary Record for Subquery Processing Column Name QQKEY QQTIME QQQDTN QQQDTL QQMATN QQMATL QQORGQ QQMRGQ QQC11 QQC12 QQC21 QQC22 QQI1 QQI2 Description Join field (unique per query) used to link records for a single query together Time record was created QDT number (unique per QDT) RQDT subquery nested levelelational database name Materialized view QDT number Materialized view nested level Materialized view QDT number Materialized view nested level Reserved Reserved Reserved Reserved Reserved Reserved DB2 UDB for AS/400 SQL Programming V4R4 538 . Table 69. If you are using Operation Navigator with the support for the SQL Monitor.Summary Record for Subquery Processing (continued) Column Name QQC301 QQC302 QQ1000 Description Reserved Reserved Reserved External File Description (QAQQ3010) Table 70.3) DECIMAL(QQMINT/1000.3) DECIMAL(QQFETT/1000.18. Runtime".18.Summary Record for Host Variable and ODP Implementation Column Name QQKEY QQTIME QQHVAR QQC11 QQC12 QQC21 QQC22 QQI1 QQI2 QQC301 QQC302 Description Join field (unique per query) used to link records for a single query together Time record was created Host variable values Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Sample SQL Queries | | | | | | | | | | | | | | | | | | | | | | | | | | | | As with the STRDBMON monitor. Close Time".3) DECIMAL(QQCLST/1000. /* Costs */ DECIMAL(QQMAXT/1000.3) DECIMAL(QQOPNT/1000.18.3) QQMETU as "Most Expensive QQLTU as "Last Use". /* Statement Identification */ CASE QQSTOP Chapter 26.3) DECIMAL(QQOTHT/1000. as "Maximum as "Average as "Minimum as "Maximum as "Maximum as "Maximum as "Maximum Use".3) DECIMAL(QQAVGT/1000. SELECT /* Database Performance Monitor Basic Statement Information */ /* Time */ a. There are a number of shipped queries that can be used or modified to extract the information from any of the files. Monitoring and Optimizing Query Performance Tools 539 . QQQ3010 . Fetch Time ". This can be done through any query interface that the user wishes.18.18. QQQ3008 . you have the ability to analyze the results direct through the GUI interface. Other Time ".18. The sample query listed below will give the user the Basic Statement Information about all of the statements that were monitored.18.QQTIME as "Time". it is up to the user to extract the information from the files in which all of the monitored data is stored. Runtime". Runtime". Open Time". ....UPDATE' WHEN 'GR' THEN 'GRANT' WHEN 'IC' THEN 'INSERT' WHEN 'IN' THEN 'INSERT' WHEN 'LO' THEN 'LABEL ON' WHEN 'LK' THEN 'LOCK' WHEN 'OC' THEN 'OPEN..... varchar(b.| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | WHEN 'AL' THEN 'ALTER TABLE' WHEN 'CA' THEN 'CALL' WHEN 'CD' THEN 'CREATE DISTINCT TYPE' WHEN 'CF' THEN 'CREATE FUNCTION' WHEN 'CL' THEN 'CLOSE' WHEN 'CO' THEN 'COMMENT ON' WHEN 'CM' THEN 'COMMIT' WHEN 'CN' THEN 'CONNECT' WHEN 'CC' THEN 'CREATE COLLECTION' WHEN 'CI' THEN 'CREATE INDEX' WHEN 'CP' THEN 'CREATE PROCEDURE' WHEN 'CS' THEN 'CREATE ALIAS' WHEN 'CT' THEN 'CREATE TABLE' WHEN 'CV' THEN 'CREATE VIEW' WHEN 'DC' THEN 'DECLARE CURSOR' WHEN 'DD' THEN 'DELETE...CLOSE' WHEN 'UD' THEN 'UPDATE..FETCH' WHEN 'UP' THEN 'UPDATE' WHEN 'UU' THEN 'UPDATE.FETCH' WHEN 'OP' THEN 'OPEN' WHEN 'OU' THEN 'OPEN.FETCH' WHEN 'DI' THEN 'DISCONNECT' WHEN 'DK' THEN 'DELETE.. varchar(qqhvar.DELETE' WHEN 'FE' THEN 'FETCH' WHEN 'FF' THEN 'FETCH.QQSTTX...UPDATE' WHEN 'EX' THEN 'EXECUTE' WHEN 'EI' THEN 'EXECUTE IMMEDIATE' WHEN 'FC' THEN 'FETCH..UPDATE' WHEN 'PR' THEN 'PREPARE' WHEN 'RE' THEN 'RELEASE' WHEN 'RO' THEN 'ROLLBACK' WHEN 'RT' THEN 'RENAME' WHEN 'RV' THEN 'REVOKE' WHEN 'SC' THEN 'SET CONNECTION' WHEN 'SI' THEN 'SELECT INTO' WHEN 'SK' THEN 'SELECT INTO' WHEN 'SP' THEN 'SET PATH' WHEN 'SR' THEN 'SET RESULTS' WHEN 'ST' THEN 'SET TRANSACTION' WHEN 'SV' THEN 'SET VARIABLE' WHEN 'UC' THEN 'UPDATE. QQCNT as "Statement Usage Count "...20000) as "Statement Text"..UPDATE' ELSE QQSTOP END as "Operation"....CLOSE' WHEN 'OD' THEN 'OPEN........FETCH' WHEN 'FL' THEN 'FREE LOCATOR' WHEN 'FU' THEN 'FETCH.500) as "Host Variable Values". /* Opens */ 540 DB2 UDB for AS/400 SQL Programming V4R4 ...DELETE' WHEN 'OF' THEN 'OPEN.DELETE' WHEN 'DE' THEN 'DESCRIBE' WHEN 'DF' THEN 'DELETE.DELETE' WHEN 'UF' THEN 'UPDATE.CLOSE' WHEN 'DL' THEN 'DELETE' WHEN 'DP' THEN 'DECLARE PROCEDURE' WHEN 'DR' THEN 'DROP' WHEN 'DT' THEN 'DESCRIBE TABLE' WHEN 'DU' THEN 'DELETE.CLOSE' WHEN 'FD' THEN 'FETCH... QQCSO as "Sort Count". QQCAPR as "Access Plan Rebuild Count". /* Job-user-program identification */ QQJOB as "Job". /* Index Information */ QQCIU as "Index Use Count". Monitoring and Optimizing Query Performance Tools 541 . Chapter 26. /* Copy of data */ QQCTF as "Temporary Table Count". as "Average Result Size".| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | QQFULO as "Full Opens". /* Row QQTOTR QQRROW QQARSS Sizes */ as "Table Rows". /* Implementation */ CASE QQODPI WHEN 'R' THEN 'Reusable' WHEN 'N' THEN 'Non-Reusable' ELSE QQODPI END as "ODP Implementation". CASE QQDACV WHEN 'N' THEN NULL WHEN '0' THEN NULL WHEN '1' THEN 'Different Lengths' WHEN '2' THEN 'Different Numeric Types' WHEN '3' THEN 'C NUL-terminated Variable' WHEN '4' THEN 'Varying Length Fixed Length' WHEN '5' THEN 'CCSID Conversion' WHEN '6' THEN 'DRDA Mapping Required' WHEN '7' THEN 'Datetime Column' WHEN '8' THEN 'Too Many Host Variables' WHEN '9' THEN 'Target Table Is Not A SQL Table' ELSE QQDACV END as "Data Conversion". QQPSUO as "Pseudo Opens". QQCIA as "Index Advised Count". QQCTS as "Table Scan Count". /* Access Plan Rebuild */ QQAPRT as "Last Access Plan Rebuilt". as "Result Rows". CASE QQHVI WHEN 'I' THEN 'ISV' WHEN 'V' THEN 'V2' WHEN 'U' THEN 'UP' ELSE QQHVI END as "Host Variable Implementation". QQCIC as "Index Create Count". CASE QQAPR WHEN 'A1' THEN WHEN 'A2' THEN WHEN 'A3' THEN WHEN 'A4' THEN WHEN 'A5' THEN WHEN 'A6' THEN WHEN 'A7' THEN WHEN 'A8' THEN WHEN 'A9' THEN WHEN 'AA' THEN ELSE QQAPR END as "Access 'Different File Or Member' 'Reusable Plan to Non-Reusable Plan Change' 'Non-Reusable To Reusable Plan Change' 'More Than Ten Percent Change In Number Of Rows' 'New Access Path Found' 'Access Path No Longer Found Or Valid' 'System Programming Change' 'Different CCSID' 'Different Date Or Time Format' 'Different Sort Sequence Table' Plan Rebuild Reason". QQCNAM as "Cursor". This join key field does not replace all of the detail fields that are still required to identify the specific information about the individual steps of a query. whether executed or not Information on host variable implementation Displayed only for those queries which are executed Limited information on the implementation of host variables Displayed only for those queries which are executed All information on host variables. QQSNAM as "Statement Name" FROM <> a left join <> b on a. and values Displayed only for those queries which are executed All information on host variables.qqkey=c.Materialized Query Definition Template Subselect Number (View w/ Subquery) Use these fields when the monitored query contains a subquery. or a view operation. "Job Number". Comparison table of query optimization tools PRTSQLINF STRDBG/CHGQRYA STRDBMON Only available when the query is run Memory-Based Monitor Onlly available when the query is run Available without Only available when running query (after the query is run access plan has been created) Displayed for all queries in SQL program. "Thread ID".qqkey=b.| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | QQUSER QQJNUM QQTHID QQPLIB QQPNAM as as as as as "Job User". The join key field contains a unique identifier that allows all of the information for this query to be received from each of the physical files. "Program Library". union. This field replaces the job (QQJOB) and unique query counters (QQCNT) that the existing database monitor used. Use these fields to identify which records belong to each step of the query process: v QQQDTN . The system uses these fields to separate the information for each QDT while still allowing each QDT to be identified as belonging to this original query (QQKEY).qqkey ORDER BY "Maximum Runtime" DESC Record Identification A new join key field has been generated (QQKEY) to ease joining multiple physical files together.Materialized Query Definition Tempalte Number (View) v QQMATL . /* Statement attributes */ QQUDEF as "User Defined Field". and values 542 DB2 UDB for AS/400 SQL Programming V4R4 . implementation. implementation.Query Definition Template Number v QQQDTL . All query types can generate multiple QDT’s to satisfy the original query request. "Program".qqkey left join <> c on a.Query Definition Template Subselect Number (Subquery) v QQMATN . The Query Definition templte (QDT) Number or the Subselect Number identifies information about each detailed step. It can be used with all DB2 UDB for AS/400 query interfaces and is not limited to use with SQL queries. Chapter 26. SQL. users (OPNQRYF.PRTSQLINF STRDBG/CHGQRYA STRDBMON Available to all query users (OPNQRYF. QUERY/400) Performance records written to database file Memory-Based Monitor Available only to SQL interfaces Available only to SQL Available to all query users with programs. The types of attributes that you can modify include: v Predictive Query Governor v Query Parallelism v Asynchronous Job v Apply CHGQRYA to remote Before the system intitiates a query. The query options file QAQQINI is used to set the attributes used by the Query Optimizer. If the query is cancelled. debug messages will be written to the joblog. Monitoring and Optimizing Query Performance Tools 543 . or service SQL. the system checks the query time limit against the estimated elapsed query time. The system also uses a time limit of zero to optimize performance on queries without having to run through several iterations. packages. Using the DB2 UDB for AS/400 Predictive Query Governor” on page 391 can stop the initiation of a query if the query’s estimated or predicted runtime (elapsed execution time) is excessive. The governor acts before a query is run instead of while a query is run. For each query that is run the query option values are retrieved from the QAQQINI file in the library specified on the QRYOPTLIB parameter of the CHGQRYA CL command and used to optimize or implement the query. Query Options File QAQQINI The query options file QAQQINI support provides the ability to dynamically modify or override the environment in which queries are executed through the CHGQRYA command and the QAQQINI file. The “Chapter 23. The governor can be used in any interactive or batch job on the AS/400. QUERY/400) programs Messages printed to spool file Messages displayed in job log Performance information collected in memory and then written to database file Repeated query requests are summarized Easier to tie messages to query with subqueries or unions Difficult to tie messages to query with subqueries or unions Uniquely identifies every query Change query attributes | | | | | | | | | | | | | | | | | | | You can modify different types of attributes of queries that you will execute during a certain job with the CHGQRYA command. You can check the inquiry message CPA4259 for the predicted runtime and for what operations the query will perform. To create your own QAQQINI file use the CRTDUPOBJ CL command to create a copy of the QAQQINI file into the library which will be specified on the CHGQRYA QRYOPTLIB parameter. in QSYS. The QAQQINI file in QSYS is to be used as a template when creating all user specified QAQQINI files. then the library QUSRSYS is searched for the existence of the QAQQINI file. The query options file will be retrieved from the library specified on the QRYOPTLIB parameter for each query and remains in effect for the duration of the job or user session. no attributes will be modified.| | | | | | | | | | | | | | | | | Environmental attributes that you can modify through the QAQQINI file include: v APPLY_REMOTE v ASYNC_JOB_USAGE v FORCE_ORDER_JOIN v MESSAGES_DEBUG v v v v v OPTIMIZE_STATISTIC_LIMITATION PARALLEL_DEGREE PARAMETER_MARKER_CONVERSION QUERY_TIME_LIMIT UDF_TIME_OUT Specifying the QAQQINI file CHGQRYA (Change Query Attributes) CL command has a parameter QRYOPTLIB (query options library) which allows the user to specify which library currently contains or will contain the query options file QAQQINI. Creating the QAQQINI Query Options File | | | | | | | | | | | | | | ach system is shipped with a QAQQINI template file in library QSYS. If no library is specified for this parameter. QAQQINI Query Options File Format Query Options File: R QAQQINI QQPARM 256A UNIQUE TEXT('Query options + file') VARLEN(10) + 544 DB2 UDB for AS/400 SQL Programming V4R4 . If a query options file is not found for a query. Note: It is recommended that the file QAQQINI. The initial value of the QRYOPTLIB parameter for a job is QUSRSYS. The filename must remain QAQQINI. or until the QRYOPTLIB parameter is changed by the CHGQRYA command. not be modified. for example: CRTDUPOBJ OBJ(QAQQINI) FROMLIB(QSYS) OBJTYPE(*FILE) TOLIB(MYLIB) DATA(*YES) Because system-supplied triggers are attached to the QAQQINI file in QSYS it is imperative that the only means of copying the QAQQINI file is through the CRTDUPOBJ CL command. This is the original template that is to be duplicated into QUSRSYS or a user specified library for use. a QAQQINI file has already been created in library MyLib.'*NOMAX'.QQVAL 256A QQTEXT 1000G K QQPARM TEXT('Query + option parameter') + COLHDG('Parameter') VARLEN(10) + TEXT('Query option + parameter value') + COLHDG('Parameter Value') VARLEN(100) + TEXT('Query + option text') + ALWNULL + COLHDG('Query Option' + 'Text') + CCSID(13488) + DFT(*NULL) | | The QAQQINI file shipped in the library QSYS has been pre-populated with the following records: Table 71. To update an existing record in MyLib/QAQQINI use the UPDATE SQL statment. This example removes the QUERY_TIME_LIMIT record from the QAQQINI file: DELETE FROM MyLib/QAQQINI WHERE QQPARM='QUERY_TIME_LIMIT' To insert a new record into MyLib/QAQQINI use the INSERT SQL statement. or DELETE SQL statements. This example sets MESSAGES_DEBUG = *YES so that the query optimizer will print out the optimizer debug messages: UPDATE MyLib/QAQQINI SET QQVAL='*YES' WHERE QQPARM='MESSAGES_DEBUG' To delete an existing record in MyLib/QAQQINI use the DELETE SQL statement. QAQQINI File Records.'New time limit set by DBAdmin') Chapter 26. Monitoring and Optimizing Query Performance Tools 545 . Description QQPARM APPLY_REMOTE ASYNC_JOB_USAGE FORCE_JOIN_ORDER MESSAGES_DEBUG OPTIMIZE_STATISTIC_LIMITATION PARALLEL_DEGREE PARAMETER_MARKER_CONVERSION QUERY_TIME_LIMIT UDF_TIME_OUT QQVAL *DEFAULT *DEFAULT *DEFAULT *DEFAULT *DEFAULT *DEFAULT *DEFAULT *DEFAULT *DEFAULT Setting the Options within the Query Options File The QAQQINI file query options can be modified with the INSERT. This example adds the QUERY_TIME_LIMIT record with a value of *NOMAX to the QAQQINI file: INSERT INTO MyLib/QAQQINI VALUES('QUERY_TIME_LIMIT'. For the following examples. UPDATE. rebuilds. Specifies a limit for database queries allowed to be started. APPLY_REMOTE *YES 546 DB2 UDB for AS/400 SQL Programming V4R4 .QAQQINI Query Options | | The tables below summarize the query options that can be specified on the QAQQINI command: Parameter value APPLY_REMOTE Description Specifies. if CHGQRYA was used for this job. ASYNC_JOB_USAGE FORCE_JOIN_ORDER MESSAGES_DEBUG OPTIMIZE_STATISTIC_LIMITATION PARALLEL_DEGREE PARAMETER_MARKER_CONVERSION QUERY_TIME_LIMIT UDF_TIME_OUT Table 72. The remote jobs will use the attributes associated to them on their systems. the system value on the remote system is used for the remote job. Only applies to queries involving distributed files. Specifies whether the Query Optimizer is not allowed to reorder files during implementation of a join query. This option will disallow database queries with literals to be implemented as parameter markers. This option issues all the Query Optimizer debug messages that would normally be issued if the job was in debug mode. This option requires that. For attributes where *SYSVAL is specified. The query attributes for the job are applied to the remote jobs used in processing database queries involving distributed files. Specifies the circumstances in which statistics gathering is allowed for query optimization. based on the estimated number of elapsed seconds that the query requires to process. Specifies the circumstances in which asynchronous (temp writer) jobs can be used to help process database queries in the job. for database queries involving distributed files. The CHGQRYA attributes for the job are not applied to the remote jobs. Specifies the parallel processing option that can be used when running database queries and database file keyed access path builds. the remote jobs must have authority to use the CHGQRYA command. Specifies. and maintenance in the job. the number of seconds that the database should wait for a UDF to finish. Query Options Specified on QAQQINI Command Parameter Value *DEFAULT *NO Description The default value is set to *NO. for database queries involving UDFs. whether or not the CHGQRYA attributes are applied to the jobs on the remote system associated with this job. in number of records. Specifies the largest table size. Therefore. The default is set to *NO. the optimizer will not gather statistics and will use default values. Asynchronous jobs may be used for database queries that involve distributed files. The join will occur in the order in which the files were specified in the query. For tables with more records than the specified value. for queries involving distributed files. Default statistics will be used for optimization. ASYNC_JOB_USAGE *DIST *ANY *NONE *DEFAULT *NO FORCE_JOIN_ORDER *YES *DEFAULT MESSAGES_DEBUG *NO *YES *DEFAULT *NO OPTIMIZE_STATISTIC_ LIMITATION *PERCENTAGE integer value *MAX_NUMBER_ OF_RECORDS_ ALLOWED integer value Chapter 26. Asynchronous jobs may be used for database queries that involve only files local to the system where the database queries are being run.Table 72.) Specifies the maximum percentage of the index that will be searched while gathering statistics. (Use this option sparingly. No index statistics will be gathered by the query optimizer. this option allows the communications required to be asynchronous. Issue all Query Optimizer debug messages The amount of time spent in statistics gathering is determined by the query optimizer. Valid values for integer value are 1 to 99. In addition. The default is set to *NO. No debug messages are to be displayed. Monitoring and Optimizing Query Performance Tools 547 . Allow the optimizer to re-order join files. This allows each system involved in the query of the distributed files to run its portion of the query at the same time (in parallel) as the other systems. for which gathering statistics is allowed. No asynchronous jobs are allowed to be used for database query processing. Asynchronous jobs may be used for any database query. Do not allow the query optimizer to re-order join files as part of its optimization process. all processing for queries involving distributed files occurs synchronously. Query Options Specified on QAQQINI Command (continued) Parameter Value *DEFAULT *LOCAL Description The default value is set to *LOCAL. In addition. no inter-system parallel processing will occur. Constants can be implemented as parameter markers. The query optimizer chooses an implementation that minimizes elapsed time based on the job has a share of the memory in the pool. Specifies the maximum value that is checked against the estimated number of elapsed seconds required to run a query. If the estimated elapsed seconds is greater than this value. this job has a share of the amount of active memory available in the pool in which the job is run. QQRYTIMLMT. The processing option used is set to the current value of the system value. *OPTIMIZE PARALLEL_DEGREE *MAX *NONE *DEFAULT PARAMETER_MARKER_ CONVERSION *NO *YES *DEFAULT *SYSVAL *NOMAX QUERY_TIME_LIMIT integer value 548 DB2 UDB for AS/400 SQL Programming V4R4 . 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 or database file keyed access path build. or maintenance. QQRYDEGREE. or maintenance. SMP parallel processing is used only if the system feature. Valid values range from 0 through 2147352578. The query optimizer chooses to use either I/O or SMP parallel processing to process the query. rebuild. rebuild. rebuild. and whether the expected elapsed time for the query or database file keyed access path build or rebuild is limited by CPU processing or I/O resources. The default value is set to *SYSVAL. the query is not started. SMP parallel processing will only be used if the system feature. Query Options Specified on QAQQINI Command (continued) Parameter Value *DEFAULT *SYSVAL *IO Description The default value is set to *SYSVAL. The default value is set to *NO.Table 72. The query time limit for this job will be obtained from the system value. SMP parallel processing is not allowed. There is no maximum number of estimated elapsed seconds. No parallel processing is allowed for database query processing or database file keyed access path build. The query optimizer can choose to use any number of tasks for either I/O or SMP parallel processing to process the query or database file keyed access path build. DB2 Symmetric Multiprocessing for OS/400. DB2 Symmetric Multiprocessing for OS/400. Use of parallel processing and the number of tasks used is determined with respect to the number of processors available in the system. or maintenance. Constants cannot be implemented as parameter markers. Any number of tasks can be used when the database query optimizer chooses to use I/O parallel processing for queries. is installed. is installed. the maximum wait time will be used by the database. or UPDATE operation). This provides the system administrator with an additional security mechanism. the following SQL0443 diagnostic message will be issued: Trigger program or external routine detected an error. Minimum value is 1 and maximum value is system defined. DELETE. is always used by the query optimizer.Table 72. A trigger cannot be removed from or added to the file QAQQINI. If an error occurs on the update of the QAQQINI file (an INSERT. This will prevent users from changing the data in the file. QAQQINI File System Supplied Triggers The query options file QAQQINI file uses a system-supplied trigger program in order to process any changes made to the file. QAQQINI Query Options File Authority Requirements QAQQINI is shippped with a *PUBLIC *USE authority. The default is 30 seconds. or updating the query options. Monitoring and Optimizing Query Performance Tools 549 . To prevent the query options from being retrieved from a particular library the system administrator can revoke authority to the CHGQRYA CL command. The query options file. When the QAQQINI file resides in the library QUSRSYS the query options will effect all of the query users on the system. the query options will effect all of the querys run for that user’s job. When the QAQQINI file resides in a user library. The maximum amount of time that the database will wait for the UDF to finish. To prevent anyone from inserting. deleting. but not change it. Chapter 26. It is recommended that only the system or database administrator have *CHANGE authority to the QAQQINI query options file. This is true even if the user has no authority to the query options library and file. which resides in the library specified on the CHGQRYA CL command QRYOPTLIB parameter. Query Options Specified on QAQQINI Command (continued) Parameter Value *DEFAULT *MAX UDF_TIME_OUT integer value Description The amount of time to wait is determined by the database. This allows users to view the query options file. Specify the number of seconds that the database should wait for a UDF to finish. specified on the CHGQRYA CL command option QRYOPTLIB. the system administrator should remove update authority from *PUBLIC to the file. If the value given exceeds the database maximum wait time. 550 DB2 UDB for AS/400 SQL Programming V4R4 . 1999 551 . Techniques are provided to help you do the following tasks: v Page through retrieved data v Retrieve data in reverse order v Establish position at the end of a table v Add data to the end of a table v Update data as it is retrieved from a table v Update data previously retrieved v Change the table definition Paging through Retrieved Data When a program retrieves data from the database. Several options that can be used to page through the data are listed in 56. one in ascending order and one in descending order. If both statements are required in the same program. 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. simply specify that the order is descending.Chapter 27. based on the scroll option specified on the FETCH statement. Establishing Position at the End of a Table For a scrollable cursor. 1997. then the program can page anywhere in the file. the FETCH statement allows the program to page forward through the data. the end of the table can be determined by the following: FETCH AFTER FROM C1 Once the cursor is positioned at the end of the table. But that is guaranteed only if the first statement specifies a unique ordering. then the following statement specifies a unique ordering of rows: SELECT * FROM DEPARTMENT WHERE LOCATION = 'MINNESOTA' ORDER BY DEPTNO To retrieve the same rows in reverse order. © Copyright IBM Corp. If you are using a scrollable cursor. Solving Common Database Problems This chapter describes techniques for solving some common database problems. it might be useful to have two indexes on the DEPTNO column. This allows the program to retrieve the data more than once. Retrieving in Reverse Order If there is only one row for each value of DEPTNO. the program can use the PRIOR or RELATIVE scroll options to position and fetch data starting from the end of the table. . If so. if the WHERE CURRENT OF clause is specified on the UPDATE statement. the last row in the block is updated. If a FOR UPDATE OF. . To get the effect of adding data to the end of a table. Therefore. Then use the cursor-controlled UPDATE statement. If a multiple-row FETCH statement has been specified and run. EXEC SQL WHENEVER NOT FOUND GO TO CLOSE-THISEMP END-EXEC. Consider the following example: Table 73. when you retrieve data from the table. DEPTINFO and IND-ARRAY are declared in the program as a host structure array and an indicator array. EXEC SQL FETCH NEXT FROM THISEMP FOR 5 ROWS INTO :DEPTINFO :IND-ARRAY END-EXEC.. use FOR UPDATE OF followed by a list of columns that may be updated. Comments 552 DB2 UDB for AS/400 SQL Programming V4R4 . EXEC SQL FETCH RELATIVE :NUMBACK FROM THISEMP END-EXEC.. use an ORDER BY clause naming that column. The WHERE CURRENT OF clause names the cursor that points to the row you want to update. Updating Data as It Is Retrieved from a Table You can update rows of data as you retrieve them. EXEC SQL OPEN THISEMP END-EXEC. On the select-statement. determine if any employees in department D11 receive a bonus less than $500. Then the UPDATE WHERE CURRENT OF can be specified. BONUS FROM CORPDATA. include a sequence number column in the table definition.EMPLOYEE WHERE WORKDEPT = ’D11’ FOR UPDATE OF BONUS END-EXEC. . WORKDEPT. the program must first position the cursor on that row.. positions to the record in the block to update by fetching in the reverse order.00. or a SCROLL clause without the DYNAMIC clause is not specified. an ORDER BY. a FOR READ ONLY. the cursor is positioned on the last row of the block.Adding Data to the End of a Table The order in which rows are returned to your program depends on the ORDER BY clause in the SQL statement. all columns can be updated.00. Then. Updating a Table Scrollable Cursor SQL Statement EXEC SQL DECLARE THISEMP DYNAMIC SCROLL CURSOR FOR SELECT EMPNO. If a row within the block must be updated. update that record to the new minimum of $500. 00 minimum. . But you can name columns in the FOR UPDATE OF clause that are not in the SELECT list. The first SELECT clause contains a column function. Updating Data Previously Retrieved You can page through and update data that had previously been retrieved by doing one of three things: Chapter 27. C FROM TABLE FOR UPDATE OF A. updates the bonus for the employee in department D11 that is under the new $500. (NUMBACK -(5 . CLOSE-THISEMP.EMPLOYEE SET BONUS = 500 WHERE CURRENT OF THISEMP END-EXEC. Comments .00.. EXEC SQL CLOSE THISEMP END-EXEC. branch back to fetch and process the next block of rows.NUMBACK . The outer subselect contains a HAVING clause. v v v v The outer subselect contains a GROUP BY clause. you cannot update columns that were not named in the FOR UPDATE OF clause. 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 first SELECT clause specifies the keyword DISTINCT. Solving Common Database Problems 553 . indexes on those columns are not used when you access the table.. . branch back to determine if any more employees in the block have a bonus under $500. Updating a Table (continued) Scrollable Cursor SQL Statement EXEC SQL UPDATE CORPDATA. v The first FROM clause identifies a read-only view. positions to the beginning of the same block that was already fetched and fetches the block again. v The SCROLL keyword is specified without DYNAMIC. B... . EXEC SQL FETCH RELATIVE :NUMBACK FROM THISEMP FOR 5 ROWS INTO :DEPTINFO :IND-ARRAY END-EXEC. v The select-statement contains a UNION or UNION ALL operator..Table 73.. v The select-statement includes a FOR READ ONLY clause.E Do not name more columns than you need in the FOR UPDATE OF clause. If a FOR UPDATE OF clause is specified... as in this example: SELECT A.1)) Restrictions You cannot use FOR UPDATE OF with a select-statement that includes any of these elements: v The first FROM clause identifies more than one table or view. using host variables in the WHERE clause.v Use the UPDATE statement with a WHERE clause that names all of the values in the row or specifies a unique key of the table. drop. which includes only the columns you want. Then. You can also dynamically create a view of the table. using the WHERE CURRENT OF clause on the UPDATE statement. See the CL Reference (Abridged) book for information on how to use the Change Physical File (CHGPF) CL command. and alter columns in a table using the SQL ALTER TABLE statement or the Change Physical File (CHGPF) CL command. Changing the Table Definition You can add. the row can be changed to the appropriate value. See the DB2 UDB for AS/400 SQL Reference book for information on how to use the SQL ALTER TABLE statement. and run the same statement many times with different values of the variables to update different rows. 554 DB2 UDB for AS/400 SQL Programming V4R4 . v For a scrollable cursor. the program can use the appropriate scroll options to retrieve the row that had previously been fetched. in the order you want. You can code one statement. In addition. However. see the Distributed Database Programming book. DB2 UDB for AS/400) or of different types (DB2 for OS/390.Chapter 28. Distributed Relational Database Function A distributed relational database consists of a set of SQL objects that are spread across interconnected computer systems. DB2 UDB for AS/400 can invoke exit programs to allow access to data on other database management systems which do not support DRDA. The database managers communicate and cooperate with each other in a way that allows a given database manager access to run SQL statements on a relational database on another system. The application server is the local or remote database to which an application requester is connected. 1997. DB2 UDB for AS/400 supports DUW over APPC only. 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. DB2 UDB for AS/400 supports RUW over either APPC or TCP/IP. The application requester supports the application side of a connection. or non-IBM database management systems which support DRDA). DB2 UDB for AS/400 Distributed Relational Database Support The DB2 UDB Query Manager and SQL Development Kit licensed program supports interactive access to distributed databases with the following SQL statements: v CONNECT v SET CONNECTION v DISCONNECT v RELEASE v DROP PACKAGE v GRANT PACKAGE v REVOKE PACKAGE For detailed descriptions of these statements. © Copyright IBM Corp. a single SQL statement can only refer to objects located at a single application server. 1999 555 . DB2 UDB for AS/400 provides support for Distributed Relational Database Architecture (DRDA) to allow an application requester to communicate with application servers. These relational databases can be of the same type (for example. DB2 UDB 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. Each relational database has a relational database manager to manage the tables in its environment. DB2 for VM. These exit programs are called application requester driver (ARD) programs. DB2 Universal Database (UDB). For comprehensive information about distributed relational databases. see the DB2 UDB for AS/400 SQL Reference book. Instructions are included in the member as comments. v Load data into the tables at the local and remote locations. Syntax and parameter definitions for the CRTSQLPKG and CRTSQLxxx commands are provided in Appendix D. and views. and run the program to update the location column in the department table. v Precompile. To use these files and members. v Precompile and compile programs. v Create SQL packages at the remote location for the application programs. compile. DB2 UDB for AS/400 Distributed Relational Database Example Program A remote unit of work relational database sample program has been shipped with the SQL product. v Precompile. and run programs to create distributed sample application collections. specify the following command on the command line: ========> ADDLIBLE QSQSAMP 556 DB2 UDB for AS/400 SQL Programming V4R4 . The SETUP batch job allows you to customize the example to do the following: v Create the QSQSAMP library at the local and remote locations. indexes.Additional support is provided by the development kit through parameters on the SQL precompiler commands: Create SQL ILE C Object (CRTSQLCI) command Create SQL COBOL Program (CRTSQLCBL) command Create SQL ILE COBOL Object (CRTSQLCBLI) command Create SQL PL/I Program (CRTSQLPLI) command Create SQL RPG Program (CRTSQLRPG) command Create SQL ILE RPG Object (CRTSQLRPGI) command For more information on the SQL precompiler commands. v Create application panels at the local location. tables. DB2 UDB for AS/400 CL Command Descriptions. you need to run the SETUP batch job located in the file QSQL/QSQSAMP. v Set up relational database directory entries at the local and remote locations. Before running the SETUP. specify the following command on the AS/400 command line: ========> SBMDBJOB QSQL/QSQSAMP SETUP Wait for the batch job to complete. There are several files and members within the QSQL library to help you set up an environment that will run a distributed DB2 UDB for AS/400 sample program. you may need to edit the SETUP member of the QSQL/QSQSAMP file. To run the SETUP. The create SQL Package (CRTSQLPKG) command lets you create an SQL package from an SQL program that was created as a distributed program. compile. To use the sample program. see the topic “Chapter 18. Preparing and Running a Program with SQL Statements” on page 333. 1982. An SQL package is not created unless the privileges held by the authorization ID associated with the creation of the SQL package includes appropriate authority for creating a package on the remote system (the application server)... the SQL package will not be created..To call the first display that allows you to customize the sample program..... ========> CALL QSQ8HC3 The following display appears. The CRTSQLPKG can be used to create a package when the package was not created at precompile time or if the package is needed at an RDB other than the one specified on the precompile command. If the compile is unsuccessful or the compile only creates the module object.. The SQL package will be created on the system specified by the RDB parameter. v Using the CRTSQLPKG command.... The Delete SQL Package (DLTSQLPKG) command allows you to delete an SQL package on the local system.: ________________ (BLANK IMPLIES LOCAL LOCATION) _______________________________ Bottom F3=Exit (C) COPYRIGHT IBM CORP......... An SQL package can be created when: v The RDB parameter is specified on the CRTSQLxxx command and the program object is successfully created. DB2 UDB for AS/400 CL Command Descriptions.. Chapter 28..: D (DISPLAY) OBJECT. (OS/400 object type is *SQLPKG... From this display..... 1991 SQL Package Support The OS/400 program supports an object called an SQL package.....: __ DI (DEPARTMENT ID) DN (DEPARTMENT NAME) EI (EMPLOYEE ID) MI (MANAGER ID) EN (EMPLOYEE NAME) LOCATION. On AS/400 systems. you can customize your database sample program. DB2 for OS/400 ORGANIZATION APPLICATION ACTION. To run the program. Distributed Relational Database Function 557 .: DS (DEPT STRUCTURE) _ __ A (ADD) U (UPDATE) DE (DEPARTMENT) E (ERASE) EM (EMPLOYEE) MN (MANAGER NAME) SEARCH CRITERIA. the authorization ID must include EXECUTE privileges on the SQL package.... specify the following command on the command line. The syntax for the Create SQL Package (CRTSQLPKG) command is shown in Appendix D.) The SQL package contains the control structures and access plans necessary to process SQL statements on the application server when running a distributed program.....: DATA. the EXECUTE privilege includes system authority of *OBJOPR and *EXECUTE.... For more information. undefined or unusable host variables or constants that are not valid would generate a message severity greater than 30. These statements are sent to the remote system during the creation of the SQL package. If a message is issued with a severity level of greater than 30. Creating a Package on a non-DB2 UDB for AS/400 When you create a program and SQL package for a non-DB2 UDB for AS/400. When you are creating a package for a DB2 Universal Database. The run-time support will return a SQLCODE of -84 or -525 when the statement cannot be run on the current application server. see the appendix that contains the section ″Considerations for Using Distributed Relational Database″ in the DB2 UDB for AS/400 SQL Reference. If the RDB parameter specifies a system that is not a DB2 UDB for AS/400 system. blocked INSERT. For example. then the following options should not be used on the CRTSQLxxx command: v COMMIT(*NONE) v OPTION(*SYS) v DATFMT(*MDY) v DATFMT(*DMY) v DATFMT(*JUL) v DATFMT(*YMD) v DATFMT(*JOB) v DYNUSRPRF(*OWNER) v TIMFMT(*HMS) if TIMSEP(*BLANK) or TIMSEP(’. Considerations for Creating an SQL Package There are many considerations to think about when you are creating an SQL package. The precompiler will continue to issue diagnostic messages for statements it does not understand. Some of these considerations are listed below. SC41-5612-02 book. CRTSQLPKG Authorization When creating an SQL package on an AS/400 system the authorization ID used must have *USE authority to the CRTSQLPKG command. The program will be created unless a message with a severity level of greater than 30 is issued. For example.’) is specified v SRTSEQ(*JOBRUN) 558 DB2 UDB for AS/400 SQL Programming V4R4 . except the SET TRANSACTION statement. you must set the GENLVL parameter to a value less than 20. Programs compiled using DB2 UDB for AS/400 that refer to a system that is not DB2 UDB for AS/400 can use executable SQL statements supported by that remote system. multiple-row FETCH. and try to use SQL statements that are unique to that relational database. and scrollable cursor support are allowed only in distributed programs where both the application requester and application server are OS/400 at Version 2 Release 2 or later. the statement is probably not valid for any relational database. The precompiler listing should be checked for unexpected messages when running with a GENLVL greater than 10.Valid SQL Statements in an SQL Package Programs that connect to another AS/400 can use any of the SQL statements as described in the DB2 UDB for AS/400 SQL Reference book. the CRTSQLxxx GENLVL parameter should be set to 30. Distributed Relational Database Function 559 . In addition. When this occurs. the SQL statements are checked to determine which release can support the function. then the restore level of the package will be Version 3 Release 1. a program that contains only the SQL statement DESCRIBE TABLE will generate message SQL5041 during SQL package creation. This situation occurs when the program contains only SQL statements that do not require an SQL package to run. The SQL statements that do not require an SQL package are: v v v v v v v DESCRIBE TABLE COMMIT ROLLBACK CONNECT SET CONNECTION DISCONNECT RELEASE Package Object Type SQL packages are always created as non-ILE objects and always run in the default activation group. an empty package is created.v SRTSEQ(*LANGIDUNQ) v SRTSEQ(*LANGIDSHR) v SRTSEQ(library-name/table-name) Note: When connecting to a DB2 Universal Database application server. along with a list of the host variables for that statement. This release is set as the restore level of the package. For example. The create SQL package function passes this statement to the application server. if 65535 is used. because FOREIGN KEY constraints were not supported prior to this release. TGTRLS message are suppressed when the TGTRLS parameter is *CURRENT. Chapter 28. the SQL statement is placed into the associated space of the program. when the RDB parameter is specified. the host variables of the source statement are replaced with an ’H’. Target Release (TGTRLS) While creating the package. you might try to create an SQL package but the SQL package will not be created and the program will still run. if the package contains a CREATE TABLE statement which adds a FOREIGN KEY constraint to the table. During the precompile of the SQL program. SQL Statement Size The create SQL package function may not be able to handle the same size SQL statement that the precompiler can process. For example. 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. each token is separated by a blank. Statements that do not require a Package In some cases. The addition of the blanks between the tokens and the replacement of host variables may cause the statement to exceed the maximum SQL statement size (SQL0101 reason 5). Assume the program is on the AS/400 system and the application server is another AS/400 system.2 resources registered that are not associated with DRDA or DDM. If it is the name of the local system. SQL maintains a list of addresses for SQL packages that are used by each session. It is possible for the program and SQL package to appear to be uncoordinated. Unit of Work Because package creation implicitly performs a commit or rollback. but the package information is saved in the *PGM object.) 560 DB2 UDB for AS/400 SQL Programming V4R4 . To avoid locating the SQL package on each call. If you specify *LOCAL for the RDB parameter. The address to the SQL package in session A is still valid. v There are no API resources registered. then the package creation will fail. Labels You can use the LABEL ON statement to create a description for the SQL package. an *SQLPKG object is not created. Creating Packages Locally The name specified on the RDB parameter can be the name of the local system. Package Creation Connection The type of connection done for the package creation is based on the type of connect requested using the RDBCNNMTH parameter. the SQL package is not used.ILE programs and service programs ILE programs and service programs that bind several modules containing SQL statements must have a separate SQL package for each module. When session B re-creates the SQL package. When you run the program with a connection to the local system. the old SQL package is moved to the QRPLOBJ library. v There are no local or DDM files open using commitment control and no closed local or DDM files with pending changes. (This situation can be avoided by creating the program and SQL package from the session that is running the program. The consistency tokens must match or the package cannot be used. 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. If the connection is read-only. The program is running in session A and it is recreated in session B (where the SQL package is also recreated). the commit definition must be at a unit of work boundary before the package creation is attempted. the SQL package will be created on the local system. The SQL package can be saved (SAVOBJ command) and then restored (RSTOBJ command) to another AS/400 system. If RDBCNNMTH(*DUW) was specified. commitment control is used and the connection may be a read-only connection. v There are no LU 6. 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. The next call to the program in session A could result in a consistency token error. or by submitting a remote command to delete the old SQL package before creating the program. Before requesting that the remote system create an SQL package. (or running a program with embedded SQL statements) the job is interrupted before the command has completed. and the text of the SQL package from the CCSID of the job to CCSID 500.″. view. If you created a program that referenced the table whose name was ″a¬b|c. SQL and Recursion If you invoke SQL from an attention key program while you are already precompiling. v The code point for ¬ in CCSID 37 is x’5F’ while in CCSID 500 it is x’BA’. Recursion would occur if while one of the commands is running. SQL package name. v Save program ″a¬b|c″ on system A. If you use delimited names or the three national extenders. the term ’connection’ was not ambiguous. That is. Distributed Relational Database Function 561 . the job CCSID value on the AS/400 cannot be set to 65535. library. CCSID Considerations for SQL If you are running a distributed application and one of your systems is not an AS/400 system. and another SQL function is started. They will produce unpredictable results if recursion is attempted. collection. or SQL package names. the name resolution functions may possibly fail in a future release. and dollar sign ($) characters should not be used in SQL object names. pound sign (#). Conversion of names does not occur between systems with different CCSIDs. STRSQL commands and the SQL run-time environment are not recursive. Their code points depend on the CCSID used. CRTSQLPKG. and ended when a DISCONNECT was done or a RELEASE ALL followed by a successful COMMIT occurred. 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. index. Connection Management and Activation Groups Connections and conversations Prior to the use of TCP/IP by DRDA. It is recommended that delimited identifiers not be used for table. The CRTSQLxxx. the names are not converted from CCSID 500 to the job CCSID. RCLDDMCNV should then be used to end the network connections. a connection started at the time one did a CONNECT TO some RDB.To use the new SQL package. The at sign (@). Consider the following example with system A running with a CCSID of 37 and system B running with a CCSID of 500. v On system B the name would display ″a[b]c″. When the remote relational database is an AS/400 system. you will receive unpredictable results. then restore it to system B. You can either sign off the session and then sign on again. It referred to a connection from the SQL point of view. Call the program again. The Chapter 28. the program would not find the table. This is required by DRDA. you should end the connection with the remote system. v Create a program that creates a table with the name ″a¬b|c″ on system A. the application requester always converts the name specified on the RDB parameter. library name. END-EXEC.. SQL connections are managed at the activation group level. and whether the conversation was with an AS/400 or other type of system. and ’network’ connections which replace the term ’conversation’. Therefore. EXEC SQL CONNECT TO SYSB END-EXEC. by the more general term ’connection’. the word will be qualified by ’SQL’ or ’network’ to allow the reader to understand the intended meaning. With the advent of TCP/IP support by DRDA. use of the term ’conversation’ will be replaced. Source Code for PGM1: .. however.. This example is used to illustrate the interaction between activation groups. and commitment control. EXEC SQL SELECT . connection management. A similar concept exists. in this book. depending on the job’s DDMCNV attribute value.. Each activation group within a job manages its own connections and these connections are not shared across activation groups. unless the discussion is specifically about an APPC conversation. CALL PGM2.. It is not a recommended coding style. Source Code for PGM1 Command to create program and SQL package for PGM1: CRTSQLCBL PGM(PGM1) COMMIT(*NONE) RDB(SYSB) 562 DB2 UDB for AS/400 SQL Programming V4R4 . Where there would be the possibility of confusion between the two types of connections. TCP/IP terminology does not include the term ’conversation’... there are now two different types of connections about which the reader must be aware: SQL connections of the type described above... For programs that run in the default activation group. connections are still managed as they were prior to Version 2 Release 3. Figure 33.APPC conversation may or may not have been kept up. . The following is an example of an application that runs in multiple activation groups. EXEC SQL INSERT INTO TAB VALUES(:st1). EXEC SQL CLOSE C1.. Figure 34. EXEC SQL COMMIT. do { EXEC SQL FETCH C1 INTO :st1...Source Code for PGM2: . SET COL1 = COL1+10 WHERE CURRENT OF C1.. EXEC SQL DECLARE C1 CURSOR FOR SELECT .. Figure 35. EXEC SQL UPDATE ... } while SQLCODE == 0... Distributed Relational Database Function 563 .. PGM3(st1).. Source Code for PGM2 Command to create program and SQL package for PGM2: CRTSQLCI OBJ(PGM2) COMMIT(*CHG) RDB(SYSC) OBJTYPE(*PGM) Source Code for PGM3: . EXEC SQL COMMIT. EXEC SQL CONNECT TO SYSC. ... .. EXEC SQL OPEN C1. Source Code for PGM3 Commands to create program and SQL package for PGM3: CRTSQLCI OBJ(PGM3) COMMIT(*CHG) RDB(SYSD) OBJTYPE(*MODULE) CRTPGM PGM(PGM3) ACTGRP(APPGRP) CRTSQLPKG PGM(PGM3) RDB(SYSD) Chapter 28... The first SQL statement causes an implicit connect to relational database SYSD. but it runs in the activation group named APPGRP. the CRTPGM command is issued separately. The CRTPGM command is followed by a CRTSQLPKG command that creates the SQL package object on the SYSD relational database. the user has not explicitly started the job level commitment definition. PGM3 is also created using the CRTSQLCI command. and it runs in a system-named activation group. PGM1 is a non-ILE program created using the CRTSQLCBL command. PGM1 connects to relational database SYSB and runs a SELECT statement. The pending changes in the system-named 564 DB2 UDB for AS/400 SQL Programming V4R4 . PGM2 is running under commitment control. PGM2 is created using the CRTSQLCI command. and is not at a connectable state. is in the middle of a unit of work. 1. A row is inserted into table TAB located at relational database SYSD. PGM2 calls PGM3. 3. 4. 5. SQL implicitly starts commitment control. PGM2 opens the cursor and fetches and updates a row. This program runs in the default activation group. 6. Both connections are active. 2. The insert is then committed. Because PGM1 and PGM2 are in different activation groups. PGM1 is called and runs in the default activation group. which runs in activation group APPGRP. The INSERT statement is the first statement run in activation group APPGRP. the connection started by PGM2 in the system-named activation group does not disconnect the connection started by PGM1 in the default activation group.SYSA Job: SYSB (Remote) Call Job: Default Activation Group: SQL Package for PGM1 Default Activation Group: PGM1 Call Connect SYSC (Remote) System-Named Activation Group: Job: Default Activation Group: Connect PGM2 SQL Package for PGM2 Call Return Call Activation Group APPGRP: SYSD (Remote) Job: Connect Default Activation Group: SQLPackage for PGM3 PGM3 RV2W577-3 In this example. In this example. which runs in a system-named activation group. PGM2 does a connect to relational database SYSC. Because APPGRP is not the default value for the ACTGRP parameter. PGM1 then calls PGM2. SYSA Job: SYSB Job: Default ActivationGroup: Connect Job: System-Named Activation Group: Connect RV2W578-2 Implicit Connection Management for the Default Activation Group The application requester can implicitly connect to an application server. all the rows are processed by PGM2 and the unit of work associated with the system-named activation group is committed. An implicit connect was done on the first call to PGM3. It is not done on subsequent calls because the activation group did not end between calls to PGM3. each SQL connection has its own network connection and its own application server job. because commitment control was started by SQL with a commit scope of activation group. Finally. If activation groups are run with commitment control. Chapter 28. v SQL is not active in the default activation group. PGM2 fetches and updates another row. changes committed in one activation group do not commit changes in other activation groups unless the job-level commitment definition is used. Distributed Relational Database Function 565 . 7. PGM3 is called again to insert the row. 8.activation group are not committed. Multiple Connections to the Same Relational Database If different activation groups connect to the same relational database. PGM3 is then exited and control returns to PGM2. Implicit SQL connection occurs when the application requester detects the first SQL statement is being issued by the first active SQL program for the default activation group and the following items are true: v The SQL statement being issued is not a CONNECT statement with parameters. the implicit SQL connection is to the relational database specified on the RDB parameter. the implicit SQL connection is to the local relational database. the implicit SQL connection is made to the local relational database. Implicit Connection Management for Nondefault Activation Groups The application requester can implicitly connect to an application server. SQL will remain active for the default activation group until the job ends. This occurs when you issue a COMMIT or ROLLBACK command outside of an SQL program. activation group level commitment control is active. when the job level commitment definition is committed or rolled back. or an active SET TRANSACTION statement.For a distributed program. 566 DB2 UDB for AS/400 SQL Programming V4R4 . Implicit SQL connection occurs when the application requester detects that the first SQL statement issued for the activation group is not a CONNECT statement with parameters. If there are pending changes. within one or more units of work. If the job level commitment definition is active and not at a unit of work boundary. 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. protected connections. run any number of static or dynamic SQL statements that refer to objects on the application server. if commitment control is not active. For a nondistributed program. v If SQL is in the exited state. For a distributed program. the implicit SQL connection is made to the relational database specified on the RDB parameter. SQL is placed in the exited state. or the job level commitment definition is at a unit of work boundary. SQL is placed in the exited state. v At the end of a job. Distributed Support DB2 UDB 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. For a nondistributed program. SQL will end any active connections in the default activation group when SQL becomes not active. Remote unit of work is also referred to as DRDA level 1. If programs precompiled with CLOSQLCSR(*ENDJOB) were run. An activation group with an application process at an application requester can connect to an application server and. Implicit disconnect can occur at the following times in a process: v When the activation group ends. v At the end of a unit of work if SQL is in the exited state. v At the end of a job. Determining Connection Type When a remote connection is established it will use either an unprotected or protected network connection. delete. the sync point managers on the different systems cooperate to ensure that resources reach a consistent state. or unknown whether it is updateable when the connection is established. SQLERRD(4) of the SQLCA indicates the type of connection. updateable. In OS/400 V4R2. but any subsequent connections. 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. If the connection is read-only. The type of data transport protocols used between systems affects whether the network connection is protected or unprotected. However. the first SQL connection is to the local system. this SQL connection may be read-only. Note that when using Interactive SQL. will be read only. A committable update is any insert. This will occur when: Chapter 28. otherwise the connection is an unprotected resource. When running distributed updates. thus they can participate in a distributed unit of work in only a limited way. The connection is unprotected. if the first connection made from the program is to an AS/400 over TCP/IP. After a CONNECT or SET CONNECTION. 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. updates can be performed over it. If two-phase commit protocols will be used. TCP/IP connections are always unprotected. With regards to committable updates. Committable updates can be performed on the connection. the connection is a protected resource. changes using COMMIT(*NONE) can still be run. Therefore in order to make updates to a remote system using TCP/IP. The protocols and flows used by sync point managers are also referred to as two-phase commit protocols. Distributed unit of work is also referred to as DRDA level 2. even over APPC. a single SQL statement can only refer to objects located at a single application server. in one logical unit of work. you must do a RELEASE ALL followed by a COMMIT to end all SQL connections before doing the CONNECT TO remote-tcp-system. Distributed Relational Database Function 567 . or DDL statement that is run under commitment control. SQLERRD(4) will also indicate if the connection uses a unprotected or protected network connection. The sync point manager is a system component that coordinates commit and rollback operations among the participants in the two-phase commit protocol. For example.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. Specific values are: 1. sync point managers at the application servers. and two-phase commit protocol support between the application requester and the application servers. update. – The commitment control level of the program issuing the connect is not *NONE. This will never occur for applications compiled with remote unit of work connection management (*RUW).v The connection is established using remote unit of work (RDBCNNMTH(*RUW)). The connection is read-only. If running with commitment control. – There are no API commitment control resources for the commitment definition. – There are no one-phase API commitment control resources for the commitment definition. v If the connection is established using distributed unit of work (RDBCNNMTH(*DUW)) then all the following are true: – The connection is not local. – There are open updateable local files under commitment control for the commitment definition. The network connection is unprotected. 568 DB2 UDB for AS/400 SQL Programming V4R4 . – Either no connections to other application servers (including local) exist that can perform committable updates or all connections are read-only connections to application servers that do not support distributed unit of work. No committable updates can be performed on the connection. – There are no protected connections registered for the commitment definition. – There are no open updateable DDM files that use a different connection under commitment control for the commitment definition. SQL will register a one-phase updateable DRDA resource for remote connections or a two-phase updateable DRDA resource for local and ARD connections. – Another connection exists to an application server that does not support distributed unit-of-work and that application server can perform committable updates – Another connection exists to an application server that supports distributed unit-of-work (including local). For example. This also includes local connections and application requester driver (ARD) connections using remote unit of work. – The application server does not support distributed unit of work. 2. v The application server does not support distributed unit of work v At least one of the following is true: – The commitment control level of the program issuing the connect is *NONE. For distributed unit of work applications. – There are open updateable DDM files that use a different connection under commitment control for the commitment definition. – There are protected connections registered for the commitment definition. – There are no open updateable local files under commitment control for the commitment definition. a DB2 UDB for AS/400 application server with a release of OS/400 prior to Version 3 Release 1. this will occur only when the following are true when the connection is established: v The connection is not local. It is unknown if committable updates can be performed. The connection is not protected. SQL will register a one-phase DRDA undetermined resource. It is unknown if committable updates can be performed and the connection is a local connection using distributed unit of work or an ARD connection using distributed unit of work. 5. SQL will register a one-phase read-only resource. For more information on two-phase and one-phase resources. It is unknown if committable updates can be performed. If running with commitment control. The connection is protected. SQL will register a two-phase undetermined resource. If running with commitment control. This will never occur for applications compiled with remote unit of work connection management (*RUW). If running with commitment control. The following table summarizes the type of connection that will result for remote distributed unit of work connections. For distributed unit of work applications. v The commitment control level of the program issuing the connect is not *NONE. see the Backup and Recovery book. v The application server supports both distributed unit of work and two-phase commit protocol (protected connections). SQLERRD(4) is set on successful CONNECT and SET CONNECTION statements. 4. For distributed unit of work. this will occur only when all of the following are true when the connection is established: v The connection is not local. this will occur when all of the following are true when the connection is established: v The connection is not local.If running with commitment control. SQL will register a two-phase DRDA undetermined resource. Distributed Relational Database Function 569 . Table 74. 3. Summary of Connection Type Application Server Supports Two-phase Commit No No Application Server Supports Distributed Unit of Work No No Other Updateable One-phase Resource Registered No Yes Connect under Commitment Control No No SQLERRD(4) 2 2 Chapter 28. This will never occur for applications compiled with remote unit of work connection management (*RUW). v The application server supports distributed unit of work v Either the application server does not support two-phase commit protocols (protected connections) or the commitment control level of the program issuing the connect is *NONE. Summary of Connection Type (continued) Application Server Supports Two-phase Commit No No Yes Yes Yes Yes No No No No Yes Yes Yes Yes Application Server Supports Distributed Unit of Work Yes Yes No No Yes Yes No No Yes Yes No No Yes Yes Other Updateable One-phase Resource Registered No Yes No Yes No Yes No Yes No Yes No Yes No Yes Connect under Commitment Control No No No No No No Yes Yes Yes Yes Yes Yes Yes Yes SQLERRD(4) 4 4 2 2 4 4 1 2 4 4 N/A * N/A * 3 3 *DRDA does not allow protected connections to be used to application servers which only support remote unit of work (DRDA1). If a two-phase undetermined or updateable resource is registered or a one-phase updateable resource is registered. Connect and Commitment Control Restrictions There are some restrictions on when you can connect using commitment control. Furthermore. v If the job-level commitment definition is used by more than one activation group. another one-phase updateable resource cannot not be registered. only one activation group may use the job-level commitment definition for RUW connections. when protected connections are inactive and the DDMCNV job attribute is *KEEP. these unused DDM connections will also cause the CONNECT statements in programs compiled with RUW connection management to fail. then there are some restrictions. These restrictions also apply to attempting to run statements using commitment control but the connection was established using COMMIT(*NONE). If running with RUW connection management and using the job-level commitment definition. This includes all DB2 for AS/400 TCP/IP connections.Table 74. Determining Connection Status The CONNECT statement without parameters can be used to determine if the current connection is updateable or read-only for the current unit of work. The value in SQLERRD(3) is determined as follows: 570 DB2 UDB for AS/400 SQL Programming V4R4 . v If the connection is remote. all RUW connections must be to the local relational database. A value of 1 or 2 will be returned in SQLERRD(3). – There are open updateable DDM files that use protected connections. v All of the following are true: – SQLERRD(4) has a value of 3 or 5. – There are open updateable local files under commitment control. .There are two-phase API commitment control resources.The first committable update is performed on a connection that uses a protected connection. is performed on the local database. – The first committable update is performed on a connection that uses an unprotected connection. or is performed on a connection to an ARD program. v SQLERRD(4) has a value of 3 or 5 and one of the following is true: – A connection exists to an updateable application server that only supports remote unit of work.There there are open updateable local files under commitment control. Committable updates can be performed on the connection for the unit of work. Chapter 28. This following table summarizes how SQLERRD(3) is determined based on the SQLERRD(4) value. – There are no open updateable DDM files that use protected connections. . – No connection exists to an application server that does not support distributed unit of work which can perform committable updates. . . and where the first committable update occurred. 2. v SQLERRD(4) has a value of 4 and one of the following is true: – A connection exists to an updateable application server that only supports remote unit of work.1. if there is an updateable connection to an application server that only supports remote unit of work. – The first committable update was not performed on this connection. – There are no two-phase API commitment control resources. Distributed Relational Database Function 571 . No committable updates can be performed on the connection for this unit of work. v All of the following are true: – SQLERRD(4) has a value of 4 – No other connections exist to an application server that does not support distributed unit of work which can perform committable updates. This will occur when one of the following is true: v SQLERRD(4) has a value of 1. – The first committable update is performed on this connection or no committable updates have been made. – There are no open updateable local files under commitment control.No committable updates have been made. – One of the following is true: . This will occur when one of the following is true: v SQLERRD(4) has a value of 2.There are open updateable DDM files that use protected connections. – There are two-phase API commitment control resources. If the connections are done not using commitment control and later committable updates are performed. the unit of work will be placed in a rollback required state. all connections over which updates will be done should be made using commitment control. 572 DB2 UDB for AS/400 SQL Programming V4R4 . read-only connections for the unit of work are likely to result. and no commitment control APIs are registered. all other statements will result in SQLCODE -918. v Two-phase indicates a committable update was performed on a two-phase distributed-unit-of-work application server. no DDM files open for update using a protected connection. if an attempt is made to perform a committable update over the connection. or 5 (due to an ARD program) and the value of SQLERRD(3) is 2. the only statement allowed is a ROLLBACK statement. Summary of Determining SQLERRD(3) Values Connection Exists to Updateable Remote Unit of Work Application Server --Yes No No No No Yes No No No No Yes No No No No SQLERRD(4) 1 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 Where First Committable Update Occurred * SQLERRD(3) ---no updates one-phase this connection two-phase -no updates one-phase this connection two-phase -no updates one-phase this connection two-phase 1 2 2 1 2 1 1 2 1 2 1 2 2 1 2 1 1 * The terms in this column are defined as: v No updates indicates no committable updates have been performed. Distributed Unit of Work Connection Considerations When connecting in a distributed unit of work application. commitment control APIs are registered. 4. no local files are open for update. v One-phase indicates the first committable update was performed using an unprotected connection or DDM files are open for update using unprotected connections. This section lists some design considerations. If an unit of work is in a rollback required state.Table 75. DDM files are open for update using a protected connection. or local files are open for update under commitment control. When the value of SQLERRD(4) is 3. there are many considerations. v If the unit of work will perform updates at more than one application server and commitment control will be used. DDM files. the network connection may either be placed in the unused state or dropped. v When running with a mixture of programs. Attempts to run programs compiled with RUW connection management to remote locations will fail when protected connections exist. a V4R2 AS/400 using TCP/IP). For a description of when connections are implicitly ended see “Implicit Connection Management for the Default Activation Group” on page 565 and “Implicit Connection Management for Nondefault Activation Groups” on page 566. Chapter 28. If the job attribute value is *KEEP and the connection is to another AS/400. Distributed Relational Database Function 573 . When a remote SQL connection is established. The DISCONNECT statement will end the connection when the statement is run. The connection is not ended until a successful COMMIT is run. Connections can be ended implicitly or explicitly. *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. that connection will be either updateable or read-only. Each SQL statement can access only one application server. some compiled with RUW connection management and some programs compiled with DUW connection management.v Other non-SQL commit resources. a DDM network connection (APPC conversation or TCP/IP connection) is used. The RELEASE statement can be used with either protected or unprotected connections. Whether a network connection is dropped or placed in the unused state depends on the DDMCNV job attribute. the connection is dropped. and commitment control API resources. Additional overhead is incurred on commits and rollbacks for unused protected connections. If the connection is updateable it is the only updateable connection. A ROLLBACK or an unsuccessful COMMIT will not end a connection in the released state. such as local files. Connections can be explicitly ended by either the DISCONNECT statement or the RELEASE statement followed by a successful COMMIT. Using distributed unit of work allows changes at multiple applications servers to be committed or rolled back within a single unit of work. v If connecting using commitment control to an application server that does not support distributed unit of work (for example. the connection is always dropped. will affect the updateable and read-only status of a connection. v When running with protected connections using either DDM or DRDA. When the RELEASE statement is run. the connection becomes unused. connections that are no longer going to be used should be ended as soon as possible. the connection is not ended but instead placed into the released state. If the connection is to a non-AS/400. A connection that is in the release stated can still be used. Ending Connections Because remote connections use resources. When the SQL connection is ended. If the job attribute value is *DROP and the connection is to another AS/400. Distributed Unit of Work Distributed unit of work (DUW) allows access to multiple application servers within the same unit of work. The DISCONNECT statement can only be used with connections that use unprotected connections or with local connections. The Reclaim DDM connections (RCLDDMCNV) command may be used to end all unused connections. The CONNECT statement can only be used to start new connections. SET CONNECTION. The following is an example of a C program running in a DUW environment that uses commitment control. which is the default. EXEC SQL CONNECT TO SYSC. Example of Distributed Unit of Work Program (Part 1 of 4) 574 DB2 UDB for AS/400 SQL Programming V4R4 . The RELEASE statement must be followed by a successful commit in order for the connections to end.. Figure 36. connections should be ended when they are no longer needed. This form of the CONNECT statement does not disconnect existing connections but instead places the previous connection in the dormant state. DISCONNECT. The relational database specified on the CONNECT statement becomes the current connection. Because connections use system resources. EXEC SQL WHENEVER SQLERROR GO TO done.Managing Distributed Unit of Work Connections The CONNECT. .. . if you want to switch between existing connections. /* Connect to the systems */ EXEC SQL CONNECT TO LOCALSYS. EXEC SQL DECLARE C1 CURSOR WITH HOLD FOR SELECT PARTNO. the SET CONNECTION statement must be used.. A distributed unit of work CONNECT is run when the program is precompiled using RDBCNNMTH(*DUW).. EXEC SQL WHENEVER NOT FOUND GO TO done. and RELEASE statements are used to manage connections in the DUW environment. /* Open the cursor */ EXEC SQL OPEN C1. EXEC SQL CONNECT TO SYSB.. /* Make the local system the current connection */ EXEC SQL SET CONNECTION LOCALSYS. PRICE FROM PARTS WHERE SITES_UPDATED = 'N' FOR UPDATE OF SITES_UPDATED. The RELEASE or DISCONNECT statement can be used to end connections.. SYSB and SYSC. and 2 remote systems. } done: Figure 36. there are 3 application servers active: LOCALSYS which the local system. When using DUW.:price. Example of Distributed Unit of Work Program (Part 2 of 4) /* Check if the part data is on SYSC */ if ((partnumber > 50) && (partnumber < 200)) { /* Make SYSC the current connection and update the price */ EXEC SQL SET CONNECTION SYSC. SYSB and SYSC also support distributed unit of work and two-phase commit. . EXEC SQL UPDATE PARTS SET PRICE=:price WHERE PARTNO=:partnumber. EXEC SQL RELEASE SYSC. CONTINUE. a CONNECT statement does not disconnect the previous connection. /* Set the current connection to local so the next row can be fetched */ EXEC SQL SET CONNECTION LOCALSYS. */ EXEC SQL COMMIT. } /* Commit the changes made at all 3 sites */ EXEC SQL COMMIT. EXEC SQL UPDATE PARTS SET PRICE=:price WHERE PARTNO=:partnumber. /* Do another commit which The local connection is released.. Initially all connections are made active by using the CONNECT statement for each of the application servers involved in the transaction. /* 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. that are no longer being used */ will end the released connections. Example of Distributed Unit of Work Program (Part 4 of 4) In this program. Distributed Relational Database Function 575 . but instead places the previous connection in Chapter 28. } Figure 36. still active because it was not Figure 36. Example of Distributed Unit of Work Program (Part 3 of 4) EXEC SQL WHENEVER SQLERROR /* Release the connections EXEC SQL RELEASE SYSB..while (SQLCODE==0) { /* Fetch the first row */ EXEC SQL FETCH C1 INTO :partnumber. /* 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. /* Close the cursor */ EXEC SQL CLOSE C1. The changes are then committed. The same is done for SYSC. The local system is still connected and continues processing. and commits is repeated until all the data has been processed. Scoping to the connection means that each connection within a program can have its own separate instance of a cursor or prepared statement. 576 DB2 UDB for AS/400 SQL Programming V4R4 . The current connection is then changed to the local system so that the next row of data can be fetched. The following COBOL example shows how to check the connection status. a commit is issued to end the connections. After the connections are released. * Check if the connection is updateable. EXEC SQL SET CONNECTION SYS5 END-EXEC. the connections for both remote systems are released. . the status of the connection should be checked before doing committable updates. . This set of fetches. The cursor is then opened and the first row of data fetched.. They can not be disconnected because they use protected connections. it remains open after the commit... If SYSB needs to be updated. EXEC SQL CONNECT END-EXEC. then SYSB is made the current connection using the SET CONNECTION statement and the update is run. Because two-phase commit is being used. After all the application servers. have been connected. resulting in two instances of cursor C1. After all the data has been fetched. update sales information otherwise * inform the user. It is then determined at which application servers the data needs to be updated. This will prevent the unit of work from entering the rollback required state. Because the cursor was declared WITH HOLD. The following distributed unit of work example shows how the same cursor name is opened in two different connections. IF SQLERRD(3) = 1 THEN EXEC SQL INSERT INTO SALES_TABLE VALUES(:SALES-DATA) END-EXEC ELSE DISPLAY 'Unable to update sales information at this time'. updates. Example of Checking Connection Status Cursors and Prepared Statements Cursors and prepared statements are scoped to the compilation unit and also to the connection. Checking Connection Status If running in an environment where it is possible to have read-only connections. * If connection is updateable... it is guaranteed that the changes are committed at the local system and the two remote systems. the local connection is made the current connection using the SET CONNECTION statement. Scoping to the compilation unit means that a program called from another separately compiled program cannot use a cursor or prepared statement that was opened or prepared by the calling program.the dormant state. Figure 37. .. . The system then returns the results to the application or the user... Distributed Relational Database Function 577 . when the relational database (RDB) parameter matches the RDB name corresponding to the ARD program. see the System API Reference. EXEC SQL FETCH C1 INTO :rmt_emp_struct. /* Connect to the remote system and open C1 */ EXEC SQL CONNECT TO SYSA. Figure 38. . v Processing of SQL statements when the current connection is to an RDB name corresponding to the ARD program. DB2 UDB for AS/400 provides an interface for writing exit programs on a DB2 UDB for AS/400 application requester to process SQL requests.. /* Close the cursor on the local system */ EXEC SQL SET CONNECTION LOCALSYS... /* Process the data */ . Chapter 28.. Example of Cursors in a DUW program Application Requester Driver Programs To complement database access provided by products that implement DRDA... Such an exit program is called an application requester driver. These calls allow the ARD program to pass the SQL statements and information about the statements to a remote relational database and return results back to the system. /* Keep processing until done */ while (NOT_DONE) { /* Fetch a row of data from the local system */ EXEC SQL SET CONNECTION LOCALSYS.. Access to relational databases accessed by ARD programs appears like access to DRDA application servers in the unlike environment. For more information about application requester driver programs. EXEC SQL OPEN C1. EXEC SQL OPEN C1. The AS/400 calls the ARD program during the following operations: v During package creation performed using the CRTSQLPKG or CRTSQLxxx commands. /* Connect to local and open C1 */ EXEC SQL CONNECT TO LOCALSYS. /* Fetch a row of data from the remote system */ EXEC SQL SET CONNECTION SYSA. EXEC SQL CLOSE C1. EXEC SQL DECLARE C1 CURSOR FOR SELECT * FROM CORPDATA. EXEC SQL FETCH C1 INTO :local_emp_struct.EMPLOYEE. } /* Close the cursor on the remote system */ EXEC SQL CLOSE C1.... Authorized Program Analysis Report (APAR). 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 19 can be created. FFDC is active in both the application requester and application server functions of the OS/400 DDM component. an SQLCODE with a corresponding SQLSTATE is returned in the SQLCA.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 system value QSFWERRLOG must be set to *LOG. The first 1024 bytes of the error information are also logged in the system error log. Note: Not all negative SQLCODEs are dumped. 578 DB2 UDB for AS/400 SQL Programming V4R4 . see the Distributed Database Problem Determination Guide When an SQL error is detected. 19. By means of this function. For more information on these codes. only those that can be used to produce an APAR are dumped. see Appendix B. for the FFDC data to be logged. key structures and the DDM data stream are automatically dumped to a spool file. For more information on handling problems on distributed relational database operations. SQLCODEs and SQLSTATEs. 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. However. © Copyright IBM Corp. NOT NULL ) The following table shows the content of the columns: Table 76. In these sample tables.Appendix A.DEPARTMENT (DEPTNO CHAR(3) DEPTNAME VARCHAR(29) MGRNO CHAR(6) ADMRDEPT CHAR(3) NOT NULL. DEPARTMENT. PROJECT. departments.EMPLOYEE) Employee to project activity table (CORPDATA. The IN_TRAY and CL_SCHED tables are used to illustrate examples that include dates and times given in the DB2 UDB for AS/400 SQL Reference book. DB2 UDB for AS/400 Sample Tables This appendix contains the sample tables referred to and used in this guide and the DB2 UDB for AS/400 SQL Reference book. projects. The tables are in a collection named CORPDATA (for corporate data). the EMPLOYEE.PROJECT) Class Schedule table (CL_SCHED) In Tray table (IN_TRAY) Notes: 1. The department table is created with the following CREATE TABLE statement: CREATE TABLE CORPDATA.DEPARTMENT) The department table describes each department in the enterprise and identifies its manager and the department it reports to. and EMP_ACT tables include information that describes employees. the department at the highest level reports to itself. 1999 579 . 1997. The department (DEPTNO) to which this department reports. and activities. For detailed information on creating tables. see “Creating and Using a Table” on page 14. As a group. 2. a question mark (?) indicates a null value.DEPARTMENT) Employee table (CORPDATA. They are not related to the examples in the CORPDATA collection. Along with the tables are the SQL statements for creating the tables.EMP_ACT) Project table (CORPDATA. NOT NULL. The tables are: v v v v v v Department table (CORPDATA. Department Table (CORPDATA. Columns of the Department Table Column Name DEPTNO DEPTNAME MGRNO ADMRDEPT Description Department number or ID. Employee number (EMPNO) of the department manager. This information makes up a sample application demonstrating some of the features of the DB2 UDB Query Manager and SQL Development Kit licensed program. A name describing the general activities of the department. . .2) NOT NULL. NOT NULL.2) COMM DECIMAL(9.DEPARTMENT DEPTNO A00 B01 C01 D01 D11 D21 E01 E11 E21 DEPTNAME SPIFFY COMPUTER SERVICE DIV. . . . PLANNING INFORMATION CENTER DEVELOPMENT CENTER MANUFACTURING SYSTEMS ADMINISTRATION SYSTEMS SUPPORT SERVICES OPERATIONS SOFTWARE SUPPORT MGRNO 000010 000020 000030 ? 000060 000070 000050 000090 000100 ADMRDEPT A00 A00 A00 A00 D01 D01 A00 E01 E01 Employee Table (CORPDATA.EMPLOYEE) The employee table identifies all employees by an employee number and lists basic personnel information. . Column Name EMPNO FIRSTNME MIDINIT LASTNAME WORKDEPT PHONENO HIREDATE JOB EDLEVEL SEX BIRTHDATE SALARY Description Employee number First name of employee Middle initial of employee Last name of employee ID of department in which the employee works Employee telephone number Date of hire Job held by the employee Number of years of formal education Sex of the employee (M or F) Date of birth Yearly salary in dollars 580 DB2 UDB for AS/400 SQL Programming V4R4 .2) BONUS DECIMAL(9. ) The table below shows the content of the columns. NOT NULL. .EMPLOYEE (EMPNO CHAR(6) FIRSTNME VARCHAR(12) MIDINIT CHAR(1) LASTNAME VARCHAR(15) WORKDEPT CHAR(3) PHONENO CHAR(4) HIREDATE DATE JOB CHAR(8) EDLEVEL SMALLINT SEX CHAR(1) BIRTHDATE DATE SALARY DECIMAL(9. . NOT NULL. NOT NULL. The employee table is created with the following CREATE TABLE statement: CREATE TABLE CORPDATA. . The employee to project activity table is created with the following CREATE TABLE statement: CREATE TABLE CORPDATA.Column Name BONUS COMM Description Yearly bonus in dollars Yearly commission in dollars 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 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 Employee to Project Activity Table (CORPDATA.00) to be spent on the project from EMSTDATE to EMENDATE Start date of the activity Appendix A. ) The table below shows the content of the columns. Table 77.2) EMSTDATE DATE EMENDATE DATE NOT NULL.EMP_ACT (EMPNO CHAR(6) PROJNO CHAR(6) ACTNO SMALLINT EMPTIME DECIMAL(5. Columns of the Employee to Project Activity Table Column Name EMPNO PROJNO ACTNO EMPTIME EMSTDATE Description Employee ID number PROJNO of the project to which the employee is assigned ID of an activity within a project to which an employee is assigned A proportion of the employee’s full time (between 0. The employee’s level of involvement (full-time or part-time) and schedule for activity are also in the table. .EMP_ACT) The employee to project activity table identifies the employee who performs each activity listed for each project.00 and 1. NOT NULL. NOT NULL. . DB2 UDB for AS/400 Sample Tables 581 . 50 .00 .50 .Table 77.50 1.50 EMSTDATE 1982-01-01 1982-01-01 1982-01-01 1982-03-15 1982-03-15 1982-04-15 1982-10-15 1982-02-15 1982-09-15 1982-01-01 1982-02-01 1982-12-01 1983-01-01 1982-02-01 1982-03-15 1982-08-15 1982-08-15 1982-10-15 1982-08-15 1982-06-15 1982-07-01 1982-01-01 1982-03-01 1982-03-01 1982-04-15 1982-06-01 1982-03-01 1982-04-01 1982-09-01 1982-09-01 1982-10-15 1982-01-01 1982-03-01 1982-06-01 1982-01-01 1982-10-01 EMENDATE 1982-07-01 1983-02-01 1982-03-15 1982-04-15 1982-10-15 1982-10-15 1983-01-01 1982-09-15 1983-01-01 1982-02-01 1982-03-15 1983-01-01 1983-02-01 1982-03-15 1982-08-15 1982-10-15 1982-10-15 1982-12-01 1983-01-01 1982-07-01 1983-02-01 1982-03-01 1982-04-15 1982-04-15 1982-06-01 1982-07-01 1982-04-01 1982-09-01 1982-10-15 1982-10-15 1983-02-01 1982-03-01 1982-04-01 1983-01-01 1982-10-01 1983-01-01 582 DB2 UDB for AS/400 SQL Programming V4R4 .50 1.00 .25 .00 .50 1.50 .50 .00 1.50 .50 .00 .00 .25 .50 1.00 1.00 .50 .50 1.75 1.50 .00 1.00 1.00 .00 .25 . Columns of the Employee to Project Activity Table (continued) Column Name EMENDATE Description Completion date of the activity EMP_ACT EMPNO 000010 000070 000230 000230 000230 000230 000230 000240 000240 000250 000250 000250 000250 000250 000250 000250 000250 000250 000250 000260 000260 000260 000260 000260 000260 000260 000270 000270 000270 000270 000270 000270 000270 000030 000130 000130 PROJNO AD3100 AD3110 AD3111 AD3111 AD3111 AD3111 AD3111 AD3111 AD3111 AD3112 AD3112 AD3112 AD3112 AD3112 AD3112 AD3112 AD3112 AD3112 AD3112 AD3113 AD3113 AD3113 AD3113 AD3113 AD3113 AD3113 AD3113 AD3113 AD3113 AD3113 AD3113 AD3113 AD3113 IF1000 IF1000 IF1000 ACTNO 10 10 60 60 70 80 180 70 80 60 60 60 60 70 70 70 80 80 180 70 70 80 80 180 180 180 60 60 60 70 70 80 80 10 90 100 EMPTIME .50 1.50 1.00 1.50 1.00 1.00 . 00 1.00 1.50 .75 .75 .50 .50 .00 1.00 1.00 1.00 1.00 1. DB2 UDB for AS/400 Sample Tables 583 .25 .50 1.25 1.50 .50 .00 1.00 1.00 .00 1.00 1.50 .00 .00 1.50 .00 1.00 1.00 1.00 EMSTDATE 1982-10-01 1982-01-01 1982-01-01 1982-03-01 1982-03-01 1982-10-01 1982-01-01 1982-01-01 1982-01-01 1982-01-01 1982-06-15 1982-01-01 1982-01-01 1982-07-15 1982-01-01 1982-06-01 1982-02-01 1982-10-01 1982-07-15 1982-01-01 1982-04-01 1982-10-01 1982-10-01 1982-01-01 1982-01-01 1982-01-01 1982-01-01 1982-01-01 1982-01-01 1982-01-01 1982-01-01 1982-01-01 1982-01-01 1982-01-01 1982-01-01 1982-01-01 1982-01-01 1982-01-01 EMENDATE 1983-01-01 1983-01-01 1982-03-01 1982-07-01 1982-07-01 1983-01-01 1982-11-01 1982-03-01 1983-02-01 1982-06-15 1983-02-01 1983-02-01 1982-07-15 1983-02-01 1983-06-01 1983-02-01 1982-10-01 1983-10-01 1983-02-01 1983-02-01 1982-06-15 1983-02-01 1983-02-01 1983-02-01 1983-02-01 1983-02-01 1983-02-01 1983-02-01 1983-02-01 1983-02-01 1983-02-01 1983-02-01 1983-02-01 1983-02-01 1983-02-01 1983-02-01 1983-02-01 1982-09-15 Appendix A.00 .00 1.25 .EMPNO 000140 000030 000140 000140 000140 000140 000010 000110 000010 000200 000200 000220 000150 000150 000170 000170 000190 000190 000160 000170 000180 000210 000210 000050 000090 000280 000290 000300 000310 000050 000100 000320 000320 000330 000330 000340 000340 000020 PROJNO IF1000 IF2000 IF2000 IF2000 IF2000 IF2000 MA2100 MA2100 MA2110 MA2111 MA2111 MA2111 MA2112 MA2112 MA2112 MA2112 MA2112 MA2112 MA2113 MA2113 MA2113 MA2113 MA2113 OP1000 OP1010 OP1010 OP1010 OP1010 OP1010 OP2010 OP2010 OP2011 OP2011 OP2012 OP2012 OP2013 OP2013 PL2100 ACTNO 90 10 100 100 110 110 10 20 10 50 60 40 60 180 60 70 70 80 60 80 70 80 180 10 10 130 130 130 130 10 10 140 150 140 160 140 170 30 EMPTIME .75 1.50 1.00 1.00 .50 1. NULL. NULL. person responsible. ) The table below shows the contents of the columns: Column Name PROJNO PROJNAME DEPTNO RESPEMP PRSTAFF PRSTDATE PRENDATE MAJPROJ Description Project number Project name Department number of the department responsible for the project Employee number of the person responsible for the project Estimated mean staffing Estimated start date of the project Estimated end date of the project Controlling project number for sub projects PROJECT PROJNO AD3100 AD3110 AD3111 AD3112 AD3113 IF1000 IF2000 MA2100 MA2110 MA2111 PROJNAME DEPTNO RESPEMP 000010 000070 000230 000250 000270 000030 000030 000010 000060 000220 PRSTAFF 6. Data contained in each row include the project number.5 6 2 1 2 2 1 12 9 2 PRSTDATE 1982-01-01 1982-01-01 1982-01-01 1982-01-01 1982-01-01 1982-01-01 1982-01-01 1982-01-01 1982-01-01 1982-01-01 PRENDATE 1983-02-01 1983-02-01 1983-02-01 1983-02-01 1983-02-01 1983-02-01 1983-02-01 1983-02-01 1983-02-01 1982-12-01 MAJPROJ ? AD3100 AD3110 AD3110 AD3110 ? ? ? MA2100 MA2110 ADMIN SERVICES D01 GENERAL ADMIN SYSTEMS PAYROLL PROGRAMMING PERSONNEL PROGRAMMING ACCOUNT PROGRAMMING QUERY SERVICES USER EDUCATION WELD LINE AUTOMATION WL PROGRAMMING W L PROGRAM DESIGN D21 D21 D21 D21 C01 C01 D01 D11 D11 584 DB2 UDB for AS/400 SQL Programming V4R4 .PROJECT) The project table describes each project that the business is currently undertaking. NULL. . and schedule dates. name. . .2) PRSTDATE DATE PRENDATE DATE MAJPROJ CHAR(6) NOT NOT NOT NOT NULL.Project Table (CORPDATA.PROJECT (PROJNO CHAR(6) PROJNAME VARCHAR(24) DEPTNO CHAR(3) RESPEMP CHAR(6) PRSTAFF DECIMAL(5. The project table is created with the following CREATE TABLE statement: CREATE TABLE CORPDATA. SMALLINT. TIME. and the message itself. Column Name CLASS_CODE DAY STARTING ENDING Description Class code (room:teacher) Day number of 4 day schedule Class start time Class end time Note: This table has no data.PROJNO MA2112 MA2113 OP1000 OP1010 OP2000 OP2010 OP2011 OP2012 OP2013 PL2100 PROJNAME W L ROBOT DESIGN W L PROD CONT PROGS OPERATION SUPPORT OPERATION GEN SYSTEMS SERVICES SYSTEMS SUPPORT SCP SYSTEMS SUPPORT APPLICATIONS SUPPORT DB/DC SUPPORT WELD LINE PLANNING DEPTNO D11 D11 E01 E11 E01 E21 E21 E21 E21 B01 RESPEMP 000150 000160 000050 000090 000050 000100 000320 000330 000340 000020 PRSTAFF 3 3 6 5 5 4 1 1 1 1 PRSTDATE 1982-01-01 1982-02-15 1982-01-01 1982-01-01 1982-01-01 1982-01-01 1982-01-01 1982-01-01 1982-01-01 1982-01-01 PRENDATE 1982-12-01 1982-12-01 1983-02-01 1983-02-01 1983-02-01 1983-02-01 1983-02-01 1983-02-01 1983-02-01 1982-09-15 MAJPROJ MA2110 MA2110 ? OP1000 ? OP2000 OP2010 OP2010 OP2010 MA2100 Class Schedule Table (CL_SCHED) The class schedule table describes: each class. DB2 UDB for AS/400 Sample Tables 585 . In Tray Table (IN_TRAY) The in tray table describes an electronic in-basket containing: a timestamp from when the message was received. the user ID of the person sending the message. The class schedule table is created with the following CREATE TABLE statement: CREATE TABLE CL_SCHED (CLASS_CODE DAY STARTING ENDING CHAR(7). The in tray table is created with the following CREATE TABLE statement: Appendix A. the end time for the class. TIME) The table below gives the contents of the columns. and the class code. the start time for the class. CHAR(8). 586 DB2 UDB for AS/400 SQL Programming V4R4 . VARCHAR(3000)) The table below gives the contents of the columns.CREATE TABLE IN_TRAY (RECEIVED SOURCE SUBJECT NOTE_TEXT TIMESTAMP. Column Name RECEIVED SOURCE SUBJECT NOTE_TEXT Description Date and time received User ID of person sending the note Brief description of the note The note Note: This table has no data. CHAR(64). you can quickly reference “Positive SQLCODEs” on page 589 or “Negative SQLCODEs” on page 591. SQLSTATEs are particularly useful when handling errors in distributed SQL applications. but they are not listed here. 1999 587 . An application can also send the SQL message corresponding to any SQLCODE to the job log by specifying the message ID and the replacement text on the CL commands Retrieve Message (RTVMSG). You can access this display by using the CL command Display Message Description (DSPMSGD). the SQLCODE is a positive number and bytes one and two of the SQLSTATE are '01'. '01' or '02'. SQL places a message corresponding to the SQLCODE in the job log for each SQL statement run. Send Program Message (SNDPGMMSG). If your SQL statement is processed without encountering an error or warning condition.Appendix B. If you are not running in debug mode and get a negative SQLCODE. and Send User Message (SNDUSRMSG). and the SQLCODE is a negative number. Detailed descriptions of all DB2 UDB for AS/400 messages. SQLSTATE values consist of a two-character class code. This appendix lists SQLCODEs and their associated SQLSTATEs. the first characters of the SQLSTATE are not '00'. are available on-line and can be displayed and printed from the Display Message Description display. If SQL encounters a warning but valid condition while processing your statement. the SQLCODE returned is 0 and SQLSTATE is '00000'. SQLCODEs are returned in the SQLCA structure. followed by a three-character code. For example. if the SQLCODE is 30070. When running in debug mode. the message ID is SQ30070. The message ID for any SQLCODE is constructed by appending the absolute value (5 digits) of the SQLCODE to SQ and changing the third character to 'L' if the third character is a 0. The class codes are: v 00 Unqualified Successful Completion v v v v v 01 02 03 07 08 Warning No Data SQL Statement Not Yet Complete Dynamic SQL Error Connection Exception v 09 Triggered Action Exception © Copyright IBM Corp. If SQL encounters an error while processing the statement. 1997. There are many other SQL messages. | | If you wish. SQLCODEs and SQLSTATEs SQL does not communicate directly with the end user but rather returns error codes to the application program when an error occurs. SQLSTATE is an additional return code that provides application programs with common return codes for common error conditions found among the IBM relational database systems. you will get a message in the job log also. Every SQLCODE has a corresponding message in message file QSQLMSG in library QSYS. The class codes conform to ISO/ANSI standards. including SQLCODEs. 588 DB2 UDB for AS/400 SQL Programming V4R4 . DB2 UDB for AS/400 attempts to map the SQLSTATE to a DB2 UDB for AS/400 SQLCODE and message: v If the SQLSTATE is not recognized by DB2 UDB for AS/400. the common message for the class is issued. SC26-8416. Version 2. SK2T-0730-11.v v v v v v v v v v v v v v v v v v 0A Feature Not Supported 09 Invalid Token 20 Case Not Found for CASE Statement 21 Cardinality Violation 22 Data Exception 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 2C Invalid Character Set Name 2D Invalid Transaction Termination 2E Invalid Connection Name 2F SQL Function Exception 33 Invalid SQL Descriptor Name 34 Invalid Cursor Name v 35 Invalid Condition Number v 38 External Function Exception v 39 External Function Call Exception v v v v v v v v v v v v 3C Ambiguous Cursor Name 3D Invalid Catalog Name 3F Invalid Collection (Schema) Name 40 Transaction Rollback 42 44 51 53 54 55 56 57 Syntax Error and Access Rule Violation WITH CHECK OPTION Violation Invalid Application State Invalid Operand or Inconsistent Specification SQL or Product Limit Exceeded Object Not in Prerequisite State Miscellaneous SQL or Product Error Resource Not Available or Operator Intervention v 58 System Error For a list of SQLSTATEs that are used by the DB2 family of products. Also available on CD-ROM as a part of the Transaction Processing Collection Kit CD-ROM. When an SQLSTATE other than '00000' is returned from a non-DB2 UDB for AS/400 application server. see IBM SQL Reference. time.v If the SQLSTATE and SQLCODE correspond to a single DB2 UDB for AS/400 SQLCODE. SQL0030 SQLCODE +30 SQLSTATE 01503 Explanation: Value in date. SQL0180 SQLCODE +180 SQLSTATE 01534 Explanation: Syntax of date. Explanation: Number of INTO host-variable incorrect. Otherwise. More detailed cause and recovery information for any SQLCODE can be found by using the Display Message Description (DSPMSGD) CL command. SQL0114 SQLCODE +114 SQLSTATE 01536 Explanation: Relational database &1 not the same as current server &2. SQL0178 SQLCODE +178 SQLSTATE 0100A Explanation: Query expression text for view &1 in &2 too long. The date resulted from an arithmetic operation. a string has been truncated. The replacement text for these fields is stored in SQLERRM in the SQLCA. If SQLWARN0 is blank. DB2 UDB for AS/400 attempts to convert the tokens returned in SQLERRM to the replacement data expected by the SQL message. The following warnings have an SQLCODE of zero: v SQLWARN1 SQLSTATE 01004 Explanation: The value of a string column was truncated when assigned to a host variable. For example. and a number (for example. v SQLWARN4 SQLSTATE 01504 Explanation: The UPDATE or DELETE statement does not include a WHERE clause. a warning condition exists. and SQLSTATE is '00000'. – A common message for the class code of the SQLSTATE is issued. &1). SQL0181 SQLCODE +181 SQLSTATE 01534 Explanation: Correlation without qualification occurred for column &1 to table &2. SQL0012 SQLCODE +12 SQLSTATE 01545 Explanation: No WHERE on UPDATE or DELETE. Positive SQLCODEs N/A SQLCODE 0 SQL0088 SQLCODE +88 SQLSTATE 01504 Explanation: The SQL statement has run successfully. or timestamp value not valid. Appendix B. Check the other warning indicators or SQLSTATE to determine the particular warning condition. If an error occurs while converting the tokens: – The SQLCA is not changed. SQL0100 SQLCODE +100 SQLSTATE 02000 Explanation: Row not found for &1. SQLCODEs and SQLSTATEs 589 . v SQLWARN2 SQLSTATE 01003 Explanation: Null values were eliminated from the argument of a column function. or timestamp string not valid. v SQLWARN6 SQLSTATE 01506 Explanation: An adjustment was made to a DATE or TIMESTAMP value to correct a date the was not valid. v SQLWARN3 SQLSTATE 01503 Explanation: The number of result columns is larger than the number of host variables provided. SQL0138 SQLCODE +138 SQLSTATE 01544 Explanation: Argument &1 of SUBSTR function not valid. if SQLWARN1 is not blank. time. SQL0177 SQLCODE +177 SQLSTATE 01009 Explanation: CHECK condition text too long. SQLCODE and SQLSTATE Descriptions In the following brief descriptions of the SQLCODEs (and their associated SQLSTATEs) message data fields are identified by an ampersand (&). the statement was run successfully. SQL0863 SQLCODE +863 SQLSTATE 01539 Explanation: Alias &1 in &2 created but table or view not found. Explanation: Character in CAST argument not valid. SQL0335 SQLCODE +335 SQLSTATE 01517 Explanation: Error occurred during disconnect. SQL0204 SQLCODE +204 SQLSTATE 01532 Explanation: Truncation of data may have occurred for ALTER TABLE in &1 of &2. SQL0403 SQLCODE +403 SQLSTATE 01522 Explanation: Data conversion or data mapping error. 01565 SQLSTATE 01515. SQL0420 SQLCODE +420 SQLSTATE 01565 Explanation: Mixed or DBCS CCSID not supported by relational database &1. SQL0460 SQLCODE +460 SQLSTATE 01593 Explanation: MIXED data not properly formed. SQL0990 SQLCODE +990 SQLSTATE 01587 Explanation: Outcome unknown for the unit of work. SQL0802 SQLCODE +802 SQLSTATE 01519.SQL0183 SQLCODE +183 SQLSTATE 01535 SQL0445 SQLCODE +445 SQLSTATE 01004 Explanation: The result of a date or timestamp expression not valid. | SQL0237 SQLCODE +237 SQLSTATE 01005 Explanation: Not authorized to object &1 in &2 type *&3. SQL0191 SQLCODE +191 SQLSTATE 01547 Explanation: Value of parameter &4 in procedure &1 in &2 too long. Explanation: WHERE NOT NULL clause ignored for index &1 in &2. 01564. 590 DB2 UDB for AS/400 SQL Programming V4R4 . | SQL0239 SQLCODE +239 SQLSTATE 01005 Explanation: Not authorized to &1. SQL0570 SQLCODE +570 SQLSTATE 01007 Explanation: Conversion error in assignment to host variable &2. SQL0552 SQLCODE +552 SQLSTATE 01542 | Explanation: Not enough SQLVAR entries were | provided in the SQLDA. SQL0569 SQLCODE +569 SQLSTATE 01006 | Explanation: Not enough SQLVAR entries were | provided in the SQLDA. SQL0645 SQLCODE +645 SQLSTATE 01528 Explanation: Characters conversion has resulted in substitution characters. SQL0326 SQLCODE +326 SQLSTATE 01557 Explanation: Not all requested privileges to object &1 in &2 type &3 granted. SQL0596 SQLCODE +596 SQLSTATE 01002 Explanation: Characters conversion cannot be performed. SQL0551 SQLCODE +551 SQLSTATE 01548 Explanation: Object &1 in &2 type *&3 not found. Explanation: Not all requested privileges revoked from object &1 in &2 type &3. 01547. SQL0595 SQLCODE +595 SQLSTATE 01526 Explanation: Too many host variables specified. SQL0331 SQLCODE +331 SQLSTATE 01520 Explanation: Commit level &1 escalated to &2 lock. 01565 | SQL0360 SQLCODE +360 SQLSTATE 01627 | Explanation: Datalink in table &1 in &2 may not be | valid due to pending links. SQL0304 SQLCODE +304 01547. SQL0109 SQLCODE -109 SQLSTATE 42601 Explanation: Indicator variable &1 not SMALLINT type. SQL0105 SQLCODE -105 SQLSTATE 42604 Explanation: Cursor or procedure &1 previously declared. SQL0113 SQLCODE -113 2E000. SQL0112 SQLCODE -112 SQLSTATE 42607 Explanation: Host variable not permitted here. | | SQL0097 SQLCODE -97 SQLSTATE 42601 Explanation: Use of data type not valid. SQL0029 SQLCODE -29 SQLSTATE 42601 Explanation: Numeric constant &1 not valid. SQL0104 SQLCODE -104 SQLSTATE 42601 Explanation: INTO clause missing from embedded SELECT statement. SQL0084 SQLCODE -84 SQLSTATE 42612 Explanation: &1 clause not allowed. SQL0060 SQLCODE -60 SQLSTATE 42815 Explanation: Mixed or graphic string constant not valid. SQL0099 SQLCODE -99 SQLSTATE 42992 Explanation: Argument of function &1 is another function. SQL0107 SQLCODE -107 SQLSTATE 42622 Explanation: &1 too long. Valid tokens: &2.SQL7905 SQLCODE +7905 SQLSTATE 01567 Explanation: Table &1 in &2 created but could not be journaled. SQL0106 SQLCODE -106 SQLSTATE 42611 Explanation: Value &3 for argument &1 of &2 function not valid. SQL0103 SQLCODE -103 SQLSTATE 42604 Explanation: String constant beginning &1 not delimited. Maximum &2 characters. 54011 SQLSTATE 54001. SQL0110 SQLCODE -110 SQLSTATE 42606 Explanation: SQL statement not allowed. SQL0080 SQLCODE -80 SQLSTATE 42978 Explanation: Precision specified for FLOAT column not valid. Negative SQLCODEs SQL0007 SQLCODE -07 SQLSTATE 42601 SQL0102 SQLCODE -102 SQLSTATE 54002 Explanation: Character &1 (HEX &2) not valid in SQL statement. SQL0051 SQLCODE -51 SQLSTATE 3C000 Explanation: Token &1 was not valid. SQL0010 SQLCODE -10 SQLSTATE 42603 Explanation: String constant beginning with &1 too long. Appendix B. SQL0101 SQLCODE -101 54010. SQL0090 SQLCODE -90 SQLSTATE 42618 Explanation: Hexadecimal constant beginning with &1 not valid. 42602 SQLSTATE 28000. SQL0114 Explanation: Name &1 not allowed. SQLCODEs and SQLSTATEs 591 . Explanation: Operator in join condition not valid. Explanation: Relational database &1 not the same as current server &2. SQLCODE -114 SQLSTATE 42961 Explanation: SQL statement too long or complex. SQL0125 SQLCODE -125 SQLSTATE 42805 Explanation: Recursion not supported for an application server other than the AS/400 system. SQL0151 SQLCODE -151 SQLSTATE 42808 Explanation: Use of NULL is not valid. 592 DB2 UDB for AS/400 SQL Programming V4R4 . SQL0131 SQLCODE -131 SQLSTATE 42818 Explanation: Column list required for CREATE VIEW. SQL0119 SQLCODE -119 SQLSTATE 42803 Explanation: Argument of function too long. SQL0118 SQLCODE -118 SQLSTATE 42902 Explanation: Operator on correlated column in SQL function not valid. SQL0117 SQLCODE -117 SQLSTATE 42802 Explanation: LIKE predicate not valid. Explanation: Constraint type not valid for constraint &1 in &2. SQL0122 SQLCODE -122 SQLSTATE 42803 Explanation: Argument &1 of SUBSTR function not valid. SQL0154 SQLCODE -154 SQLSTATE 42909 Explanation: Operands of LIKE not compatible or not valid. Explanation: UNION and UNION ALL for CREATE VIEW not valid. SQL0134 SQLCODE -134 SQLSTATE 42907 Explanation: Table &1 in &2 also specified in a FROM clause. SQL0144 SQLCODE -144 SQLSTATE 58003 Explanation: Section number not valid. SQL0133 SQLCODE -133 SQLSTATE 42906 Explanation: Statement inserts wrong number of values. SQL0120 SQLCODE -120 SQLSTATE 42903 Explanation: ORDER BY or GROUP BY columns too long. SQL0128 SQLCODE -128 SQLSTATE 42601 Explanation: View or logical file &1 in &2 read-only. SQL0121 SQLCODE -121 SQLSTATE 42701 Explanation: Duplicate column name &1 in INSERT or UPDATE. SQL0145 SQLCODE -145 SQLSTATE 55005 Explanation: Column specified in SELECT list not valid. SQL0138 SQLCODE -138 SQLSTATE 22011 Explanation: Use of column function &2 not valid. SQL0129 SQLCODE -129 SQLSTATE 54004 Explanation: Column &1 in table &2 in &3 read-only. SQL0150 SQLCODE -150 SQLSTATE 42807 Explanation: ORDER BY column number &1 not valid. SQL0136 SQLCODE -136 SQLSTATE 54005 Explanation: Column &1 in HAVING clause not in GROUP BY. SQL0130 SQLCODE -130 22025 SQLSTATE 22019. SQL0152 SQLCODE -152 SQLSTATE 42809 Explanation: Too many tables in SQL statement. SQL0137 SQLCODE -137 SQLSTATE 54006 Explanation: Result too long. SQL0153 SQLCODE -153 SQLSTATE 42908 Explanation: Escape character &1 or LIKE pattern not valid.SQL0115 SQLCODE -115 SQLSTATE 42601 SQL0132 SQLCODE -132 SQLSTATE 42824 Explanation: Comparison operator &1 not valid. time. SQL0175 SQLCODE -175 SQLSTATE 58028 Explanation: Argument of TRANSLATE function not valid. SQL0195 SQLCODE -195 SQLSTATE 42814 Explanation: Syntax of date. SQL0181 SQLCODE -181 SQLSTATE 22007 Explanation: Last column of &1 in &2 cannot be dropped. SQL0194 SQLCODE -194 SQLSTATE 42848 Explanation: COMMIT failed. Explanation: &1 in &2 not correct type. or timestamp string not valid. SQLCODEs and SQLSTATEs 593 . SQL0180 SQLCODE -180 SQLSTATE 22007 Explanation: KEEP LOCKS not allowed. or timestamp value not valid. SQL0157 SQLCODE -157 SQLSTATE 42810 Explanation: The result of a date or timestamp expression not valid. SQL0161 SQLCODE -161 SQLSTATE 44000 Explanation: Coded Character Set Identifier &1 is not valid. SQL0192 SQLCODE -192 SQLSTATE 42937 Explanation: Argument &1 of function &2 not valid. or timestamp expression not valid. SQL0187 SQLCODE -187 SQLSTATE 42816 Explanation: Number of columns specified not consistent. SQL0197 SQLCODE -197 SQLSTATE 42877 Explanation: A date. SQL0190 SQLCODE -190 SQLSTATE 42837 Explanation: INSERT/UPDATE not allowed due to WITH CHECK OPTION. Explanation: Column &1 cannot be qualified. SQL0160 SQLCODE -160 SQLSTATE 42813 Explanation: &1 is not a valid string representation of an authorization name or a relational database name. Appendix B. SQL0182 SQLCODE -182 SQLSTATE 42816 Explanation: Column &3 in &1 in &2 cannot be dropped with RESTRICT. SQL0191 SQLCODE -191 SQLSTATE 22504 Explanation: Number of arguments for function &1 not valid. time. 2E000 SQLSTATE 22503. SQL0170 SQLCODE -170 SQLSTATE 42605 Explanation: Attributes of column &3 in &1 in &2 not compatible. SQL0196 SQLCODE -196 SQLSTATE 42817 Explanation: Value in date. SQL0171 SQLCODE -171 SQLSTATE 42815 Explanation: MIXED data not properly formed. SQL0189 SQLCODE -189 SQLSTATE 22522 Explanation: WITH CHECK OPTION not allowed for view &1 in &2. SQL0159 SQLCODE -159 SQLSTATE 42809 Explanation: Use of labeled duration is not valid. SQL0158 SQLCODE -158 SQLSTATE 42811 Explanation: Parameter marker not valid in expression.SQL0156 SQLCODE -156 SQLSTATE 42809 SQL0183 SQLCODE -183 SQLSTATE 22008 Explanation: &1 in &2 not a table. time. SQL0184 SQLCODE -184 SQLSTATE 42610 Explanation: View &1 in &2 not valid in FOREIGN KEY clause. SQL0188 SQLCODE -188 28000. SQL0227 SQLCODE -227 SQLSTATE 24513 Explanation: Host variable &1 not compatible with SELECT item. SQL0212 SQLCODE -212 SQLSTATE 42712 Explanation: Constraint &1 in &2 not allowed on distributed file. SQL0251 SQLCODE -251 42602 SQLSTATE 2E000. Valid tokens: &2. SQL0231 SQLCODE -231 SQLSTATE 22006 Explanation: Keyword &1 not expected. SQL0255 SQLCODE -255 SQLSTATE 42999 Explanation: Column &1 not in specified tables. Explanation: Current row deleted or moved for cursor &1. SQL0204 SQLCODE -204 SQLSTATE 42704 Explanation: Local relational database not defined in the directory. SQL0256 SQLCODE -256 SQLSTATE 42998 Explanation: ORDER BY column &1 not in results table.SQL0198 SQLCODE -198 SQLSTATE 42617 SQL0228 SQLCODE -228 SQLSTATE 42620 Explanation: SQL statement empty or blank. 22003. SQL0302 SQLCODE -302 SQLSTATE 22001. SQL0225 SQLCODE -225 SQLSTATE 42872 Explanation: FETCH not valid. SQL0199 SQLCODE -199 SQLSTATE 42601 Explanation: FOR UPDATE OF clause not valid with SCROLL for cursor &1. SQL0208 SQLCODE -208 SQLSTATE 42707 Explanation: DB2 Multisystem query error. SQL0206 SQLCODE -206 SQLSTATE 42703 Explanation: Character in relational database name &1 is not valid. 22504 SQLSTATE 22003. 594 DB2 UDB for AS/400 SQL Programming V4R4 . SQL0203 SQLCODE -203 SQLSTATE 42702 Explanation: Position of cursor &1 not valid for FETCH of current row. SQL0221 SQLCODE -221 SQLSTATE 42873 Explanation: Input host variable &2 or argument &1 not valid. cursor &1 in unknown position. SQL0214 SQLCODE -214 SQLSTATE 42822 Explanation: Unique index not allowed. SQL0303 SQLCODE -303 42806 SQLSTATE 22001. SQL0250 SQLCODE -250 SQLSTATE 42718 Explanation: Column &1 is ambiguous. Explanation: Conversion error in assignment to host variable &2. SQL0270 SQLCODE -270 SQLSTATE 42997 Explanation: Duplicate table designator &1 not valid. SQL0301 SQLCODE -301 07006.42895 SQLSTATE Explanation: ORDER BY expression is not valid. SQL0205 SQLCODE -205 SQLSTATE 42703 Explanation: Column &1 not in table &2. SQL0226 SQLCODE -226 SQLSTATE 24507 Explanation: Conversion error on input host variable &2. Explanation: &1 in &2 type *&3 not found. 22024 Explanation: Number of rows &2 not valid. SQL0304 SQLCODE -304 22023. cursor &1 not declared with SCROLL. Explanation: FETCH not valid. 22023. | SQL0357 SQLCODE -357 SQLSTATE 57050 Explanation: Character conversion cannot be performed. | SQL0392 SQLCODE -392 SQLSTATE 42855 Explanation: Character conversion between CCSID &1 and CCSID &2 not valid. Explanation: Comparison operator &1 operands not compatible. SQL0351 SQLCODE -351 SQLSTATE 56084 Explanation: Number of host variables not valid. | SQL0398 SQLCODE -398 SQLSTATE 428D2 Explanation: Character conversion has resulted in truncation. SQLCODEs and SQLSTATEs 595 .SQL0305 SQLCODE -305 SQLSTATE 22002 | SQL0340 SQLCODE -340 SQLSTATE 42726 Explanation: Indicator variable required. | SQL0346 SQLCODE -346 SQLSTATE 42836 Explanation: Length in a varying-length host variable not valid. SQL0401 SQLCODE -401 SQLSTATE 42818 Explanation: JOIN expression not valid. SQL0312 SQLCODE -312 SQLSTATE 42618 | Explanation: Recursion not allowed for common table | expressions. SQL0311 SQLCODE -311 SQLSTATE 22501 | Explanation: Cyclic references between common | table expressions. | SQL0352 SQLCODE -352 SQLSTATE 56084 Explanation: Column &1 not allowed in partitioning key. SQL0334 SQLCODE -334 SQLSTATE 22524 | Explanation: Assignment of LOB to specified host | variable not allowed. | | SQL0329 SQLCODE -329 SQLSTATE 0E000 Explanation: The SET PATH name list is not valid. SQL0331 SQLCODE -331 SQLSTATE 22021 | Explanation: File server &1 used in DataLink not | currently available. | SQL0341 SQLCODE -341 SQLSTATE 42835 Explanation: Undefined host variable in REXX. | SQL0358 SQLCODE -358 SQLSTATE 428D1 Explanation: Character conversion cannot be performed. SQL0328 SQLCODE -328 SQLSTATE 42996 | Explanation: The AR is not at the same level and | DB2/400 cannot transform the data type to a compatible | type. SQL0306 SQLCODE -306 SQLSTATE 42863 | Explanation: Duplicate name &1 for common table | expression. SQL0313 SQLCODE -313 07004 SQLSTATE 07001. SQL0330 SQLCODE -330 SQLSTATE 22021 | Explanation: The AS is not at the same level and | DB2/400 cannot transform the data type to a compatible | type. Appendix B. | Explanation: Column &1 is not valid as key field for | index or constraint. SQL0338 SQLCODE -338 SQLSTATE 42972 | Explanation: AS LOCATOR cannot be specified for a | non-LOB parameter. SQL0332 SQLCODE -332 SQLSTATE 57017 | Explanation: Error &1 occurred using DataLink data | type. | SQL0350 SQLCODE -350 SQLSTATE 42962 Explanation: Host variable &1 not defined or not usable. | SQL0414 SQLCODE -414 SQLSTATE 42824 Explanation: Column &1 not valid in LIKE predicate. Explanation: Combination of parameter markers not valid. | | SQL0423 SQLCODE -423 SQLSTATE 0F001 Explanation: Numeric constant &1 out of range. SQL0415 SQLCODE -415 SQLSTATE 42825 SQL0441 SQLCODE -441 SQLSTATE 42601 | | Explanation: Clause or keyword &1 not valid where specified. SQL0444 SQLCODE -444 SQLSTATE 42724 Explanation: Use of parameter marker is not valid. SQL0428 SQLCODE -428 SQLSTATE 25501 Explanation: SQL statement cannot be run. SQL0442 SQLCODE -442 SQLSTATE 54023 Explanation: UNION operands not compatible. Explanation: Conversion error on assignment to column &2.SQL0402 SQLCODE -402 SQLSTATE 42819 SQL0420 SQLCODE -420 SQLSTATE 22018 Explanation: &1 use not valid. SQL0432 SQLCODE -432 SQLSTATE 42841 Explanation: Null values are not allowed in column &1. Explanation: Number of arguments on CALL must match procedure. SQL0406 SQLCODE -406 22023. Explanation: LOB locator &1 not valid. SQL0404 SQLCODE -404 SQLSTATE 22001 Explanation: Character in CAST argument not valid. SQL0440 SQLCODE -440 SQLSTATE 42884 Explanation: Floating point literal &1 not valid. SQL0421 SQLCODE -421 SQLSTATE 42826 Explanation: Value for column &1 too long. SQL0433 SQLCODE -433 SQLSTATE 22001 Explanation: INSERT or UPDATE value for column &1 not compatible. 596 DB2 UDB for AS/400 SQL Programming V4R4 . SQL0407 SQLCODE -407 SQLSTATE 23502 | | | | | | SQL0429 SQLCODE -429 SQLSTATE 54028 Explanation: The maximum number of concurrent LOB lcoators has been reached. SQL0405 SQLCODE -405 SQLSTATE 42820 Explanation: Number of UNION operands not equal. 22504 SQLSTATE 22003. SQL0408 SQLCODE -408 SQLSTATE 42821 Explanation: A parameter marker cannot have the user-defined type name &1. SQL0418 SQLCODE -418 SQLSTATE 42610 Explanation: Trigger program or external procedure detected on error. SQL0412 SQLCODE -412 SQLSTATE 42823 Explanation: Subquery with more than one result column not valid. SQL0443 SQLCODE -443 38501 SQLSTATE 2Fxxx. SQL0410 SQLCODE -410 SQLSTATE 42820 Explanation: Significant digits truncated during CAST from numeric to character. Explanation: Negative scale not valid. SQL0417 SQLCODE -417 SQLSTATE 42609 Explanation: Maximum # of parameters on CALL exceeded. SQL0419 SQLCODE -419 SQLSTATE 42911 Explanation: External program &4 in &1 not found. | SQL0483 SQLCODE -483 SQLSTATE 42885 Explanation: Function &1 in &2 with the same signature already exists. SQL0490 SQLCODE -490 SQLSTATE 428B7 Explanation: Name &1 in &2 not allowed for function. OUT. SQL0451 SQLCODE -451 SQLSTATE 42815 Explanation: NULL values not allowed for parameter &4 in procedure. | | | | | | | SQL0456 SQLCODE -456 SQLSTATE 42710 | Explanation: Routine &1 in &2 already exists. | SQL0473 SQLCODE -473 SQLSTATE 42918 Explanation: Attributes of parameter &1 not valid for procedure. SQL0470 SQLCODE -470 SQLSTATE 39002 Explanation: External program name for procedure &1 in &2 not valid. | SQL0478 SQLCODE -478 SQLSTATE 42893 Explanation: Return type for function &1 in &2 not compatible with CAST TO type. SQL0487 SQLCODE -487 SQLSTATE 38001 Explanation: Specific name &3 in &2 already exists. Explanation: Cast from &1 to &2 not supported. SQL0461 SQLCODE -461 SQLSTATE 42846 | SQL0491 SQLCODE -491 SQLSTATE 42601 | Explanation: RETURNS clause required on CREATE | FUNCTION statement.. SQL0458 SQLCODE -458 SQLSTATE 42883 Explanation: Numeric value &1 not valid. Explanation: Function &1 in &2 not found with matching signature. SQL0457 SQLCODE -457 SQLSTATE 42939 Explanation: SQL statements not allowed. SQL0455 SQLCODE -455 SQLSTATE 42882 | Explanation: Parameters for function &1 in &2 not | same as sourced function. | SQL0484 SQLCODE -484 SQLSTATE 42733 Explanation: Specific name not same as procedure name.SQL0446 SQLCODE -446 SQLSTATE 22003 | SQL0463 SQLCODE -463 SQLSTATE 39001 Explanation: Conversion error in assignment of argument &2. Appendix B. SQL0448 SQLCODE -448 SQLSTATE 54023 | Explanation: SQLSTATE &4 returned from routine &1 | in &2 not valid. SQL0453 SQLCODE -453 SQLSTATE 42880 | Explanation: RETURNS data type for function &3 in | &4 not valid. | SQL0475 SQLCODE -475 SQLSTATE 42866 | | | | | | | | | SQL0452 SQLCODE -452 SQLSTATE 428A1 Explanation: Unable to access a file that is referred to by a file reference variable. INOUT not valid for parameter &4 in procedure &1 in &2. | SQL0476 SQLCODE -476 SQLSTATE 42725 | Explanation: Function &1 in &2 not unique. SQL0454 SQLCODE -454 SQLSTATE 42723 | Explanation: Object &1 in &2 of type &3 cannot be | dropped. SQL0449 SQLCODE -449 SQLSTATE 42878 Explanation: IN. SQLCODEs and SQLSTATEs 597 . | Explanation: User-defined type &1 cannot be created. SQL0469 SQLCODE -469 SQLSTATE 42886 Explanation: Maximum parameters on DECLARE PROCEDURE exceeded. SQL0536 SQLCODE -536 SQLSTATE 42914 Explanation: Alias &1 in &2 cannot reference another alias. SQL0503 SQLCODE -503 SQLSTATE 42912 Explanation: Prepared statement &2 in use. SQL0537 SQLCODE -537 SQLSTATE 42709 Explanation: Prepared statement &2 not found. SQL0504 SQLCODE -504 SQLSTATE 34000 Explanation: Cannot UPDATE or DELETE on cursor &1. 598 DB2 UDB for AS/400 SQL Programming V4R4 . SQL0518 SQLCODE -518 SQLSTATE 07003 Explanation: Cursor &1 not open. SQL0516 SQLCODE -516 SQLSTATE 26501 Explanation: Prepared statement &2 not found. SQL0507 SQLCODE -507 SQLSTATE 24501 Explanation: Statement not valid on application server. Explanation: Duplicate column name in definition of key. SQL0514 SQLCODE -514 SQLSTATE 26501 Explanation: Delete not allowed because table referenced in subquery can be affected. SQL0502 SQLCODE -502 SQLSTATE 24502 Explanation: Prepared statement &1 not found. SQL0501 SQLCODE -501 SQLSTATE 24501 Explanation: Prepared statement &2 not SELECT statement. SQL0525 SQLCODE -525 SQLSTATE 51015 Explanation: Cursor &1 not declared.| SQL0492 SQLCODE -492 SQLSTATE 42879 SQL0517 SQLCODE -517 SQLSTATE 07005 | Explanation: Data type for function &1 in &2 not valid | for source type. Explanation: FOR UPDATE OF clause not valid. SQL0508 SQLCODE -508 SQLSTATE 24504 Explanation: ALWCPYDTA(*NO) specified but temporary result required for &1. SQL0513 SQLCODE -513 SQLSTATE 42924 Explanation: Delete prevented by referential constraint. Explanation: Cursor &1 for file &2 is read-only. SQL0531 SQLCODE -531 23504 SQLSTATE 23001. SQL0532 SQLCODE -532 23504 SQLSTATE 23001. SQL0511 SQLCODE -511 SQLSTATE 42829 Explanation: Update prevented by referential constraint. SQL0520 SQLCODE -520 SQLSTATE 42828 Explanation: Column &3 cannot be updated. SQL0519 SQLCODE -519 SQLSTATE 24506 Explanation: Cursor &1 already open. SQL0527 SQLCODE -527 SQLSTATE 42874 Explanation: Cursor &1 not open. SQL0530 SQLCODE -530 SQLSTATE 23503 Explanation: Cursor &1 not positioned on locked row. SQL0510 SQLCODE -510 SQLSTATE 42828 Explanation: Insert or UPDATE value not allowed by referential constraint. SQL0509 SQLCODE -509 SQLSTATE 42827 Explanation: Table &2 in &3 not same as table in cursor &1. SQL0552 SQLCODE -552 SQLSTATE 42502 Explanation: Object &1 in &2 type *&3 already exists. SQL0573 SQLCODE -573 SQLSTATE 42890 Explanation: Unique index cannot be created because of duplicate keys. SQL0545 SQLCODE -545 SQLSTATE 23513 | SQL0583 SQLCODE -583 SQLSTATE 42845 | Explanation: Use of function &1 in &2 not valid.SQL0538 SQLCODE -538 SQLSTATE 42830 SQL0577 Explanation: Foreign key attributes do not match parent key. SQL0574 SQLCODE -574 SQLSTATE 42894 Explanation: Attributes of column not valid. SQL0546 SQLCODE -546 SQLSTATE 42621 | Explanation: Library &1 is used incorrectly on the | SET PATH statement SQL0590 SQLCODE -590 SQLSTATE 42734 Explanation: CHECK condition of constraint &1 not valid. SQL0602 SQLCODE -602 SQLSTATE 54008 Explanation: Not authorized to &1. SQL0551 SQLCODE -551 SQLSTATE 42501 Explanation: Name &1 specified in &2 not unique. SQLCODE -580 SQLSTATE 42625 Explanation: Duplicate UNIQUE constraint already exists. Explanation: CHECK constraint &1 cannot be added. SQL0601 SQLCODE -601 SQLSTATE 42710 Explanation: Not authorized to object &1 in &2 type *&3. SQL0604 SQLCODE -604 SQLSTATE 42611 Explanation: Table does not have matching parent key. SQL0607 SQLCODE -607 SQLSTATE 42832 Explanation: Default value not valid. | SQL0585 SQLCODE -585 SQLSTATE 42732 Explanation: INSERT or UPDATE not allowed by CHECK constraint. SQL0557 SQLCODE -557 SQLSTATE 42852 Explanation: More than 120 columns specified for CREATE INDEX. SQL0579 SQLCODE -579 2F004 SQLSTATE 38004. SQL0544 SQLCODE -544 SQLSTATE 23512 Explanation: The results in a CASE expression are not compatible. Appendix B. SQL0543 SQLCODE -543 SQLSTATE 23511 Explanation: At least one result in CASE expression must be not NULL. Explanation: Operation not allowed on system table &1 in &2. Explanation: Modifying SQL data not permitted. SQLCODEs and SQLSTATEs 599 . SQL0581 SQLCODE -581 SQLSTATE 42804 Explanation: Constraint &1 conflicts with SET NULL or SET DEFAULT rule. SQL0539 SQLCODE -539 SQLSTATE 42888 SQLCODE -577 2F002 SQLSTATE 38002. SQL0603 SQLCODE -603 SQLSTATE 23515 Explanation: Privilege not valid for table or view &1 in &2. Explanation: Table does not have primary key. SQL0541 SQLCODE -541 SQLSTATE 42891 SQL0580 Explanation: Reading SQL data not permitted. It is in use. SQL0751 SQLCODE -751 SQLSTATE 42987 Explanation: Foreign key for referential constraint too long. SQL0628 SQLCODE -628 SQLSTATE 42613 | SQL0707 SQLCODE -707 SQLSTATE 42939 | Explanation: Name &1 in &2 not allowed for distinct | type. 600 DB2 UDB for AS/400 SQL Programming V4R4 .SQL0612 SQLCODE -612 SQLSTATE 42711 SQL0666 SQLCODE -666 SQLSTATE 57005 Explanation: &1 is a duplicate column name. SQL0615 SQLCODE -615 SQLSTATE 55006 Explanation: Specified delete rule not allowed with existing trigger. SQL0724 SQLCODE -724 SQLSTATE 54038 Explanation: SET NULL not allowed for referential constraint. SQL0683 SQLCODE -683 SQLSTATE 42842 Explanation: &1 in &2 type &3 cannot be dropped with RESTRICT. SQL0613 SQLCODE -613 SQLSTATE 54008 Explanation: Estimated query processing time exceeds limit. SQL0614 SQLCODE -614 SQLSTATE 54008 Explanation: Foreign key does not match a value in the parent key. Explanation: Case not found for CASE statement. SQL0679 SQLCODE -679 SQLSTATE 57006 Explanation: Object &1 in &2 type *&3 not dropped. SQL0642 SQLCODE -642 SQLSTATE 54021 Explanation: Connection cannot be changed. Reason code is &1. SQL0629 SQLCODE -629 SQLSTATE 42834 | Explanation: Host variable for &2 is NULL. | SQL0658 SQLCODE -658 SQLSTATE 42917 SQL0774 SQLCODE -774 SQLSTATE 2D522 Explanation: Statement cannot be executed within a compound SQL statement. SQL0667 SQLCODE -667 SQLSTATE 23520 Explanation: Primary or unique key constraint too long. SQL0616 SQLCODE -616 SQLSTATE 42893 Explanation: Object &1 in &2 type *&3 not created due to pending operation. Explanation: Table already has primary key. SQL0631 SQLCODE -631 SQLSTATE 54008 Explanation: Too many cascaded trigger programs. SQL0624 SQLCODE -624 SQLSTATE 42889 Explanation: FOR DATA or CCSID clause not valid for specified type. SQL0637 SQLCODE -637 SQLSTATE 42614 Explanation: SQL statement &1 not allowed in stored procedure or trigger. | SQL0713 SQLCODE -713 SQLSTATE 42815 Explanation: Clauses are mutually exclusive. SQL0675 SQLCODE -675 SQLSTATE 42892 Explanation: Length of columns for CREATE INDEX too long. SQL0752 SQLCODE -752 SQLSTATE 0A001 Explanation: Duplicate &1 keyword. | Explanation: Function cannot be dropped. SQL0773 SQLCODE -773 SQLSTATE 20000 Explanation: Maximum number of constraints exceeded. SQL0779 SQLCODE -779 SQLSTATE 42736 Explanation: Consistency tokens do not match. SQL0871 SQLCODE -871 SQLSTATE 54019 Explanation: Too many CCSID values specified. SQL0781 SQLCODE -781 SQLSTATE 42737 Explanation: &1 in &2 type *SQLPKG cannot be accessed. 22504 Explanation: Local program attempted to connect to a remote relational database. SQL0777 SQLCODE -777 SQLSTATE 42919 Explanation: SQL package &1 in &2 not found.SQL0775 SQLCODE -775 SQLSTATE 42910 SQL0803 SQLCODE -803 SQLSTATE 23505 Explanation: Statement not allowed in a compound SQL statement. SQL0802 SQLCODE -802 SQLSTATE 22003. SQL0778 SQLCODE -778 SQLSTATE 428D5 Explanation: Result of SELECT INTO or subquery more than one row. SQL0818 SQLCODE -818 SQLSTATE 51003 Explanation: End label &1 not same as begin label. 22012. SQL0843 SQLCODE -843 SQLSTATE 08003 Explanation: Connection does not exist. SQL0811 SQLCODE -811 SQLSTATE 21000 Explanation: Nested compound statements not allowed. SQL0780 SQLCODE -780 SQLSTATE 428D6 Explanation: Address in SQLDA not valid. SQL0784 SQLCODE -784 SQLSTATE 42860 Explanation: Cannot disconnect relational database due to LU 6. Appendix B. Explanation: Data conversion or data mapping error. SQL0804 SQLCODE -804 SQLSTATE 07002 Explanation: SQLDA not valid. SQL0840 SQLCODE -840 SQLSTATE 54004 Explanation: Condition &1 specified in handler not defined. SQL0782 SQLCODE -782 SQLSTATE 428D7 Explanation: Number of selected items exceeds 8000.2 protected conversation. SQL0776 SQLCODE -776 SQLSTATE 428D4 Explanation: Duplicate key value specified. SQL0858 SQLCODE -858 SQLSTATE 08501 Explanation: Select list for cursor &1 in FOR statement not valid. SQL0827 SQLCODE -827 SQLSTATE 42862 Explanation: UNDO specified for a handler and ATOMIC not specified. SQL0783 SQLCODE -783 SQLSTATE 42738 Explanation: Connection already exists. SQL0785 SQLCODE -785 SQLSTATE 428D8 Explanation: Use of SQLCODE or SQLSTATE not valid. SQL0862 SQLCODE -862 SQLSTATE 55029 Explanation: Check constraint &1 cannot be dropped. SQL0842 SQLCODE -842 SQLSTATE 08002 Explanation: Condition value &1 specified in handler not valid. SQLCODEs and SQLSTATEs 601 . SQL0805 SQLCODE -805 SQLSTATE 51002 Explanation: Cursor &1 specified in FOR statement not allowed. SQL0822 SQLCODE -822 SQLSTATE 51004 Explanation: Label &1 specified on LEAVE statement not valid. 22023. SQL5001 SQLCODE -5001 SQLSTATE 42703 Explanation: SQL system error. SQL5021 SQLCODE -5021 SQLSTATE 42930 Explanation: Package not created. SQL5003 SQLCODE -5003 SQLSTATE 42922 Explanation: Operation not performed because of previous error. SQL0904 SQLCODE -904 SQLSTATE 57011 Explanation: Column qualifier &2 undefined. SQL5012 SQLCODE -5012 SQLSTATE 42618 Explanation: Object &1 in &2 type *&3 has a pending change. SQL0917 SQLCODE -917 SQLSTATE 42969 Explanation: Object name &1 not valid for naming option. It is in use. SQL5047 SQLCODE -5047 SQLSTATE 42616 Explanation: Object &1 in &2 not altered. SQL0907 SQLCODE -907 SQLSTATE 27000 Explanation: Cannot perform operation under commitment control. SQL0951 SQLCODE -951 SQLSTATE 55007 Explanation: Duplicate statement name in DECLARE CURSOR. SQL0910 SQLCODE -910 SQLSTATE 57007 Explanation: Operator &4 not consistent with operands. SQL0913 SQLCODE -913 SQLSTATE 57033 Explanation: Host variable not a numeric with zero scale. SQL5024 SQLCODE -5024 SQLSTATE 42618 Explanation: Host variable &1 not character. 602 DB2 UDB for AS/400 SQL Programming V4R4 . SQL0918 SQLCODE -918 SQLSTATE 51021 Explanation: FOR UPDATE OF column &1 also in ORDER BY. SQL0901 SQLCODE -901 SQLSTATE 58004 Explanation: Referential constraint &4 in check pending state. SQL5016 SQLCODE -5016 SQLSTATE 42833 Explanation: Row or object &1 in &2 type *&3 in use. SQL5051 SQLCODE -5051 SQLSTATE 42875 Explanation: Incorrect qualifier. SQL0950 SQLCODE -950 SQLSTATE 42705 Explanation: Relational database &1 not in relational database directory. SQL0952 SQLCODE -952 SQLSTATE 57014 Explanation: Processing of the SQL statement ended by ENDRDBRQS command. SQL5005 SQLCODE -5005 SQLSTATE 42815 Explanation: Attempt to change same row twice.SQL0900 SQLCODE -900 SQLSTATE 08003 SQL0971 SQLCODE -971 SQLSTATE 57011 Explanation: Application process not in a connected state. SQL0969 SQLCODE -969 SQLSTATE 58033 Explanation: Error processing SRTSEQ or LANGID parameter. SQL5002 SQLCODE -5002 SQLSTATE 42812 Explanation: Resource limit exceeded. SQL0906 SQLCODE -906 SQLSTATE 24514 Explanation: Collection must be specified for table &1. SQL5023 SQLCODE -5023 SQLSTATE 26510 Explanation: Rollback required. Explanation: Unexpected client driver error. SQL7033 SQLCODE -7033 SQLSTATE 42923 Explanation: Logical file &1 in &2 not valid for CREATE VIEW. SQ30000 SQLCODE -30000 SQLSTATE 58008 Explanation: User &1 not the same as current user &2 for connect to local relational database. Explanation: Call to distributed SQL program not allowed. SQL7024 SQLCODE -7024 SQLSTATE 42876 Explanation: Distributed Relational Database Architecture (DRDA) protocol error. SQL7027 SQLCODE -7027 SQLSTATE 42984 Explanation: Override parameter not valid. | SQL7034 SQLCODE -7034 SQLSTATE 42926 Explanation: &1 in &2 not table. SQL7003 SQLCODE -7003 SQLSTATE 42857 Explanation: Unable to grant to a view. SQL7007 SQLCODE -7007 SQLSTATE 51009 Explanation: New name &3 is not valid. SQL9012 SQLCODE -9012 SQLSTATE 42968 Explanation: Local program attempting to run on application server. SQL7022 SQLCODE -7022 SQLSTATE 42977 Explanation: DB2 UDB Query Manager and SQL Development Kit not available. SQL7002 SQLCODE -7002 SQLSTATE 42847 Explanation: Auxiliary storage pool not found. view. or physical file. SQL7006 SQLCODE -7006 SQLSTATE 55018 Explanation: Unable to CHGOBJOWN for primary group. SQL7010 SQLCODE -7010 SQLSTATE 42850 Explanation: SQL procedure &1 in &2 not created. | SQL7037 SQLCODE -7037 SQLSTATE 42835 Explanation: Commitment control is already active to a DDM target. SQ30001 SQLCODE -30001 SQLSTATE 57042 Explanation: Index cannot be created because of CCSID incompatibility. SQL7032 SQLCODE -7032 SQLSTATE 42904 Explanation: &1 in &2 not valid for operation. SQL7028 SQLCODE -7028 SQLSTATE 42944 Explanation: File &1 in &2 has more than one format. SQL7017 SQLCODE -7017 SQLSTATE 42971 | Explanation: LOB locators are not allowed with | COMMIT(*NONE). Appendix B.SQL7001 SQLCODE -7001 SQLSTATE 42858 SQL7026 SQLCODE -7026 SQLSTATE 42896 Explanation: File &1 in &2 not database file. SQL7008 SQLCODE -7008 SQLSTATE 55019 Explanation: Sort sequence table &1 too long. SQLCODEs and SQLSTATEs 603 . SQL7021 SQLCODE -7021 SQLSTATE 57043 Explanation: Application process not at commit boundary. SQL7018 SQLCODE -7018 SQLSTATE 42970 | Explanation: Data in a distributed file &1 in &2 cannot | be redistributed. SQL7029 SQLCODE -7029 SQLSTATE 428B8 Explanation: Cannot drop collection &1. SQL7031 SQLCODE -7031 SQLSTATE 54044 Explanation: COMMIT or ROLLBACK not valid. SQL7011 SQLCODE -7011 SQLSTATE 42851 Explanation: Alias name &1 in &2 not allowed. SQL7941 SQLCODE -7941 SQLSTATE 42981 Explanation: COMMIT HOLD or ROLLBACK HOLD not allowed. SQ30053 SQLCODE -30053 SQLSTATE 42506 Explanation: Not authorized to create package for owner &1. Explanation: Program preparation assumptions not correct. SQ30071 SQLCODE -30071 SQLSTATE 58015 Explanation: Distributed Data Management (DDM) object &1 not supported. SQ30051 SQLCODE -30051 SQLSTATE 58012 Explanation: Communication error occurred during DB2 Multisystem processing. Explanation: Bind process for specified package name and consistency token not active. SQ30060 SQLCODE -30060 SQLSTATE 08004 Explanation: User not authorized to relational database &1. SQ30089 SQLCODE -30089 SQLSTATE 08001 Explanation: DDM command &1 is not valid while bind process is in progress. SQ30052 SQLCODE -30052 SQLSTATE 42932 Explanation: Change request not valid for read-only application server. SQ30021 SQLCODE -30021 SQLSTATE 58010 Explanation: Distributed Data Management (DDM) parameter &1 not supported. 2D529 SQLSTATE 25000. SQ30070 SQLCODE -30070 SQLSTATE 58014 Explanation: Distributed Data Management (DDM) command &1 not supported. SQ30080 SQLCODE -30080 SQLSTATE 08001 Explanation: DDM resources at relational database &1 not available. 604 DB2 UDB for AS/400 SQL Programming V4R4 . SQ30074 SQLCODE -30074 SQLSTATE 58018 Explanation: DDM resource &2 at relational database &1 not available. SQ30073 SQLCODE -30073 SQLSTATE 58017 Explanation: Distributed relational database not supported by the remote system.SQ30020 SQLCODE -30020 SQLSTATE 58009 SQ30072 SQLCODE -30072 SQLSTATE 58016 Explanation: Distributed Relational Database Architecture (DRDA) protocol error. SQ30061 SQLCODE -30061 SQLSTATE 08004 Explanation: Relational database &1 not found. SQ30041 SQLCODE -30041 SQLSTATE 57013 Explanation: Distributed Data Management (DDM) reply message &1 not supported. SQ30090 SQLCODE -30090 2D528. SQ30040 SQLCODE -30040 SQLSTATE 57012 Explanation: Distributed Data Management (DDM) parameter value &1 not supported. SQ30050 SQLCODE -30050 SQLSTATE 58011 Explanation: Communication error occurred during distributed database processing. ILE RPG for AS/400. 1999 3 4 5 This SQL DECLARE CURSOR statement defines cursor C1. Sample Programs Using DB2 UDB for AS/400 Statements This appendix contains a sample application showing how to code SQL statements in each of the languages supported by the DB2 UDB for AS/400 system: ILE C. The updated rows are those that have employee commissions greater than 2000. all employees working on the project who received a raise. For REXX. the SQL precompiler automatically places the SQLCA data structure into the source at the end of the Input specification section. REXX does not support the retrieval of external definitions. The first part of the report shows. For RPG programs. 1997. is the default. The following notes apply to all the sample programs: SQL statements can be entered in upper or lowercase. this is PREPARE and EXECUTE since UPDATE cannot be executed directly if there is a host variable. 1 This host language statement retrieves the external definitions for the SQL table PROJECT. COBOL.) 6 © Copyright IBM Corp. and COBOL programs. These definitions can be used as host variables or as a host structure. which contains the employee salary by the percentage in the host variable PERCENTAGE (PERCNT for RPG). Each sample program produces the same report. 2. REXX does not support the WHENEVER statement. C. *CHG. Notes: 1. Note: The program was precompiled using COMMIT(*CHG). PL/I. 2 The SQL INCLUDE SQLCA statement is used to include the SQLCA for PL/I. For REXX. which joins 605 . ILE COBOL. the SQLCA fields are maintained in separate variables rather than in a contiguous data area mapped by the SQLCA. Instead. REXX uses the SIGNAL ON ERROR facility. Examples of programs that use SQL statements The sample application gives raises based on commission. This SQL WHENEVER statement defines the host language label to which control is passed if an SQLERROR (SQLCODE < 0) occurs in an SQL statement. In RPG for AS/400. field names in an externally described structure that are longer than 6 characters must be renamed. (For REXX. and REXX. This SQL COMMIT statement commits the changes made by the SQL UPDATE statement. by project. Record locks on all changed rows are released.Appendix C. This SQL UPDATE statement updates the SALARY column. The second part of the report shows the new salary expense for each project. RPG for AS/400. This WHENEVER SQLERROR statement applies to all the following SQL statements until the next WHENEVER SQLERROR statement is encountered. which is shown at the end of this appendix. This SQL FETCH statement returns all columns for cursor C1 and places the returned values into the corresponding elements of the host structure. 9 10 11 12 13 14 SQL Statements in ILE C and C++ Programs This sample program is written in the C programming language. and returns rows for employees who received a raise (commission > 2000). 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. SQL statements until the next WHENEVER SQLERROR statement is encountered. The COUNT function returns the number of rows in each group. This SQL WHENEVER statement with the CONTINUE option causes processing to continue to the next statement regardless if an error occurs on the SQL ROLLBACK statement. After all rows are fetched. The results are grouped by columns PROJNO and PROJNAME. 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. 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. PROJECT. REXX uses the SIGNAL OFF ERROR facility. This SQL WHENEVER statement defines the host language label to which control is passed when all rows are fetched (SQLCODE = 100). EMP_ACT. This SQL ROLLBACK statement restores the table to its original condition if an error occurred during the update. REXX does not support the WHENEVER statement. For REXX. For REXX. which joins the three tables. the SQLCODE must be explicitly checked. this prevents the program from going into a loop if an error does occur. The ORDER BY 1 clause specifies that rows are retrieved based on the contents of the final results column (EMP_ACT. For REXX. Instead. and EMPLOYEE. EMPLOYEE and EMP_ACT. Rows are returned in ascending order by project number and employee number (PROJNO and EMPNO columns). control is passed to this label. The same program would work in C++ if the following conditions are true: v An SQL BEGIN DECLARE SECTION statement was added before line 18 v An SQL END DECLARE SECTION statement was added after line 42 606 DB2 UDB for AS/400 SQL Programming V4R4 . however. 7 8 This SQL OPEN statement opens cursor C1 so that the rows can be fetched.two tables. The SUM function calculates the new salary cost for each project. The SQL CLOSE statement closes cursor C1.PROJNO). This SQL DECLARE CURSOR statement defines cursor C2. Errors are not expected on the SQL ROLLBACK statement. ...............CEX To source file...........................*DUW Default Collection....*JOB IBM SQL flagging....*OBJLIB/*OBJ Created object type........*NONE Text.................................65535 Job CCSID............. Sample Programs Using DB2 UDB for AS/400 Statements 607 ..*YES Relational database.....*YES Close SQL cursor...........CORPDATA/CEX Source file...................QTEMP/QSQLTEMP Options............C Object name................................................................*CURRENT RDB connect method..................*JOB Date separator..5769ST1 V4R4M0 990521 Create SQL ILE C Object Source type......*LOCAL User ..*XREF Listing option............*LIBL/*SRCFILE Commit.. Sample C Program Using SQL Statements (Part 1 of 7) Appendix C.........*PRINT Target release..................CORPDATA/SRC Member....*JOB Replace.........*NAMING Sort Sequence................10 Margins.*SRCMBRTXT Source file CCSID....*ENDACTGRP Allow blocking.*USER User Profile..........65535 Source member changed on 04/01/98 17:15:17 CEX 04/01/98 15:52:26 Page 1 Figure 39.........*NONE Package name.............*HMS Time separator .........*PGM Debugging view...........*JOB Language ID...........................*READ Delay PREPARE.....V4R4M0 INCLUDE file.........................*LIBL/QSYSPRT Date format.*NO Generation level..........*JOB Time format..............*NONE Dynamic User Profile.*SRCFILE Printer file..............................*NOFLAG ANS flagging..*CHG Allow copy of data........................ .00.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 V4R4M0 990521 Create SQL ILE C Object CEX *.+.+. EXEC SQL WHENEVER SQLERROR GO TO report_error.+.. char empno??(7??).. /* Report the updated statistics for each employee assigned to the */ /* selected projects. 2 . 4 ." REPORT OF PROJECTS AFFECTED \ 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 2 Figure 39."CORPDATA/PROJECT(PROJECT)". float salary. 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. /* effective raise date /* File declaration for qprint */ FILE *qprint.. Sample C Program Using SQL Statements (Part 2 of 7) 608 DB2 UDB for AS/400 SQL Programming V4R4 . /* Structure for report 2 */ struct { char projno??(7??).. char project_name??(37??). /* Structure for report 1 */ 1 #pragma mapinc ("project".+. ROLLBACK the changes. */ /* 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. 8 #include "string. char name??(30??).04. 5 . double total_proj_cost. 7 .h" #include "stdlib..... If an error */ occurs during the update...h" #include "stdio. /* work days during in one year float commission = 2000.."w"). */ */ */ */ /* Commit changes */ 5 EXEC SQL COMMIT.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'. */ /* Write out the header for Report 1 */ fprintf(qprint.... /* /* 3 4 Update the selected projects by the new percentage.."both".. 1 ."p z") #include "project" struct { CORPDATA_PROJECT_PROJECT_both_t Proj_struct.... 2 exec sql include SQLCA. short employee_count... } rpt1.+.. 3 ....+.. /* cutoff to qualify for raise float percentage = 1.+.. */ EXEC SQL WHENEVER SQLERROR GO TO update_error. } rpt2. qprint=fopen("QPRINT"..+. EXEC SQL UPDATE CORPDATA/EMPLOYEE SET SALARY = SALARY * :percentage WHERE COMM >= :commission ... */ short work_days = 253. /* raised salary as percentage char raise_date??(12??) = "1982-06-01". 6 .. fprintf(qprint. CORPDATA/PROJECT. 7 .rpt1. 5 . 11 EXEC SQL DECLARE C2 CURSOR FOR SELECT EMP_ACT.. '||firstnme.salary).e. fprintf(qprint. 8 BY RAISES").. lastname||'. empno."\n%6s %6s %-30s %8. Sample C Program Using SQL Statements (Part 3 of 7) Appendix C. do { 10 EXEC SQL FETCH C1 INTO :Proj_struct. rpt1.PROJNO and EMP_ACT. EXEC SQL OPEN C2.salary.. those projects potentially affected by the salary raises) generate a report containing the project number. " SALARY\n"). "\nNUMBER PROJECT NAME \ EMPLOYEES COST\n"). SUM ( ( DAYS(EMENDATE) .. CORPDATA/EMPLOYEE WHERE EMP_ACT.+. do { 12 EXEC SQL FETCH C2 INTO :rpt2. :rpt1.. "\n\nPROJECT \ NUMBER OF TOTAL"). emp_act. fprintf(qprint.+.+.. fprintf(qprint..empno. 7 EXEC SQL OPEN C1..+.DAYS(EMSTDATE) ) * EMPTIME * (DECIMAL( SALARY / :work_days .2f".. /* Fetch and write the rows to QPRINT */ EXEC SQL WHENEVER NOT FOUND GO TO done2.PROJNO. done1: EXEC SQL CLOSE C1.2))) FROM CORPDATA/EMP_ACT..rpt1.. /* /* /* /* /* For all projects ending at a date later than the 'raise_date' (i..PROJNO.Proj_struct..."\n\nPROJECT EMPID EMPLOYEE NAME ")..+. * / */ */ */ */ /* Write out the header for Report 2 */ fprintf(qprint.empno and comm >= :commission order by projno.. Sample Programs Using DB2 UDB for AS/400 Statements 609 ..:rpt1. 2 . fprintf(qprint.+. 4 . project name the count of employees participating in the project and the total salary cost of the project. salary from corpdata/emp_act.name..empno = employee.empno.. :rpt1.. 6 ......EMPNO and PRENDATE > :raise_date GROUP BY EMP_ACT.. COUNT(*).+. 6 exec sql declare c1 cursor for select distinct projno.PROJNO. PROJNAME.. /* Fetch and write the rows to QPRINT */ 8 EXEC SQL WHENEVER NOT FOUND GO TO done1. 1 ..8. 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 3 Figure 39.EMPNO =EMPLOYEE.PROJNO=PROJECT. } while (SQLCODE==0).+. 3 .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 V4R4M0 990521 Create SQL ILE C Object CEX *....."\n\n\n ACCUMULATED STATISTICS\ BY PROJECT").name. corpdata/employee where emp_act. PROJNAME ORDER BY 1.PROJNO. rpt1.empno. .project_name.. /* All done */ finished: fclose(qprint)... SQLCODE=" "%5d\n"..+.+.. fprintf(qprint. " "SQLCODE=%5d\n"... goto finished. 3 ... } while (SQLCODE==0). } * E N D O F S O U R C E * * * * * */ 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 4 Figure 39. 4 ..2f".rpt2.. Inform user and rollback */ /* changes.+. goto finished..... 7 .projno. 1 .+... Inform user and exit.. */ update_error: 13 EXEC SQL WHENEVER SQLERROR CONTINUE. rpt2. 6 . goto finished..rpt2....SQLCODE).total_proj_cost).+.+. 8 fprintf(qprint.. rpt2.employee_count. /* Error occured while updating table. /* Error occured while generating reports...+..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 * * * * V4R4M0 990521 Create SQL ILE C Object CEX *.."*** ERROR Occurred while generating reports...+. report_error: fprintf(qprint."\n%6s %-36s %6d %9.SQLCODE). Sample C Program Using SQL Statements (Part 4 of 7) 610 DB2 UDB for AS/400 SQL Programming V4R4 . 2 . 5 . exit(0). done2: EXEC SQL CLOSE C2. 14 EXEC SQL ROLLBACK.."*** ERROR Occurred while updating table.. 5769ST1 V4R4M0 990521 CROSS REFERENCE Data Names commission done1 done2 employee_count empno name percentage project_name projno raise_date report_error rpt1 rpt2 salary total_proj_cost update_error work_days ACTNO BIRTHDATE BONUS COMM COMM CORPDATA C1 C2 DEPTNO DEPTNO EDLEVEL EMENDATE EMENDATE EMP_ACT EMP_ACT Create SQL ILE C Object Define 19 **** **** 40 31 32 20 39 38 21 **** 34 42 33 41 **** 18 74 74 74 **** 74 **** 71 112 27 116 74 74 **** **** **** CEX 04/01/98 15:52:26 Page 5 Reference FLOAT(24) 54 75 LABEL 81 LABEL 126 SMALL INTEGER PRECISION(4.EMP_ACT COLUMN 114 TABLE 72 75 113 117 118 120 TABLE IN CORPDATA 74 116 Figure 39.0) COLUMN (NOT NULL) IN CORPDATA.EMP_ACT DATE(10) COLUMN IN CORPDATA.2) COLUMN IN CORPDATA.EMPLOYEE DECIMAL(9.PROJECT SMALL INTEGER PRECISION(4.0) COLUMN (NOT NULL) IN CORPDATA. Sample C Program Using SQL Statements (Part 5 of 7) Appendix C.EMPLOYEE COLUMN 54 75 DECIMAL(9. Sample Programs Using DB2 UDB for AS/400 Statements 611 .2) COLUMN IN CORPDATA.EMPLOYEE DATE(10) 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.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. 5769ST1 V4R4M0 990521 CROSS REFERENCE EMPLOYEE EMPLOYEE EMPNO EMPNO EMPNO EMPNO EMPTIME EMPTIME EMSTDATE EMSTDATE FIRSTNME FIRSTNME HIREDATE JOB LASTNAME LASTNAME MAJPROJ MAJPROJ MIDINIT Proj_struct PHONENO PRENDATE PRENDATE PRENDATE PROJECT PROJECT PROJNAME PROJNAME PROJNAME PROJNO PROJNO PROJNO PROJNO Create SQL ILE C Object **** **** **** **** 74 74 74 **** 74 **** **** 74 74 74 **** 74 27 116 74 30 74 27 **** 116 **** **** 27 **** 116 27 **** 74 **** CEX 04/01/98 15:52:26 Page 6 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. Sample C Program Using SQL Statements (Part 7 of 7) 612 DB2 UDB for AS/400 SQL Programming V4R4 .2) COLUMN IN CORPDATA.2) IN Proj_struct DECIMAL(5.EMPLOYEE STRUCTURE IN rpt1 CHARACTER(4) COLUMN IN CORPDATA.EMPLOYEE CHARACTER(3) COLUMN IN CORPDATA.PROJECT DATE(10) IN Proj_struct DATE(10) COLUMN IN CORPDATA.PROJECT CHARACTER(1) COLUMN (NOT NULL) IN CORPDATA.2) COLUMN IN CORPDATA.PROJECT VARCHAR(6) IN Proj_struct 85 COLUMN 72 76 CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE * * * * * Figure 39.PROJECT VARCHAR(6) IN Proj_struct CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.2) COLUMN IN CORPDATA.EMPLOYEE DECIMAL(5.EMP_ACT COLUMN IN EMP_ACT Figure 39.EMPLOYEE CHARACTER(8) COLUMN IN CORPDATA.EMP_ACT COLUMN 114 DATE(10) COLUMN IN CORPDATA.EMPLOYEE DATE(10) IN Proj_struct COLUMN 119 DATE(10) COLUMN IN CORPDATA.EMPLOYEE CHARACTER(1) COLUMN IN CORPDATA.EMP_ACT CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMP_ACT COLUMN 114 COLUMN 73 VARCHAR(12) COLUMN (NOT NULL) IN CORPDATA. Sample C Program Using SQL Statements (Part 6 of 7) 5769ST1 V4R4M0 990521 CROSS REFERENCE PROJNO PROJNO PRSTAFF PRSTAFF PRSTDATE PRSTDATE RESPEMP RESPEMP SALARY SALARY SEX WORKDEPT No errors found in source 163 Source records processed * * * * * E N D O F L I S T I Create SQL ILE C Object **** 116 27 116 27 116 27 116 **** 74 74 74 N G CEX 04/01/98 15:52:26 Page 7 113 117 120 COLUMN IN PROJECT 117 CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE VARCHAR(6) IN Proj_struct CHARACTER(6) COLUMN IN CORPDATA.PROJECT COLUMN 53 53 73 115 DECIMAL(9.PROJECT TABLE IN CORPDATA 116 TABLE 117 VARCHAR(24) IN Proj_struct COLUMN 113 120 VARCHAR(24) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE DATE(10) COLUMN IN CORPDATA.EMPLOYEE COLUMN 73 VARCHAR(15) COLUMN (NOT NULL) IN CORPDATA.PROJECT DECIMAL(5. .............*ENDPGM Allow blocking.....*CURRENT RDB connect method..CORPDATA/SRC Member..*LOCAL User ..........................*JOB Time format....*SRC *XREF Target release.............*JOB IBM SQL flagging..............*YES Close SQL cursor.*HMS Time separator ...*NONE Package name..QTEMP/QSQLTEMP Options............................................10 Printer file.......................CBLEX To source file....*LIBL/QSYSPRT Date format...*NO Generation level........V4R4M0 INCLUDE file........65535 Job CCSID...................*JOB Language ID..*USER User Profile....................*LIBL/*SRCFILE Commit..................*CHG Allow copy of data.............*PGMLIB/*PGM Dynamic User Profile....................................... Sample Programs Using DB2 UDB for AS/400 Statements 613 ............*JOB Date separator.. Sample COBOL Program Using SQL Statements (Part 1 of 9) Appendix C..................................*DUW Default Collection..................65535 Source member changed on 07/01/96 09:44:58 CBLEX 04/01/98 11:09:13 Page 1 Figure 40.*SRCMBRTXT Source file CCSID...................*NONE Text.......SQL Statements in COBOL and ILE COBOL Programs 5769ST1 V4R4M0 990521 Create SQL COBOL Program Source type.............*NAMING Sort Sequence.......*YES Relational database.....................*JOB Replace.........*READ Delay PREPARE...COBOL Program name..............CORPDATA/CBLEX Source file..............*NOFLAG ANS flagging. .... 24 INPUT-OUTPUT SECTION. 31 32 FILE SECTION. 37 01 PRINT-RECORD PIC X(132). 43 77 COMMISSION PIC S99999V99 PACKED-DECIMAL VALUE 2000.. 51 05 EMPNO PIC X(6)..5769ST1 V4R4M0 990521 Create SQL COBOL Program CBLEX Record *.. IBM-AS400.. 64 15 TOTAL-PROJ-COST PIC S9(10)V99 PACKED-DECIMAL. A report is generated showing the projects * 8 * which these employees have contributed to ordered by the * 9 * project number and employee ID. CBLEX.. 2 . 25 26 FILE-CONTROL.+.... A second report shows each * 10 * project having an end date occurring after RAISE-DATE * 11 * (i..... 29 30 DATA DIVISION. * 47 *************************************************************** 48 49 1 01 RPT1.. 61 15 PROJNO PIC X(6).. The salaries of those who * 6 * qualify are increased by the value of PERCENTAGE retroactive * 7 * to RAISE-DATE. Sample COBOL Program Using SQL Statements (Part 2 of 9) 614 DB2 UDB for AS/400 SQL Programming V4R4 .. 18 19 PROGRAM-ID. 52 05 NAME PIC X(30). * 58 *************************************************************** 59 60 01 RPT2.+. 21 CONFIGURATION SECTION. 3 .e... IBM-AS400. 5 .+. 42 77 PERCENTAGE PIC S999V99 PACKED-DECIMAL. 50 COPY DDS-PROJECT OF CORPDATA-PROJECT. 41 77 RAISE-DATE PIC X(11) VALUE "1982-06-01"....+.00.. 6 . 20 ENVIRONMENT DIVISION... 4 . 38 39 WORKING-STORAGE SECTION.. 40 77 WORK-DAYS PIC S9(4) BINARY VALUE 253.+. 1 . 54 55 56 *************************************************************** 57 * Structure for report 2.. 44 45 *************************************************************** 46 * Structure for report 1. 7 . 53 05 SALARY PIC S9(6)V99 PACKED-DECIMAL. 63 15 EMPLOYEE-COUNT PIC S9(4) BINARY. 62 15 PROJECT-NAME PIC X(36)..+.+. 33 34 FD PRINTFILE 35 BLOCK CONTAINS 1 RECORDS 36 LABEL RECORDS ARE OMITTED. potentially affected by the retroactive raises ) with * 12 * its total salary expenses and a count of employees who * 13 * contributed to the project.+. * 14 **************************************************************** 15 16 17 IDENTIFICATION DIVISION. 8 1 2 **************************************************************** 3 * A sample program which updates the salaries for those * 4 * employees whose current commission total is greater than or * 5 * equal to the value of COMMISSION. 65 SEQNBR 04/01/98 11:09:13 Last change Page 2 Figure 40... 23 OBJECT-COMPUTER. 27 SELECT PRINTFILE ASSIGN TO PRINTER-QPRINT 28 ORGANIZATION IS SEQUENTIAL. 22 SOURCE-COMPUTER. 8 66 2 EXEC SQL 67 INCLUDE SQLCA 68 END-EXEC.+.+. 108 05 FILLER PIC X(96) VALUE SPACES. 120 121 A000-MAIN. 83 10 FILLER PIC X(35) VALUE "EMPLOYEE NAME"... * 73 *************************************************************** 74 75 01 RPT1-HEADERS... 114 05 EMPLOYEE-COUNT PIC ZZZ9... 95 05 RPT2-HEADER3.5769ST1 V4R4M0 990521 Create SQL COBOL Program CBLEX Record *. 106 05 FILLER PIC X(3) VALUE SPACES. 97 10 FILLER PIC X(38) VALUE "PROJECT NAME". 4 .+.. 3 . 98 10 FILLER PIC X(16) VALUE "EMPLOYEES". 5 .. 122 MOVE 1. Sample COBOL Program Using SQL Statements (Part 3 of 9) Appendix C. 70 71 *************************************************************** 72 * Headers for reports. 110 05 PROJNO PIC X(6).. 86 05 RPT2-HEADER1. 115 05 FILLER PIC X(5) VALUE SPACES..99... 118 119 PROCEDURE DIVISION.+. 7 . 104 05 FILLER PIC X(4) VALUE SPACES. 69 77 CODE-EDIT PIC ---99. 105 05 NAME PIC X(30).. 112 05 PROJECT-NAME PIC X(36). 117 05 FILLER PIC X(56) VALUE SPACES... 92 10 FILLER PIC X(38) VALUE SPACES.. 102 05 FILLER PIC XXX VALUE SPACES.. 85 01 RPT2-HEADERS. 81 10 FILLER PIC X(9) VALUE "PROJECT". 94 10 FILLER PIC X(10) VALUE "TOTAL"..+. 80 05 RPT1-HEADER2.. 93 10 FILLER PIC X(16) VALUE "NUMBER OF". 103 05 EMPNO PIC X(6). 113 05 FILLER PIC X(4) VALUE SPACES. 99 10 FILLER PIC X(65) VALUE "COST". 101 05 PROJNO PIC X(6). 78 10 FILLER PIC X(111) 79 VALUE "REPORT OF PROJECTS AFFECTED BY RAISES". 100 01 RPT1-DATA. 88 10 FILLER PIC X(111) 89 VALUE "ACCUMULATED STATISTICS BY PROJECT".+. * 128 *************************************************************** 129 130 3 EXEC SQL SEQNBR 04/01/98 11:09:13 Last change Page 3 Figure 40. 2 .. If an * 127 * error occurs during the update. 82 10 FILLER PIC X(10) VALUE "EMPID". 96 10 FILLER PIC X(9) VALUE "NUMBER". 84 10 FILLER PIC X(40) VALUE "SALARY".. 109 01 RPT2-DATA.. 123 OPEN OUTPUT PRINTFILE.. 76 05 RPT1-HEADER1. ROLLBACK the changes. Sample Programs Using DB2 UDB for AS/400 Statements 615 .+.+.04 TO PERCENTAGE. 124 125 *************************************************************** 126 * Update the selected employees by the new percentage.99.. 87 10 FILLER PIC X(21) VALUE SPACES. 77 10 FILLER PIC X(21) VALUE SPACES.... 111 05 FILLER PIC XXX VALUE SPACES.. 90 05 RPT2-HEADER2.... 6 . 116 05 TOTAL-PROJ-COST PIC ZZZZZZZZ9. 107 05 SALARY PIC ZZZZZ9. 91 10 FILLER PIC X(9) VALUE "PROJECT". 1 .. +.. Figure 40.. 133 4 EXEC SQL 134 UPDATE CORPDATA/EMPLOYEE 135 SET SALARY = SALARY * :PERCENTAGE 136 WHERE COMM >= :COMMISSION 137 END-EXEC....... * 158 *************************************************************** 159 160 write print-record from rpt1-header1 161 before advancing 2 lines. empno 172 end-exec.+.empno. 2 .. 138 139 *************************************************************** 140 * Commit changes.salary 168 from corpdata/emp_act. Sample COBOL Program Using SQL Statements (Part 4 of 9) 616 DB2 UDB for AS/400 SQL Programming V4R4 ... 3 . 150 151 *************************************************************** 152 * Report the updated statistics for each employee receiving * 153 * a raise and the projects that s/he participates in * 154 *************************************************************** 155 156 *************************************************************** 157 * Write out the header for Report 1..+. 5 .. 4 ..+... 176 177 PERFORM B000-GENERATE-REPORT1 THRU B010-GENERATE-REPORT1-EXIT 178 UNTIL SQLCODE NOT EQUAL TO ZERO. those projects potentially affected by the * 188 * salary raises generate a report containing the project * 189 * project number.5769ST1 V4R4M0 990521 Create SQL COBOL Program CBLEX Record *.. "||firstnme . 167 lastname||". 7 .. 181 EXEC SQL 182 CLOSE C1 183 END-EXEC. 146 147 EXEC SQL 148 WHENEVER SQLERROR GO TO E020-REPORT-ERROR 149 END-EXEC.. 8 131 WHENEVER SQLERROR GO TO E010-UPDATE-ERROR 132 END-EXEC. 173 7 EXEC SQL 174 OPEN C1 175 END-EXEC..... corpdata/employee 169 where emp_act. * 141 *************************************************************** 142 143 5 EXEC SQL 144 COMMIT 145 END-EXEC. 1 . emp_act. 162 write print-record from rpt1-header2 163 before advancing 1 line.* 187 * DATE ( i... 164 6 exec sql 165 declare c1 cursor for 166 SELECT DISTINCT projno. 179 180 10 A100-DONE1.empno =employee.. project name. 6 ...+.+.empno and 170 comm >= :commission 171 order by projno.+.+.e. 184 185 ************************************************************* 186 * For all projects ending at a date later than the RAISE..... the count of employees * 190 * participating in the project and the total salary cost * 191 * for the project * 192 ************************************************************* 193 194 195 *************************************************************** SEQNBR 04/01/98 11:09:13 Last change Page 4 Note: 8 and 9 are located on Part 5 of this figure. ...NAME........ :RPT1. PROJNAME.+.8. 249 9 EXEC SQL 250 FETCH C1 INTO :PROJECT.PROJNO. PROJNAME 219 ORDER BY 1 220 END-EXEC. 214 CORPDATA/EMPLOYEE 215 WHERE EMP_ACT. 246 8 EXEC SQL 247 WHENEVER NOT FOUND GO TO A100-DONE1 248 END-EXEC. 2 .+... CORPDATA/PROJECT.+. 259 EXIT. 254 MOVE PROJNO OF RPT1 TO PROJNO OF RPT1-DATA.. * 243 *************************************************************** 244 245 B000-GENERATE-REPORT1. 257 258 B010-GENERATE-REPORT1-EXIT. 203 WRITE PRINT-RECORD FROM RPT2-HEADER2 204 BEFORE ADVANCING 1 LINE.+.EMPNO =EMPLOYEE. 227 228 A200-DONE2.PROJNO. 4 . 201 WRITE PRINT-RECORD FROM RPT2-HEADER1 202 BEFORE ADVANCING 2 LINES..+. 205 WRITE PRINT-RECORD FROM RPT2-HEADER3 206 BEFORE ADVANCING 2 LINES. COUNT(*). Sample Programs Using DB2 UDB for AS/400 Statements 617 . 1 . 211 SUM ( (DAYS(EMENDATE)-DAYS(EMSTDATE)) * 212 EMPTIME * DECIMAL((SALARY / :WORK-DAYS)..+. 260 SEQNBR 04/01/98 11:09:13 Last change Page 5 Figure 40. 239 STOP RUN. 240 241 *************************************************************** 242 * Fetch and write the rows to PRINTFILE.+.EMPNO. 224 225 PERFORM C000-GENERATE-REPORT2 THRU C010-GENERATE-REPORT2-EXIT 226 UNTIL SQLCODE NOT EQUAL TO ZERO....... 5 . 238 CLOSE PRINTFILE. * 235 *************************************************************** 236 237 A900-MAIN-EXIT..PROJNO AND 216 EMP_ACT.. 251 :RPT1. 255 WRITE PRINT-RECORD FROM RPT1-DATA 256 BEFORE ADVANCING 1 LINE. 229 EXEC SQL 230 CLOSE C2 231 END-EXEC 232 233 *************************************************************** 234 * All done. 6 . 3 ... 200 WRITE PRINT-RECORD BEFORE ADVANCING 2 LINES.... 253 MOVE CORRESPONDING RPT1 TO RPT1-DATA.PROJNO.2)) 213 FROM CORPDATA/EMP_ACT. 7 ..SALARY 252 END-EXEC..+. 207 208 EXEC SQL 209 11 DECLARE C2 CURSOR FOR 210 SELECT EMP_ACT.PROJNO=PROJECT.. :RPT1.5769ST1 V4R4M0 990521 Create SQL COBOL Program CBLEX Record *. Sample COBOL Program Using SQL Statements (Part 5 of 9) Appendix C. 221 EXEC SQL 222 OPEN C2 223 END-EXEC.EMPNO AND 217 PRENDATE > :RAISE-DATE 218 GROUP BY EMP_ACT. 8 196 * Write out the header for Report 2.. * 197 *************************************************************** 198 199 MOVE SPACES TO PRINT-RECORD. . 306 WRITE PRINT-RECORD.+.. * 300 *************************************************************** 301 302 E020-REPORT-ERROR.+. 272 MOVE CORRESPONDING RPT2 TO RPT2-DATA. 5 . 3 . 8 261 *************************************************************** 262 * Fetch and write the rows to PRINTFILE...... 288 MOVE SQLCODE TO CODE-EDIT. 277 EXIT. 7 . 273 WRITE PRINT-RECORD FROM RPT2-DATA 274 BEFORE ADVANCING 1 LINE.... 304 STRING "*** ERROR Occurred while generating reports.... 285 13 EXEC SQL 286 WHENEVER SQLERROR CONTINUE 287 END-EXEC. 269 12 EXEC SQL 270 FETCH C2 INTO :RPT2 271 END-EXEC... SQLCODE=" 290 CODE-EDIT DELIMITED BY SIZE INTO PRINT-RECORD. 292 14 EXEC SQL 293 ROLLBACK 294 END-EXEC....+.. 291 WRITE PRINT-RECORD. 296 297 *************************************************************** 298 * Error occured while generating reports. 295 STOP RUN. Inform user and * 299 * exit. 6 .+. 275 276 C010-GENERATE-REPORT2-EXIT.+. Sample COBOL Program Using SQL Statements (Part 6 of 9) 618 DB2 UDB for AS/400 SQL Programming V4R4 .+. * 282 *************************************************************** 283 284 E010-UPDATE-ERROR.....5769ST1 V4R4M0 990521 Create SQL COBOL Program CBLEX Record *. 303 MOVE SQLCODE TO CODE-EDIT. 1 . 2 .+... 4 . Inform user and * 281 * rollback changes. 307 STOP RUN....+. SQLCODE 305 "=" CODE-EDIT DELIMITED BY SIZE INTO PRINT-RECORD.. 266 EXEC SQL 267 WHENEVER NOT FOUND GO TO A200-DONE2 268 END-EXEC. * 263 *************************************************************** 264 265 C000-GENERATE-REPORT2. 289 STRING "*** ERROR Occurred while updating table... 278 279 *************************************************************** 280 * Error occured while updating table. * * * * * E N D O F S O U R C E * * * * * SEQNBR 04/01/98 11:09:13 Last change Page 6 Figure 40.. EMPLOYEE DATE(10) COLUMN 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 LABEL 247 LABEL 267 DATE(10) COLUMN IN CORPDATA.0) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE DECIMAL(9.EMP_ACT Figure 40.EMPLOYEE COLUMN 136 170 DECIMAL(9. Sample COBOL Program Using SQL Statements (Part 7 of 9) Appendix C.2) COLUMN IN CORPDATA.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.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.2) COLUMN IN CORPDATA.EMPLOYEE DECIMAL(7. Sample Programs Using DB2 UDB for AS/400 Statements 619 .2) COLUMN IN CORPDATA.EMP_ACT DECIMAL(5.5769ST1 V4R4M0 990521 CROSS REFERENCE Data Names ACTNO A100-DONE1 A200-DONE2 BIRTHDATE BONUS CODE-EDIT COMM COMM COMMISSION CORPDATA C1 C2 DEPTNO DEPTNO EDLEVEL EMENDATE EMENDATE EMP_ACT EMP_ACT EMPLOYEE EMPLOYEE EMPLOYEE-COUNT EMPLOYEE-COUNT EMPNO EMPNO EMPNO EMPNO EMPNO EMPNO EMPTIME EMPTIME EMSTDATE Create SQL COBOL Program Define 168 **** **** 134 134 69 **** 134 43 **** 165 209 50 213 134 168 **** **** **** **** **** 63 114 51 103 134 **** **** 168 168 **** 168 CBLEX 04/01/98 11:09:13 Page 7 Reference SMALL INTEGER PRECISION(4.0) COLUMN (NOT NULL) IN CORPDATA.0) IN RPT2 IN RPT2-DATA CHARACTER(6) IN RPT1 250 CHARACTER(6) IN RPT1-DATA CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.PROJECT SMALL INTEGER PRECISION(4.EMP_ACT COLUMN 212 DATE(10) COLUMN IN CORPDATA. 2) 135 CHARACTER(4) COLUMN IN CORPDATA.5769ST1 V4R4M0 990521 CROSS REFERENCE EMSTDATE E010-UPDATE-ERROR E020-REPORT-ERROR FIRSTNME FIRSTNME HIREDATE JOB LASTNAME LASTNAME MAJPROJ MAJPROJ MIDINIT NAME NAME PERCENTAGE PHONENO PRENDATE PRENDATE PRENDATE PRINT-RECORD PROJECT PROJECT PROJECT PROJECT-NAME PROJECT-NAME PROJNAME PROJNAME PROJNAME PROJNO PROJNO PROJNO PROJNO PROJNO Create SQL COBOL Program **** **** **** 134 **** 134 134 134 **** 50 213 134 52 105 42 134 50 **** 213 37 50 **** **** 62 112 50 **** 213 50 61 101 110 **** CBLEX 04/01/98 11:09:13 Page 8 COLUMN 211 LABEL 131 LABEL 148 VARCHAR(12) 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 Figure 40.EMPLOYEE CHARACTER(8) COLUMN IN CORPDATA.EMPLOYEE COLUMN 167 DATE(10) COLUMN IN CORPDATA.EMPLOYEE DATE(10) IN PROJECT COLUMN 217 DATE(10) 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.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.EMPLOYEE CHARACTER(30) IN RPT1 251 CHARACTER(30) IN RPT1-DATA DECIMAL(5. Sample COBOL Program Using SQL Statements (Part 8 of 9) 620 DB2 UDB for AS/400 SQL Programming V4R4 . 0) 212 CHARACTER(3) COLUMN IN CORPDATA.EMPLOYEE CHARACTER(1) COLUMN IN CORPDATA.5769ST1 V4R4M0 990521 CROSS REFERENCE PROJNO PROJNO PROJNO PROJNO PRSTAFF PRSTAFF PRSTDATE PRSTDATE RAISE-DATE RESPEMP RESPEMP RPT1 RPT1-DATA RPT1-HEADERS RPT1-HEADER1 RPT1-HEADER2 RPT2 RPT2-DATA RPT2-HEADERS RPT2-HEADER1 RPT2-HEADER2 RPT2-HEADER3 SALARY SALARY SALARY SALARY SEX TOTAL-PROJ-COST TOTAL-PROJ-COST WORK-DAYS WORKDEPT No errors found in source 307 Source records processed Create SQL COBOL Program 168 **** **** 213 50 213 50 213 41 50 213 49 100 75 76 80 60 109 85 86 90 95 53 107 **** 134 134 64 116 40 134 * * * * * CBLEX 04/01/98 11:09:13 Page 9 166 171 CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA. Sample COBOL Program Using SQL Statements (Part 9 of 9) SQL Statements in PL/I Appendix C.2) IN RPT2 IN RPT2-DATA SMALL INTEGER PRECISION(4.PROJECT CHARACTER(11) 217 CHARACTER(6) IN PROJECT CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE DECIMAL(12. Sample Programs Using DB2 UDB for AS/400 Statements 621 .PROJECT DECIMAL(5.PROJECT DATE(10) IN PROJECT DATE(10) COLUMN IN CORPDATA.2) IN RPT1 251 IN RPT1-DATA COLUMN 135 135 167 212 DECIMAL(9.2) COLUMN IN CORPDATA.EMP_ACT COLUMN IN EMP_ACT 210 215 218 COLUMN IN PROJECT 215 CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE E N D O F L I S T I N G * * * * * Figure 40.2) IN PROJECT DECIMAL(5.2) COLUMN IN CORPDATA.PROJECT IN RPT1-HEADERS IN RPT1-HEADERS STRUCTURE 270 IN RPT2-HEADERS IN RPT2-HEADERS IN RPT2-HEADERS DECIMAL(8. ..........*JOB Time format.................*JOB Date separator..*NONE Package name............*NO Generation level.....*JOB Replace............................QTEMP/QSQLTEMP Options.....................CORPDATA/SRC Member..............V4R4M0 INCLUDE file..........*LIBL/QSYSPRT Date format............5769ST1 V4R4M0 990521 Create SQL PL/I Program Source type.........*CURRENT RDB connect method......*LOCAL User .........*PGMLIB/*PGM Dynamic User Profile....................*HMS Time separator ...................PLI Program name....*CHG Allow copy of data..........*SRC *XREF Target release........*USER User Profile..*NOFLAG ANS flagging.*YES Close SQL cursor...*SRCFILE Printer file................................. Sample PL/I Program Using SQL Statements (Part 1 of 7) 622 DB2 UDB for AS/400 SQL Programming V4R4 .......................*DUW Default Collection......................................*ENDPGM Allow blocking..............*YES Relational database....*LIBL/*SRCFILE Commit.*JOB Language ID.........65535 Source member changed on 07/01/96 12:53:08 PLIEX 04/01/98 12:53:36 Page 1 Figure 41.....65535 Job CCSID........*READ Delay PREPARE.......................PLIEX To source file..*NAMING Sort Sequence.......CORPDATA/PLIEX Source file................................*NONE Text............*JOB IBM SQL flagging................10 Margins..............*SRCMBRTXT Source file CCSID................ .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 V4R4M0 990521 Create SQL PL/I Program PLIEX *. 15 PROJECT_NAME CHAR(36). 8 /* A sample program which updates the salaries for those employees */ /* whose current commission total is greater than or equal to the */ /* value of COMMISSION.04. 1 %INCLUDE PROJECT (PROJECT.. */ /* Write out the header for Report 1 */ put file(sysprint) edit('REPORT OF PROJECTS AFFECTED BY EMPLOYEE RAISES') (col(22). 5 .. Sample PL/I Program Using SQL Statements (Part 2 of 7) Appendix C.+.+..+.2). 15 EMPNO CHAR(6).... /* Commit changes */ 5 EXEC SQL COMMIT... 2 . ROLLBACK the changes.+. 4 EXEC SQL UPDATE CORPDATA/EMPLOYEE SET SALARY = SALARY * :PERCENTAGE WHERE COMM >= :COMMISSION . EXEC SQL WHENEVER SQLERROR GO TO REPORT_ERROR..2). FIXED DECIMAL(5. 7 . ordered by project number and employee ID.2).+. 15 PROJNO CHAR(6). OPEN FILE(SYSPRINT).. FIXED DECIMAL(8. */ /* A report is generated showing the projects which these employees */ /* have contributed to. /* Report the updated statistics for each project supported by one */ /* of the selected employees...COMMA).+. /* File declaration for sysprint */ DCL SYSPRINT FILE EXTERNAL OUTPUT STREAM PRINT. 6 . 4 ..00. 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 2 Figure 41.... */ /* A second report shows each project having an end date occurring */ /* after RAISE_DATE (i..+. is potentially affected by the retroactive */ /* raises) with its total salary expenses and a count of employees */ /* who contributed to the project. retroactive to RAISE_DATE. /* Structure for report 1 */ DCL 1 RPT1. */ 3 EXEC SQL WHENEVER SQLERROR GO TO UPDATE_ERROR.2). /* Update the selected employee's salaries by the new percentage.... WORK_DAYS = 253.. RAISE_DATE = '1982-06-01'.e. 15 SALARY FIXED DECIMAL(8. FIXED BIN(15). DCL DCL DCL DCL RAISE_DATE WORK_DAYS COMMISSION PERCENTAGE CHAR(10). */ /*********************************************************************/ PLIEX: PROC. */ /* If an error occurs during the update.a). RECORD.. 1 .. 3 ..+... COMMISSION = 2000. Sample Programs Using DB2 UDB for AS/400 Statements 623 . 15 TOTL_PROJ_COST FIXED DECIMAL(10... PERCENTAGE = 1... 15 NAME CHAR(30). 2 EXEC SQL INCLUDE SQLCA. 15 EMPLOYEE_COUNT FIXED BIN(15). /* Structure for report 2 */ DCL 1 RPT2.. The salaries of those who qualify are */ /* increased by the value of PERCENTAGE.. */ */ */ */ */ /* Write out the header for Report 2 */ PUT FILE(SYSPRINT) EDIT('ACCUMULATED STATISTICS BY PROJECT') (SKIP(3).PROJNO AND EMP_ACT. PROJNAME.EMPNO. :RPT1.e..A..+.a)..8. 1 . 6 exec sql declare c1 cursor for select DISTINCT projno.'COST') (SKIP.COL(48).a. Sample PL/I Program Using SQL Statements (Part 3 of 7) 624 DB2 UDB for AS/400 SQL Programming V4R4 .+..RPT1.a.A.. 4 . PUT FILE(SYSPRINT) EDIT('PROJECT'..RPT1. EMP_ACT. 11 EXEC SQL DECLARE C2 CURSOR FOR SELECT EMP_ACT. /* Fetch and write the rows to SYSPRINT */ EXEC SQL WHENEVER NOT FOUND GO TO DONE2..'SALARY') (skip(2)..col(55)...COL(48).COL(22).2))...A).2) ) FROM CORPDATA/EMP_ACT.SKIP). 6 . 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 3 Figure 41.A.'EMPID'. :RPT1. CORPDATA/PROJECT.+.RPT1.. 7 EXEC SQL OPEN C1.col(1).'NUMBER OF'.+. :rpt1.empno = EMPLOYEE.. those projects potentially affected by the salary raises) generate a report containing the project number.COL(1).+.'EMPLOYEES'.A.+. PUT FILE(SYSPRINT) EDIT('NUMBER'..PROJNO. 7 . /* /* /* /* /* For all projects ending at a date later than 'raise_date' (i..a. 2 . CORPDATA/EMPLOYEE where EMP_ACT.. 3 . salary from CORPDATA/EMP_ACT. DONE1: 10 EXEC SQL CLOSE C1.empno and comm >= :COMMISSION order by projno.PROJNO.A....COL(54)...NAME.SALARY.COL(20).A. project name the count of employees participating in the project and the total salary cost of the project..EMPNO.'TOTAL') (SKIP(2)..+..DAYS(EMSTDATE)) * EMPTIME * DECIMAL(( SALARY / :WORK_DAYS ). COUNT(*).'EMPLOYEE NAME'..NAME. 5 .col(20).A. CORPDATA/EMPLOYEE WHERE EMP_ACT.PROJNO.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 V4R4M0 990521 Create SQL PL/I Program PLIEX *.col(10).PROJNO=PROJECT. empno.COL(1).COL(10)..SALARY) (SKIP.A.. DO UNTIL (SQLCODE |= 0).A). 8 put file(sysprint) edit('PROJECT'. PUT FILE(SYSPRINT) EDIT(RPT1..'PROJECT NAME'. PROJNAME ORDER BY 1.EMPNO AND PRENDATE > :RAISE_DATE GROUP BY EMP_ACT. END.COL(10).+. SUM( (DAYS(EMENDATE) .COL(63).COL(1). 9 EXEC SQL FETCH C1 INTO :RPT1.F(8..EMPNO =EMPLOYEE.. EXEC SQL OPEN C2.. lastname||'.empno. '||firstnme. /* Fetch and write the rows to SYSPRINT */ 8 EXEC SQL WHENEVER NOT FOUND GO TO DONE1.PROJNO.COL(63). DO UNTIL (SQLCODE |= 0).A. . * * * * * E N D O F S O U R C E * * * * * */ 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 4 Figure 41..PROJNO.COL(1).. 14 EXEC SQL ROLLBACK. Inform user and rollback */ /* changes.+..2)). GO TO FINISHED..+. 7 . RETURN. GO TO FINISHED..F(8.RPT2.. Sample PL/I Program Using SQL Statements (Part 4 of 7) Appendix C..F(5)).A... 1 ..PROJECT_NAME. */ UPDATE_ERROR: 13 EXEC SQL WHENEVER SQLERROR CONTINUE...F(5)). 3 ...+. PUT FILE(SYSPRINT) EDIT('*** ERROR Occurred while updating table.SQLCODE)(A.. /* Error occured while generating reports. 6 .COL(50).EMPLOYEE_COUNT.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 164 165 V4R4M0 990521 Create SQL PL/I Program PLIEX *.COL(62). END..SQLCODE)(A. 8 12 EXEC SQL FETCH C2 INTO :RPT2. GO TO FINISHED..'|| ' SQLCODE='.F(4).. 5 .A...+..+. PUT FILE(SYSPRINT) EDIT(RPT2.. SQLCODE='.+.. /* Error occured while updating table. REPORT_ERROR: PUT FILE(SYSPRINT) EDIT('*** ERROR Occurred while generating '|| 'reports.COL(10). END PLIEX. /* All done */ FINISHED: CLOSE FILE(SYSPRINT).. 2 . 4 .. DONE2: EXEC SQL CLOSE C2....+.... TOTL_PROJ_COST) (SKIP. Inform user and exit. Sample Programs Using DB2 UDB for AS/400 Statements 625 .+. 0) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE COLUMN 52 76 DECIMAL(9.EMPLOYEE DECIMAL(8.EMPLOYEE DECIMAL(5.EMP_ACT COLUMN 116 DATE(10) COLUMN IN CORPDATA.2) COLUMN IN CORPDATA.EMPLOYEE Figure 41.2) COLUMN IN CORPDATA.EMP_ACT CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.2) COLUMN IN CORPDATA.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.EMP_ACT COLUMN 116 COLUMN 73 VARCHAR(12) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE DATE(10) COLUMN IN CORPDATA.5769ST1 V4R4M0 990521 CROSS REFERENCE Data Names ACTNO BIRTHDATE BONUS COMM COMM COMMISSION CORPDATA C1 C2 DEPTNO DEPTNO DONE1 DONE2 EDLEVEL EMENDATE EMENDATE EMP_ACT EMP_ACT EMPLOYEE EMPLOYEE EMPLOYEE_COUNT EMPNO EMPNO EMPNO EMPNO EMPNO EMPTIME EMPTIME EMSTDATE EMSTDATE FIRSTNME FIRSTNME Create SQL PL/I Program Define 74 74 74 **** 74 18 **** 71 114 26 118 **** **** 74 74 **** **** **** **** **** 35 27 **** **** 74 74 74 **** 74 **** **** 74 PLIEX 04/01/98 12:53:36 Page 5 Reference 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 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.EMPLOYEE DECIMAL(9. Sample PL/I Program Using SQL Statements (Part 5 of 7) 626 DB2 UDB for AS/400 SQL Programming V4R4 .0) COLUMN (NOT NULL) IN CORPDATA. 2) IN RPT1 DECIMAL(5.2) 87 COLUMN 51 51 73 117 DECIMAL(9.5769ST1 V4R4M0 990521 CROSS REFERENCE HIREDATE JOB LASTNAME LASTNAME MAJPROJ MAJPROJ MIDINIT NAME PERCENTAGE PHONENO PRENDATE PRENDATE PRENDATE PROJECT PROJECT PROJECT_NAME PROJNAME PROJNAME PROJNAME PROJNO PROJNO PROJNO PROJNO PROJNO PROJNO PROJNO PRSTAFF PRSTAFF PRSTDATE PRSTDATE RAISE_DATE REPORT_ERROR Create SQL PL/I Program 74 74 **** 74 26 118 74 28 19 74 26 **** 118 **** **** 34 26 **** 118 26 33 **** 74 **** **** 118 26 118 26 118 16 **** PLIEX 04/01/98 12:53:36 Page 6 DATE(10) COLUMN IN CORPDATA.PROJECT CHARACTER(1) COLUMN (NOT NULL) IN CORPDATA. Sample PL/I Program Using SQL Statements (Part 6 of 7) 5769ST1 V4R4M0 990521 CROSS REFERENCE RESPEMP RESPEMP RPT1 RPT2 SALARY SALARY SALARY SEX SYSPRINT TOTL_PROJ_COST UPDATE_ERROR WORK_DAYS WORKDEPT No errors found in source 165 Source records processed Create SQL PL/I Program 26 118 25 32 29 **** 74 74 22 36 **** 17 74 * * * * * CHARACTER(6) CHARACTER(6) STRUCTURE STRUCTURE 132 DECIMAL(8.PROJECT DATE(10) IN RPT1 DATE(10) COLUMN IN CORPDATA.EMPLOYEE CHARACTER(6) IN RPT1 CHARACTER(6) COLUMN IN CORPDATA.EMPLOYEE DATE(10) IN RPT1 COLUMN 121 DATE(10) COLUMN IN CORPDATA.EMPLOYEE CHARACTER(30) IN RPT1 86 DECIMAL(5.2) 51 CHARACTER(4) COLUMN IN CORPDATA.EMPLOYEE E N D O F L I S T I N G * * * * * Figure 41.PROJECT IN RPT1 COLUMN IN CORPDATA. Sample PL/I Program Using SQL Statements (Part 7 of 7) Appendix C.0) 117 CHARACTER(3) COLUMN IN CORPDATA.PROJECT TABLE IN CORPDATA 118 TABLE 119 CHARACTER(36) IN RPT2 VARCHAR(24) IN RPT1 COLUMN 115 122 VARCHAR(24) COLUMN (NOT NULL) IN CORPDATA. Sample Programs Using DB2 UDB for AS/400 Statements 627 .PROJECT CHARACTER(10) 121 LABEL 57 Figure 41.2) CHARACTER(1) PLIEX 04/01/98 12:53:36 Page 7 IN RPT1 COLUMN (NOT NULL) IN CORPDATA.PROJECT CHARACTER(6) IN RPT1 86 CHARACTER(6) IN RPT2 COLUMN 72 77 CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE DECIMAL(10.EMP_ACT COLUMN IN EMP_ACT 115 119 122 COLUMN IN PROJECT 119 CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE COLUMN IN CORPDATA.EMPLOYEE COLUMN 73 VARCHAR(15) COLUMN (NOT NULL) IN CORPDATA.2) IN RPT2 LABEL 48 SMALL INTEGER PRECISION(4.PROJECT DECIMAL(5.2) COLUMN IN CORPDATA.EMPLOYEE CHARACTER(8) COLUMN IN CORPDATA. ....................*JOB Time format.*NO Generation level....*CURRENT RDB connect method............................................................................*NAMING Sort Sequence...............65535 Job CCSID..........................CORPDATA/SRC Member....*SRCMBRTXT Source file CCSID....................*YES Close SQL cursor....QTEMP/QSQLTEMP Options............................................RPG Program name..*CHG Allow copy of data........V4R4M0 INCLUDE file..65535 Source member changed on 07/01/96 17:06:17 RPGEX 04/01/98 12:55:22 Page 1 Figure 42.......*NOFLAG ANS flagging........CORPDATA/RPGEX Source file....*SRC *XREF Target release.............*JOB IBM SQL flagging................*NONE Package name.. Sample RPG for AS/400 Program Using SQL Statements (Part 1 of 8) 628 DB2 UDB for AS/400 SQL Programming V4R4 ......................*LIBL/QSYSPRT Date format.......*JOB Replace...*JOB Language ID...*ENDPGM Allow blocking.....................*HMS Time separator ........*YES Relational database...*READ Delay PREPARE.......*LOCAL User ........*JOB Date separator......*NONE Text.................SQL Statements in RPG for AS/400 Programs 5769ST1 V4R4M0 990521 Create SQL RPG Program Source type...*DUW Default Collection....*USER User Profile...............*LIBL/*SRCFILE Commit...........................*PGMLIB/*PGM Dynamic User Profile..............10 Printer file........RPGEX To source file......... 7 .. 4 . Sample Programs Using DB2 UDB for AS/400 Statements 629 .+.. 2 .. 64 C* 65 C* Write out the header for report 1.. 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 2 Figure 42.+..00 COMMI 37 C Z-ADD1.04 PERCNT 38 C MOVEL'1982-06-'RDATE 39 C MOVE '01' RDATE 40 C SETON LR 41 C* 42 C* Update the selected projects by the new percentage. 3 ..... ROLLBACK the changes....... 44 C* 45 3 C/EXEC SQL WHENEVER SQLERROR GOTO UPDERR 46 C/END-EXEC 47 C* 48 4 C/EXEC SQL 49 C+ UPDATE CORPDATA/EMPLOYEE 50 C+ SET SALARY = SALARY * :PERCNT 51 C+ WHERE COMM >= :COMMI 52 C/END-EXEC 53 C* 54 C* Commit changes. 22 I* 23 IRPT2 DS 24 I 1 6 PRJNUM 25 I 7 42 PNAME 26 I B 43 440EMPCNT 27 I P 45 492PRCOST 28 I* 29 I DS 30 I B 1 20WRKDAY 31 I P 3 62COMMI 32 I 7 16 RDATE 33 I P 17 202PERCNT 34 2 C* 35 C Z-ADD253 WRKDAY 36 C Z-ADD2000.... 5 . If an 43 C* error occurs during the update.+...+.. 7 I* 8 1 IRPT1 E DSPROJECT 9 I PROJNAME PROJNM 10 I RESPEMP RESEM 11 I PRSTAFF STAFF 12 I PRSTDATE PRSTD 13 I PRENDATE PREND 14 I MAJPROJ MAJPRJ 15 I* 16 I DS 17 I 1 6 EMPNO 18 I 7 36 NAME 19 I P 37 412SALARY 20 I* 21 I* Structure for report 2... 8 1 H 2 F* File declaration for QPRINT 3 F* 4 FQPRINT O F 132 PRINTER 5 I* 6 I* Structure for report 1..5769ST1 V4R4M0 990521 Create SQL RPG Program RPGEX Record *.+.. Sample RPG for AS/400 Program Using SQL Statements (Part 2 of 8) Appendix C.. 6 ...+. 1 ..+...+.. 55 C* 56 5 C/EXEC SQL COMMIT 57 C/END-EXEC 58 C* 59 C/EXEC SQL WHENEVER SQLERROR GO TO RPTERR 60 C/END-EXEC 61 C* 62 C* Report the updated statistics for each employee assigned to 63 C* selected projects. 122 C* 123 C/EXEC SQL WHENEVER NOT FOUND GO TO DONE2 124 C/END-EXEC 125 C SQLCOD DOUNE0 126 C/EXEC SQL 127 12 C+ FETCH C2 INTO :RPT2 128 C/END-EXEC 129 C EXCPTRECD 130 C END 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 3 Figure 42... :EMPNO..+. 82 C* 83 8 C/EXEC SQL WHENEVER NOT FOUND GO TO DONE1 84 C/END-EXEC 85 C SQLCOD DOUNE0 86 C/EXEC SQL 87 9 C+ FETCH C1 INTO :PROJNO... CORPDATA/EMPLOYEE 111 C+ WHERE EMP_ACT.PROJNO..+.e.EMPNO = EMPLOYEE. CORPDATA/PROJECT.. COUNT(*)..+.. Sample RPG for AS/400 Program Using SQL Statements (Part 3 of 8) 630 DB2 UDB for AS/400 SQL Programming V4R4 .. EMPNO 75 C/END-EXEC 76 C* 77 7 C/EXEC SQL 78 C+ OPEN C1 79 C/END-EXEC 80 C* 81 C* Fetch and write the rows to QPRINT.PROJNO = PROJECT. 3 .. CORPDATA/EMPLOYEE 72 C+ WHERE EMP_ACT.+.... SALARY 71 C+ FROM CORPDATA/EMP_ACT... '||FIRSTNME.. PROJNAME. 108 C+ SUM((DAYS(EMENDATE) .DAYS(EMSTDATE)) * EMPTIME * 109 C+ DECIMAL((SALARY/:WRKDAY)... 2 .EMPNO = EMPLOYEE... 103 C* 104 C EXCPTRECC 105 11 C/EXEC SQL 106 C+ DECLARE C2 CURSOR FOR 107 C+ SELECT EMP_ACT. 101 C* 102 C* Write out the header for report 2. 8 66 C* 67 C EXCPTRECA 68 6 C/EXEC SQL DECLARE C1 CURSOR FOR 69 C+ SELECT DISTINCT PROJNO. those projects potentially affected by the salary raises) 98 C* generate a report containing the project number... :NAME. 4 .EMPNO AND 113 C+ PRENDATE > :RDATE 114 C+ GROUP BY EMP_ACT....PROJNO AND 112 C+ EMP_ACT.. PROJNAME 115 C+ ORDER BY 1 116 C/END-EXEC 117 C* 118 C/EXEC SQL OPEN C2 119 C/END-EXEC 120 C* 121 C* Fetch and write the rows to QPRINT. 99 C* the count of employees participating in the project and the 100 C* total salary cost of the project.EMPNO.+. project name.. 1 .8.+...PROJNO.+. 70 C+ LASTNAME||'. 5 . 7 ..+.EMPNO AND 73 C+ COMM >= :COMMI 74 C+ ORDER BY PROJNO. EMP_ACT..2)) 110 C+ FROM CORPDATA/EMP_ACT. :SALARY 88 C/END-EXEC 89 C EXCPTRECB 90 C END 91 C DONE1 TAG 92 C/EXEC SQL 93 10 C+ CLOSE C1 94 C/END-EXEC 95 C* 96 C* For all project ending at a date later than the raise date 97 C* (i.5769ST1 V4R4M0 990521 Create SQL RPG Program RPGEX Record *. 6 . ... 155 C* 156 C FINISH TAG 157 OQPRINT E 0201 RECA 158 O 45 'REPORT OF PROJECTS AFFEC' 159 O 64 'TED BY EMPLOYEE RAISES' 160 O E 01 RECA 161 O 7 'PROJECT' 162 O 17 'EMPLOYEE' 163 O 32 'EMPLOYEE NAME' 164 O 60 'SALARY' 165 O E 01 RECB 166 O PROJNO 6 167 O EMPNO 15 168 O NAME 50 169 O SALARYL 61 170 O E 22 RECC 171 O 42 'ACCUMULATED STATISTIC' 172 O 54 'S BY PROJECT' 173 O E 01 RECC 174 O 7 'PROJECT' 175 O 56 'NUMBER OF' 176 O 67 'TOTAL' 177 O E 02 RECC 178 O 6 'NUMBER' 179 O 21 'PROJECT NAME' 180 O 56 'EMPLOYEES' 181 O 66 'COST' 182 O E 01 RECD 195 O 57 'CODE=' 183 O PRJNUM 6 184 O PNAME 45 185 O EMPCNTL 54 186 O PRCOSTL 70 187 O E 01 RECE 188 O 28 '*** ERROR Occurred while' 189 O 52 ' updating table.. 6 ... 2 .... 150 C* 151 C RPTERR TAG 152 C EXCPTRECF 153 C* 154 C* All done. 3 . SQLCODE' 190 O 53 '=' 191 O SQLCODL 62 192 O E 01 RECF 193 O 28 '*** ERROR Occurred while' 194 O 52 ' generating reports. 7 . 1 .. 5 .+...... 2 ....+....... 4 .... 138 C* 139 C UPDERR TAG 140 C EXCPTRECE 141 13 C/EXEC SQL WHENEVER SQLERROR CONTINUE 142 C/END-EXEC 143 C* 144 14 C/EXEC SQL 145 C+ ROLLBACK 146 C/END-EXEC 147 C RETRN 148 C* 149 C* Error occured while generating reports.. SQL' 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 4 Figure 42.... Sample RPG for AS/400 Program Using SQL Statements (Part 5 of 8) Appendix C.... Sample Programs Using DB2 UDB for AS/400 Statements 631 .+..+.+. 5 .. 4 196 O SQLCODL * * * * * E N D Program RPGEX .+.+.. 1 ... 7 .+....... 8 67 O F S O U R C E * * * * * 04/01/98 12:55:22 SEQNBR Last change 19600 Page 5 Figure 42.... 6 ...... 3 .+.+......+...+. Sample RPG for AS/400 Program Using SQL Statements (Part 4 of 8) 5769ST1 V4R4M0 990521 Create SQL RPG Record *. Inform user and rollback 137 C* changes..5769ST1 V4R4M0 990521 Create SQL RPG Program RPGEX Record *. 8 131 C DONE2 TAG 132 C/EXEC SQL CLOSE C2 133 C/END-EXEC 134 C RETRN 135 C* 136 C* Error occured while updating table.+.+.... Inform user and exit.+.+. Sample RPG for AS/400 Program Using SQL Statements (Part 6 of 8) 632 DB2 UDB for AS/400 SQL Programming V4R4 .EMPLOYEE DECIMAL(7.EMPLOYEE DATE(10) COLUMN IN CORPDATA.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.EMPLOYEE DECIMAL(9.2) COLUMN IN CORPDATA.EMP_ACT DECIMAL(5.EMPLOYEE Figure 42.0) COLUMN (NOT NULL) IN CORPDATA.EMP_ACT DATE(10) COLUMN IN CORPDATA.PROJECT LABEL 83 LABEL 123 SMALL INTEGER PRECISION(4.0) COLUMN (NOT NULL) IN CORPDATA.EMP_ACT COLUMN 105 TABLE 68 68 105 105 105 105 TABLE IN CORPDATA 68 105 SMALL INTEGER PRECISION(4.5769ST1 V4R4M0 990521 CROSS REFERENCE Data Names ACTNO BIRTHDATE BONUS COMM COMM COMMI CORPDATA C1 C2 DEPTNO DEPTNO DONE1 DONE2 EDLEVEL EMENDATE EMENDATE EMP_ACT EMP_ACT EMPCNT EMPLOYEE EMPLOYEE EMPNO EMPNO EMPNO EMPNO EMPNO EMPTIME EMPTIME EMSTDATE EMSTDATE FINISH FIRSTNME Create SQL RPG Program Define 68 48 48 **** 48 31 **** 68 105 8 105 91 131 48 68 **** **** **** 26 **** **** 17 48 **** **** 68 68 **** 68 **** 156 48 RPGEX 04/01/98 12:55:22 Page 6 Reference SMALL INTEGER PRECISION(4.EMPLOYEE COLUMN 48 68 DECIMAL(9.0) IN RPT2 TABLE IN CORPDATA 48 68 105 TABLE 68 105 CHARACTER(6) 86 CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMP_ACT COLUMN 105 DATE(10) COLUMN IN CORPDATA.2) COLUMN IN CORPDATA.2) COLUMN 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 COLUMN 105 LABEL VARCHAR(12) COLUMN (NOT NULL) IN CORPDATA. PROJECT DECIMAL(5.PROJECT CHARACTER(1) COLUMN (NOT NULL) IN CORPDATA.PROJECT CHARACTER(6) IN RPT2 TABLE IN CORPDATA 105 TABLE 105 COLUMN 105 105 VARCHAR(24) COLUMN (NOT NULL) IN CORPDATA. Sample RPG for AS/400 Program Using SQL Statements (Part 8 of 8) Appendix C.EMPLOYEE VARCHAR(15) 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.EMPLOYEE COLUMN 68 CHARACTER(6) IN RPT1 CHARACTER(6) COLUMN IN CORPDATA.EMP_ACT COLUMN IN EMP_ACT 105 105 105 COLUMN IN PROJECT 105 CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE CHARACTER(36) IN RPT2 DECIMAL(9.PROJECT LABEL 59 STRUCTURE STRUCTURE 126 DECIMAL(9.EMPLOYEE SMALL INTEGER PRECISION(4.PROJECT CHARACTER(10) 105 Figure 42.5769ST1 V4R4M0 990521 CROSS REFERENCE FIRSTNME HIREDATE JOB LASTNAME LASTNAME MAJPRJ MAJPROJ MIDINIT NAME PERCNT PHONENO PNAME PRCOST PREND PRENDATE PRENDATE PRJNUM PROJECT PROJECT PROJNAME PROJNAME PROJNM PROJNO PROJNO PROJNO PROJNO PROJNO PROJNO PRSTAFF PRSTD PRSTDATE RDATE Create SQL RPG Program **** 48 48 48 **** 8 105 48 18 33 48 25 27 8 **** 105 24 **** **** **** 105 8 8 **** 68 **** **** 105 105 8 105 32 RPGEX 04/01/98 12:55:22 Page 7 COLUMN 68 DATE(10) COLUMN IN CORPDATA.2) COLUMN IN CORPDATA.EMPLOYEE CHARACTER(8) COLUMN IN CORPDATA.2) 86 COLUMN 48 48 68 105 DECIMAL(9.PROJECT DATE(10) IN RPT1 DATE(10) COLUMN IN CORPDATA. Sample Programs Using DB2 UDB for AS/400 Statements 633 . Sample RPG for AS/400 Program Using SQL Statements (Part 7 of 8) 5769ST1 V4R4M0 990521 CROSS REFERENCE RESEM RESPEMP RPTERR RPT1 RPT2 SALARY SALARY SALARY SEX STAFF UPDERR WORKDEPT WRKDAY No errors found in source 196 Source records processed Create SQL RPG Program 8 105 151 8 23 19 **** 48 48 8 139 48 30 RPGEX 04/01/98 12:55:22 Page 8 CHARACTER(6) IN RPT1 CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE CHARACTER(30) 86 DECIMAL(7.EMPLOYEE DECIMAL(5.EMPLOYEE CHARACTER(1) COLUMN IN CORPDATA.2) IN RPT1 LABEL 45 CHARACTER(3) COLUMN IN CORPDATA.2) COLUMN IN CORPDATA.0) 105 E N D O F L I S T I N G * * * * * * * * * * Figure 42.2) IN RPT2 DATE(10) IN RPT1 COLUMN 105 DATE(10) COLUMN IN CORPDATA.2) 48 CHARACTER(4) COLUMN IN CORPDATA. ............*YES Relational database............*NONE Package name.V4R4M0 INCLUDE file..........65535 Job CCSID.*NOFLAG ANS flagging................*LIBL/QSYSPRT Date format..................10 Printer file..RPG Object name....*LIBL/*SRCFILE Commit............ Sample ILE RPG for AS/400 Program Using SQL Statements (Part 1 of 7) 634 DB2 UDB for AS/400 SQL Programming V4R4 .*ENDMOD Allow blocking.........................*JOB Language ID.........CORPDATA/SRC Member...........*NO Generation level..................*JOB Date separator............................*NAMING Sort Sequence.........*JOB IBM SQL flagging.*JOB Replace...........*PRINT Target release....*YES Close SQL cursor.................*OBJLIB/*OBJ Created object type............*CURRENT RDB connect method........................*USER User Profile..........*PGM Debugging view.........65535 Source member changed on 07/01/96 15:55:32 RPGLEEX 04/01/98 16:03:02 Page 1 Figure 43.........................SQL Statements in ILE RPG for AS/400 Programs 5769ST1 V4R4M0 990521 Create SQL ILE RPG Object Source type.......*XREF Listing option.CORPDATA/RPGLEEX Source file................................*DUW Default Collection.......*NONE Dynamic User Profile.....................*READ Delay PREPARE...................*NONE Text...................*HMS Time separator ...............*SRCMBRTXT Source file CCSID..................*CHG Allow copy of data....*JOB Time format.............................*OBJ To source file..QTEMP/QSQLTEMP1 Options..*LOCAL User .............. 64 C+ LASTNAME||'. 8 1 H 2 F* File declaration for QPRINT 3 F* 4 FQPRINT O F 132 PRINTER 5 D* 6 D* Structure for report 1.. 7 ... 38 C* 39 3 C/EXEC SQL WHENEVER SQLERROR GOTO UPDERR 40 C/END-EXEC 41 C* 42 C/EXEC SQL 43 4 C+ UPDATE CORPDATA/EMPLOYEE 44 C+ SET SALARY = SALARY * :PERCNT 45 C+ WHERE COMM >= :COMMI 46 C/END-EXEC 47 C* 48 C* Commit changes.... 58 C* 59 C* Write out the header for report 1. EMP_ACT.. 5 .+....+.. 16 D* 17 DRPT2 DS 18 D PRJNUM 1 6 19 D PNAME 7 42 20 D EMPCNT 43 44B 0 21 D PRCOST 45 49P 2 22 D* 23 D DS 24 D WRKDAY 1 2B 0 25 D COMMI 3 6P 2 26 D RDATE 7 16 27 D PERCNT 17 20P 2 28 * 29 2 C Z-ADD 253 WRKDAY 30 C Z-ADD 2000. 49 C* 50 5 C/EXEC SQL COMMIT 51 C/END-EXEC 52 C* 53 C/EXEC SQL WHENEVER SQLERROR GO TO RPTERR 54 C/END-EXEC 55 C* 56 C* Report the updated statistics for each employee assigned to 57 C* selected projects. ROLLBACK the changes..+.+..+.. 2 . 6 .+.. 60 C* 61 C EXCEPT RECA 62 6 C/EXEC SQL DECLARE C1 CURSOR FOR 63 C+ SELECT DISTINCT PROJNO.00 COMMI 31 C Z-ADD 1.. CORPDATA/EMPLOYEE 04/01/98 16:03:02 Page SEQNBR Last change Comments 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 2 Figure 43..+...... 1 .... Sample Programs Using DB2 UDB for AS/400 Statements 635 . '||FIRSTNME. SALARY 65 C+ FROM CORPDATA/EMP_ACT.... If an 37 C* error occurs during the update. 7 D* 8 1 DRPT1 E DS EXTNAME(PROJECT) 9 D* 10 D DS 11 D EMPNO 1 6 12 D NAME 7 36 13 D SALARY 37 41P 2 14 D* 15 D* Structure for report 2. 3 ..EMPNO... 4 . Sample ILE RPG for AS/400 Program Using SQL Statements (Part 2 of 7) Appendix C..04 PERCNT 32 C MOVEL '1982-06-' RDATE 33 C MOVE '01' RDATE 34 C SETON LR 35 C* 36 C* Update the selected projects by the new percentage.+.5769ST1 V4R4M0 990521 Create SQL ILE RPG Object RPGLEEX Record *. .5769ST1 V4R4M0 990521 Create SQL ILE RPG Object RPGLEEX Record *.... 116 C* 117 C/EXEC SQL WHENEVER NOT FOUND GO TO DONE2 118 C/END-EXEC 119 C SQLCOD DOUNE 0 120 C/EXEC SQL 121 12 C+ FETCH C2 INTO :RPT2 122 C/END-EXEC 123 C EXCEPT RECD 124 C END 125 C DONE2 TAG 126 C/EXEC SQL CLOSE C2 127 C/END-EXEC 128 C RETURN 129 C* 130 C* Error occured while updating table.PROJNO AND 106 C+ EMP_ACT. 7 ...DAYS(EMSTDATE)) * EMPTIME * 103 C+ DECIMAL((SALARY/:WRKDAY).. PROJNAME 109 C+ ORDER BY 1 110 C/END-EXEC 111 C* 112 C/EXEC SQL OPEN C2 113 C/END-EXEC 114 C* 115 C* Fetch and write the rows to QPRINT. 3 .e. :SALARY 82 C/END-EXEC 83 C EXCEPT RECB 84 C END 85 C DONE1 TAG 86 C/EXEC SQL 87 10 C+ CLOSE C1 88 C/END-EXEC 89 C* 90 C* For all project ending at a date later than the raise date 91 C* (i.+.PROJNO.+...... 76 C* 77 8 C/EXEC SQL WHENEVER NOT FOUND GO TO DONE1 78 C/END-EXEC 79 C SQLCOD DOUNE 0 80 C/EXEC SQL 81 9 C+ FETCH C1 INTO :PROJNO.PROJNO = PROJECT.. CORPDATA/PROJECT. Inform user and rollback 04/01/98 16:03:02 Page SEQNBR Last change Comments 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 3 Figure 43.. 97 C* 98 C EXCEPT RECC 99 C/EXEC SQL 100 11 C+ DECLARE C2 CURSOR FOR 101 C+ SELECT EMP_ACT.EMPNO AND 67 C+ COMM >= :COMMI 68 C+ ORDER BY PROJNO.. 93 C* the count of employees participating in the project and the 94 C* total salary cost of the project.. 5 . those projects potentially affected by the salary raises) 92 C* generate a report containing the project number.+.8. CORPDATA/EMPLOYEE 105 C+ WHERE EMP_ACT.... 8 66 C+ WHERE EMP_ACT.. 1 .PROJNO.EMPNO AND 107 C+ PRENDATE > :RDATE 108 C+ GROUP BY EMP_ACT. COUNT(*).. PROJNAME. :NAME. project name.+.. 2 . 4 .2)) 104 C+ FROM CORPDATA/EMP_ACT.+. EMPNO 69 C/END-EXEC 70 C* 71 7 C/EXEC SQL 72 C+ OPEN C1 73 C/END-EXEC 74 C* 75 C* Fetch and write the rows to QPRINT...+.+...EMPNO = EMPLOYEE. 6 . Sample ILE RPG for AS/400 Program Using SQL Statements (Part 3 of 7) 636 DB2 UDB for AS/400 SQL Programming V4R4 ... :EMPNO. 102 C+ SUM((DAYS(EMENDATE) ....+. 95 C* 96 C* Write out the header for report 2.EMPNO = EMPLOYEE.. 1 .........+... 8 131 C* changes.5769ST1 V4R4M0 990521 Create SQL ILE RPG Object RPGLEEX Record *....+.+...+.. Sample ILE RPG for AS/400 Program Using SQL Statements (Part 4 of 7) Appendix C.. 5 .+.. SQL' 189 O 57 'CODE=' 190 O SQLCOD L 67 * * * * * E N D O F S O U R C E * * * * * 04/01/98 16:03:02 Page SEQNBR Last change Comments 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 16600 16700 16800 16900 17000 17100 17200 17300 17400 17500 17600 17700 17800 17900 18000 18100 18200 18300 18400 18500 18600 18700 18800 18900 19000 4 Figure 43. 132 C* 133 C UPDERR TAG 134 C EXCEPT RECE 135 13 C/EXEC SQL WHENEVER SQLERROR CONTINUE 136 C/END-EXEC 137 C* 138 14 C/EXEC SQL 139 C+ ROLLBACK 140 C/END-EXEC 141 C RETURN 142 C* 143 C* Error occured while generating reports..+... 4 ..... 144 C* 145 C RPTERR TAG 146 C EXCEPT RECF 147 C* 148 C* All done... 149 C* 150 C FINISH TAG 151 OQPRINT E RECA 0 2 01 152 O 42 'REPORT OF PROJECTS AFFEC' 153 O 64 'TED BY EMPLOYEE RAISES' 154 O E RECA 0 1 155 O 7 'PROJECT' 156 O 17 'EMPLOYEE' 157 O 32 'EMPLOYEE NAME' 158 O 60 'SALARY' 159 O E RECB 0 1 160 O PROJNO 6 161 O EMPNO 15 162 O NAME 50 163 O SALARY L 61 164 O E RECC 2 2 165 O 42 'ACCUMULATED STATISTIC' 166 O 54 'S BY PROJECT' 167 O E RECC 0 1 168 O 7 'PROJECT' 169 O 56 'NUMBER OF' 170 O 67 'TOTAL' 171 O E RECC 0 2 172 O 6 'NUMBER' 173 O 21 'PROJECT NAME' 174 O 56 'EMPLOYEES' 175 O 66 'COST' 176 O E RECD 0 1 177 O PRJNUM 6 178 O PNAME 45 179 O EMPCNT L 54 180 O PRCOST L 70 181 O E RECE 0 1 182 O 28 '*** ERROR Occurred while' 183 O 52 ' updating table. 3 .. 7 . 2 ...+.. 6 .+.. Inform user and exit. SQLCODE' 184 O 53 '=' 185 O SQLCOD L 62 186 O E RECF 0 1 187 O 28 '*** ERROR Occurred while' 188 O 52 ' generating reports. Sample Programs Using DB2 UDB for AS/400 Statements 637 . EMPLOYEE COLUMN IN EMP_ACT 62 62 62 99 COLUMN IN EMPLOYEE 62 99 CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE DATE(10) COLUMN IN CORPDATA.EMP_ACT DECIMAL(5. Sample ILE RPG for AS/400 Program Using SQL Statements (Part 5 of 7) 638 DB2 UDB for AS/400 SQL Programming V4R4 .5769ST1 V4R4M0 990521 CROSS REFERENCE Data Names ACTNO BIRTHDATE BONUS COMM COMM COMMI CORPDATA C1 C2 DEPTNO DEPTNO DONE1 DONE1 DONE2 DONE2 EDLEVEL EMENDATE EMENDATE EMP_ACT EMP_ACT EMPCNT EMPLOYEE EMPLOYEE EMPNO EMPNO EMPNO EMPNO EMPNO EMPTIME EMPTIME EMSTDATE EMSTDATE FINISH Create SQL ILE RPG Object Define 62 42 42 **** 42 25 **** 62 99 8 99 85 **** 125 **** 42 62 **** **** **** 20 **** **** 11 42 **** **** 62 62 **** 62 **** 150 RPGLEEX 04/01/98 16:03:02 Page 5 Reference 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.2) COLUMN IN CORPDATA.EMPLOYEE COLUMN 42 62 DECIMAL(9.PROJECT LABEL 77 LABEL 117 SMALL INTEGER PRECISION(4.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.EMP_ACT COLUMN 99 DATE(10) COLUMN IN CORPDATA.EMP_ACT DATE(10) COLUMN IN CORPDATA.EMPLOYEE DECIMAL(9.EMPLOYEE DECIMAL(7.0) COLUMN (NOT NULL) IN CORPDATA.EMP_ACT COLUMN 99 Figure 43.2) COLUMN IN CORPDATA.0) COLUMN (NOT NULL) IN CORPDATA.EMP_ACT COLUMN 99 TABLE 62 62 99 99 99 99 TABLE IN CORPDATA 62 99 SMALL INTEGER PRECISION(4.2) COLUMN IN CORPDATA. EMP_ACT COLUMN IN EMP_ACT 99 99 99 COLUMN IN PROJECT 99 CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.PROJECT CHARACTER(1) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE CHARACTER(30) DBCS-open 80 DECIMAL(7.2) IN RPT1 DECIMAL(5.EMPLOYEE SMALL INTEGER PRECISION(4. Sample ILE RPG for AS/400 Program Using SQL Statements (Part 7 of 7) Appendix C.EMPLOYEE CHARACTER(1) COLUMN IN CORPDATA.EMPLOYEE CHARACTER(8) COLUMN IN CORPDATA.PROJECT CHARACTER(6) DBCS-open IN RPT2 TABLE IN CORPDATA 99 TABLE 99 VARCHAR(24) IN RPT1 COLUMN 99 99 VARCHAR(24) COLUMN (NOT NULL) IN CORPDATA. Sample ILE RPG for AS/400 Program Using SQL Statements (Part 6 of 7) 5769ST1 V4R4M0 990521 CROSS REFERENCE RDATE RESPEMP RESPEMP RPTERR RPTERR RPT1 RPT2 SALARY SALARY SALARY SEX UPDERR UPDERR WORKDEPT WRKDAY Create SQL ILE RPG Object 26 8 99 145 **** 8 17 13 **** 42 42 133 **** 42 24 RPGLEEX 04/01/98 16:03:02 Page 7 CHARACTER(10) DBCS-open 99 CHARACTER(6) IN RPT1 CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.PROJECT CHARACTER(6) IN RPT1 80 COLUMN 62 62 CHARACTER(6) COLUMN (NOT NULL) IN CORPDATA.EMPLOYEE COLUMN 62 CHARACTER(6) IN RPT1 CHARACTER(6) COLUMN IN CORPDATA.PROJECT LABEL 53 STRUCTURE STRUCTURE 120 DECIMAL(9.2) IN RPT2 DATE(8) IN RPT1 COLUMN 99 DATE(10) COLUMN IN CORPDATA.PROJECT Figure 43.EMPLOYEE VARCHAR(15) COLUMN (NOT NULL) IN CORPDATA.5769ST1 V4R4M0 990521 CROSS REFERENCE FIRSTNME FIRSTNME HIREDATE JOB LASTNAME LASTNAME MAJPROJ MAJPROJ MIDINIT NAME PERCNT PHONENO PNAME PRCOST PRENDATE PRENDATE PRENDATE PRJNUM PROJECT PROJECT PROJNAME PROJNAME PROJNAME PROJNO PROJNO PROJNO PROJNO PROJNO PROJNO PRSTAFF PRSTAFF PRSTDATE PRSTDATE Create SQL ILE RPG Object 42 **** 42 42 42 **** 8 99 42 12 27 42 19 21 8 **** 99 18 **** **** 8 **** 99 8 **** 62 **** **** 99 8 99 8 99 RPGLEEX 04/01/98 16:03:02 Page 6 VARCHAR(12) COLUMN (NOT NULL) IN CORPDATA.PROJECT DATE(8) IN RPT1 DATE(10) COLUMN IN CORPDATA. Sample Programs Using DB2 UDB for AS/400 Statements 639 .PROJECT DECIMAL(5.2) 80 COLUMN 42 42 62 99 DECIMAL(9.EMPLOYEE COLUMN 62 DATE(10) COLUMN IN CORPDATA.EMPLOYEE CHARACTER(36) DBCS-open IN RPT2 DECIMAL(9.2) COLUMN IN CORPDATA.2) COLUMN IN CORPDATA.0) 99 E N D O F L I S T I N G * * * * * No errors found in source 190 Source records processed * * * * * Figure 43.2) 42 CHARACTER(4) COLUMN IN CORPDATA.EMPLOYEE LABEL 39 CHARACTER(3) COLUMN IN CORPDATA. 5 ..SQL Statements in REXX Programs 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 *......+. 8 /*********************************************************************/ /* A sample program which updates the salaries for those employees */ /* whose current commission total is greater than or equal to the */ /* value of COMMISSION..e.. 4 .. */ ADDRESS '*COMMAND'. is */ /* potentially affected by the retroactive raises) with its total */ /* salary expenses and a count of employees who contributed to the */ /* project.. 1 .+. */ /*********************************************************************/ /* Initialize RC variable */ RC = 0 /* Initialize HV for program usage */ COMMISSION = 2000. Sample REXX Procedure Using SQL Statements (Part 1 of 4) 640 DB2 UDB for AS/400 SQL Programming V4R4 ... 7 .+.. 3 .+. 6 . RAISE_DATE = '1982-06-01'..+. 'CRTPF FILE(CORPDATA/REPORTFILE) RCDLEN(80)' ADDRESS '*COMMAND'. 'SET SALARY = SALARY * ? '. WORK_DAYS = 253.+.... 'OVRDBF FILE(STDOUT) TOFILE(CORPDATA/REPORTFILE) MBR(REPORTFILE)' /* Update the selected employee's salaries by the new percentage. ' :COMMISSION ' /* Commit changes */ 5 EXECSQL... PERCENTAGE = 1.+.. 'EXECUTE S1 USING :PERCENTAGE. 'PREPARE S1 FROM :UPDATE_STMT' 4 EXECSQL. The salaries of those who qualify are */ /* increased by the value of PERCENTAGE. retroactive to RAISE_DATE... 'DLTF FILE(CORPDATA/REPORTFILE)' ADDRESS '*COMMAND'. 'COMMIT' Figure 44.. ordered by */ /* project number and employee ID... A second report shows each */ /* project having an end date occurring after RAISE DATE (i.. /* Create the output file to dump the 2 reports.00.04. 'WHERE COMM >= ? ' EXECSQL.+. Perform an OVRDBF */ /* to allow us to use the SAY REXX command to write to the output */ /* file... ROLLBACK the changes.'. 2 . */ /* A report is generated and dumped to the display which shows the */ /* projects which these employees have contributed to.. */ /* If an error occurs during the update.... */ 3 SIGNAL ON ERROR ERRLOC = 'UPDATE_ERROR' UPDATE_STMT = 'UPDATE CORPDATA/EMPLOYEE '. ..... IF SQLCODE < 0 THEN SIGNAL ERROR */ */ /* Stop the loop when we hit the EOF.----SAY ' ' SELECT_STMT = for Report 1 */ PROJECTS AFFECTED BY EMPLOYEE RAISES' EMPLOYEE NAME ------------SALARY' ------' '. 6 .. 1 . ''||FIRSTNME.EMPNO.EMPNO = EMPLOYEE.. '.+. 4 .. 7 . EMP_ACT. project name the count of employees participating in the project and the total salary cost of the project.PROJNO ' ' RPT1.+. CORPDATA/EMPLOYEE 'WHERE EMP_ACT..EMPNO... 'DECLARE C1 CURSOR FOR S2' 7 EXECSQL. 10 EXECSQL. 2 .EMPNO ' END.'. 8 ERRLOC = 'REPORT_ERROR' /* Report the updated statistics for each project supported by one */ /* of the selected employees.. 5 ..NAME ' ' RPT1.+. ' EXECSQL. EMPNO /* Handle the FETCH errors and warnings inline */ SIGNAL OFF ERROR /* Fetch all of the rows */ DO UNTIL (SQLCODE <> 0) 9 EXECSQL. '..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 *. SALARY 'FROM CORPDATA/EMP_ACT. Sample Programs Using DB2 UDB for AS/400 Statements 641 .+. ' LASTNAME||''..+... 3 .. */ /* Write out the header SAY ' ' SAY ' ' SAY ' ' SAY ' REPORT OF SAY ' ' SAY 'PROJECT EMPID SAY '------. 'FETCH C1 INTO :RPT1. */ 8 IF SQLCODE = 100 THEN LEAVE /* Print out the fetched row */ SAY RPT1.... :RPT1.. those projects potentially affected by the salary raises) generate a report containing the project number. 'CLOSE C1' /* /* /* /* /* For all projects ending at a date later than 'raise_date' (i. Continue so that /* we close the cursor for any warnings.SALARY /* Write out the header for Report 2 */ SAY ' ' SAY ' ' SAY ' ' SAY ' ACCUMULATED STATISTICS BY PROJECT' SAY ' ' SAY 'PROJECT PROJECT NAME SAY 'NUMBER SAY '------.-----------SAY ' ' NUMBER OF EMPLOYEES --------- TOTAL' COST' -----' Figure 44. '.+. Don't try to print out the */ /* fetched values.. '.e.+. 'PREPARE S2 FROM :SELECT_STMT' 6 EXECSQL... */ */ */ */ */ ' RPT1.+.. 'OPEN C1 USING :COMMISSION' 'SELECT DISTINCT PROJNO.EMPNO AND ' COMM >= ? 'ORDER BY PROJNO.SALARY ' /* Process any errors that may have occurred. Sample REXX Procedure Using SQL Statements (Part 2 of 4) Appendix C.. ' :RPT1....PROJNO...NAME. :RPT1. 6 . ADDRESS '*COMMAND'. 'CLOSE C2' /* Delete the OVRDBF so that we will continue writing to the output /* display. 3 .PROJNAME. If it occurred on the report generation. EXECSQL. :RAISE_DATE' /* Handle the FETCH errors and warnings inline */ SIGNAL OFF ERROR /* Fetch all of the rows */ DO UNTIL (SQLCODE <> 0) 12 EXECSQL. 7 . ' SUM( (DAYS(EMENDATE) .. 'OPEN C2 USING :WORK_DAYS.... If the error occurred on the UPDATE.+..... CORPDATA/EMPLOYEE'.. 4 . COUNT(*).. rollback all of */ /* the changes.DAYS(EMSTDATE)) * EMPTIME * '.PROJNO AND '. '.PROJNO. 8 /* Go to the common error handler */ SIGNAL ON ERROR SELECT_STMT = 'SELECT EMP_ACT.'.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 *.. 'FROM CORPDATA/EMP_ACT. 'SQLCODE = ' SQLCODE 14 EXECSQL. Don't try to print out the */ /* fetched values.EMPNO AND '. ' PRENDATE > ? '.PROJNO = PROJECT. 'DECLARE C2 CURSOR FOR S3' EXECSQL.... 'ROLLBACK' END */ */ Figure 44. ' :RPT2. 'ORDER BY 1 ' EXECSQL. Continue so that /* we close the cursor for any warnings..PROJNO ' ' RPT2. 'WHERE EMP_ACT.+. 'DLTOVR FILE(STDOUT)' /* Leave procedure with a successful or warning RC */ EXIT RC /* Error occurred while updating the table or generating the */ /* reports...EMPCOUNT ' ' RPT2.+.+.EMPNO = EMPLOYEE. :RPT2.+.. 1 ..8.. PROJNAME '..2) ) '.. 'FETCH C2 INTO :RPT2..TOTAL_COST ' /* Process any errors that may have occurred.+...PROJNO. 2 .PROJNAME ' ' . */ ERROR: 13 SIGNAL OFF ERROR /* Determine the error location */ SELECT /* When the error occurred on the UPDATE statement */ WHEN ERRLOC = 'UPDATE_ERROR' THEN DO SAY '*** ERROR Occurred while updating table..+. PROJNAME. RPT2.+. */ IF SQLCODE = 100 THEN LEAVE /* Print out the fetched row */ SAY RPT2. Sample REXX Procedure Using SQL Statements (Part 3 of 4) 642 DB2 UDB for AS/400 SQL Programming V4R4 . 5 . :RPT2.TOTAL_COST END. '. 'GROUP BY EMP_ACT. CORPDATA/PROJECT. ' EMP_ACT.. 'PREPARE S3 FROM :SELECT_STMT' 11 EXECSQL.EMPCOUNT. IF SQLCODE < 0 THEN SIGNAL ERROR */ */ /* Stop the loop when we hit the EOF......PROJNO. ' DECIMAL(( SALARY / ? ). display the */ /* REXX RC variable and the SQLCODE and exit the procedure. 24 166945. DAVID LUTZ.60 31033. SALLY NICHOLLS. 'SQLCODE = ' SQLCODE OTHERWISE SAY '*** Application procedure logic error occurred ' END /* Delete the OVRDBF so that we will continue writing to the /* output display. Sample REXX Procedure Using SQL Statements (Part 4 of 4) Report Produced by Sample Programs The following report is produced by each of the preceding sample programs.196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 /* When the error occurred during the report generation */ WHEN ERRLOC = 'REPORT_ERROR' THEN SAY '*** ERROR Occurred while generating reports.00 48360.80 39780. Sample Programs Using DB2 UDB for AS/400 Statements 643 .60 26291. 'DLTOVR FILE(STDOUT)' /* Return the error RC received from SQL.68 93729.84 Appendix C. HEATHER HAAS. WING THOMPSON. REPORT OF PROJECTS AFFECTED BY RAISES PROJECT AD3100 AD3110 AD3111 AD3113 IF1000 IF1000 IF2000 IF2000 MA2100 MA2100 MA2110 MA2111 MA2111 MA2112 OP1000 OP1010 OP1010 OP2010 OP2010 OP2012 PL2100 EMPID 000010 000070 000240 000270 000030 000140 000030 000140 000010 000110 000010 000200 000220 000150 000050 000090 000280 000050 000100 000330 000020 EMPLOYEE NAME HAAS.00 37616. BRUCE GEYER.80 29910.80 42900. HEATHER KWAN. EVA MARINO.28 72806. JENNIFER ADAMSON.20 41782.00 28849.00 41782. */ EXIT RC * * * * * E N D O F S O U R C E */ */ * * * * * Figure 44.00 54860.80 54860.61 114001. CHRISTINE LUCCHESSI.20 39780. THEODORE LEE. SALVATORE PEREZ.00 27196.11 58877.00 30940. '.52 85864.00 29556.00 26384. CHRISTINE PULASKI. JOHN SPENSER. ETHEL GEYER. CHRISTINE BROWN. MARIA KWAN.52 52205. EILEEN SCHNEIDER. JOHN HENDERSON.00 27300.66 55212. ADDRESS '*COMMAND'.40 28475. VICENZO HAAS. SALLY NICHOLLS. MICHAEL SALARY 54860.00 ACCUMULATED STATISTICS BY PROJECT PROJECT NUMBER AD3100 AD3110 AD3111 AD3112 AD3113 IF1000 IF2000 MA2100 MA2110 MA2111 MA2112 PROJECT NAME 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 NUMBER OF EMPLOYEES 1 1 8 9 14 4 5 2 1 3 6 TOTAL COST 19623.70 72114.00 29556.74 28845. 86 167828.11 16348.12 43576.76 91612.60 41294.92 644 DB2 UDB for AS/400 SQL Programming V4R4 .MA2113 OP1000 OP1010 OP2010 OP2011 OP2012 OP2013 PL2100 W L PROD CONT PROGS OPERATION SUPPORT OPERATION SYSTEMS SUPPORT SCP SYSTEMS SUPPORT APPLICATIONS SUPPORT DB/DC SUPPORT WELD LINE PLANNING 5 1 5 2 2 2 2 1 71509.88 37311.62 31224. CRTSQLCBL (Create Structured Query Language COBOL) Command Job: B.I Pgm: B.I PGM( library-name/ REXX: B.I *CURLIB/ Exec program-name ) CRTSQLCBL *LIBL/ SRCFILE( *CURLIB/ library-name/ QLBLSRC source-file-name ) (1) *PGM source-file-member-name SRCMBR( ) OPTION( OPTION Details ) TGTRLS( *CURRENT *PRV VxRxMx ) *LIBL/ INCFILE( *CURLIB/ library-name/ *SRCFILE source-file-name ) COMMIT( *UR *CHG *ALL *RS *CS *NONE *NC *RR CLOSQLCSR( ) *ENDPGM *ENDSQL *ENDJOB ) ALWCPYDTA( *OPTIMIZE *YES *NO ) ALWBLK( *ALLREAD *NONE *READ ) © Copyright IBM Corp. DB2 UDB for AS/400 CL Command Descriptions This appendix contains the syntax diagrams referred to and used in this guide and the DB2 UDB for AS/400 SQL Reference book. 1999 645 .Appendix D. 1997. ' '.CRTSQLCBL *NO *YES 10 severity-level DLYPRP( ) GENLVL( ) DATFMT( *JOB *USA *ISO *EUR *JIS *MDY *DMY *YMD *JUL ) DATSEP( *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 ) DYNDFTCOL( *NO *YES ) *PGMLIB/ SQLPKG( library-name/ *PGM package-name ) 646 DB2 UDB for AS/400 SQL Programming V4R4 .' '-' ' ' *BLANK ) TIMFMT( *HMS *USA *ISO *EUR *JIS ) TIMSEP( *JOB ':' '. DB2 UDB for AS/400 CL Command Descriptions 647 .CRTSQLCBL *NAMING *LIBL SQLPATH( ) collection-name SAAFLAG( *NOFLAG *FLAG ) FLAGSTD( *NONE *ANS ) *LIBL/ PRTFILE( *CURLIB/ library-name/ QSYSPRT printer-file-name ) SRTSEQ( *JOB *JOBRUN *LANGIDUNQ *LANGIDSHR *HEX *LIBL/ table-name *CURLIB/ library-name/ ) LANGID( *JOB *JOBRUN language-ID ) USRPRF( *NAMING *OWNER *USER ) DYNUSRPRF( *USER *OWNER ) QTEMP/ TOSRCFILE( *LIBL/ *CURLIB/ library-name/ QSQLTEMP source-file-name ) TEXT( *SRCMBRTXT *BLANK 'description' ) Appendix D. and then optionally calls the COBOL compiler to compile the program. which precompiles COBOL source containing SQL statements. program-name: Specify the name of the compiled COBOL program. If no library is specified as the current library for the job. the IBM-supplied source file QLBLSRC contains the COBOL source. Purpose The Create Structured Query Language COBOL (CRTSQLCBL) command calls the Structured Query Language (SQL) precompiler. All parameters preceding this point can be specified in positional form. 648 DB2 UDB for AS/400 SQL Programming V4R4 . Parameters PGM Specifies the qualified name of the compiled program. *CURLIB: The current library for the job is searched. The name of the source file can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. 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. the QGPL library is used. SRCFILE Specifies the qualified name of the source file that contains the COBOL source with SQL statements. QLBLSRC: If a COBOL source file name is not specified.CRTSQLCBL OPTION Details: *NOSRC *NOSOURCE *SOURCE *SRC *NOXREF *XREF *GEN *NOGEN *JOB *PERIOD *SYSVAL *COMMA *NOLSTDBG *LSTDBG *QUOTESQL *APOSTSQL *QUOTE *APOST *SYS *SQL *NOSECLVL *SECLVL Notes: 1. the QGPL library is used. library-name: Specify the name of the library to be searched. If no library is specified as the current library for the job. library name: Specify the name of the library where the compiled COBOL program is created. produces a temporary source member. source-file-member-name: Specify the name of the member that contains the COBOL source. *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. the PGM name specified on the PGM parameter is used. *SOURCE or *SRC: The precompiler produces a source printout consisting of COBOL source input. any numeric constants in lists (such as in the SELECT clause or the VALUES clause) must be separated by a comma followed by a Appendix D.CRTSQLCBL source-file-name: Specify the name of the source file that contains the COBOL source. OPTION Specifies whether one or more of the following options are used when the COBOL source is precompiled. This parameter is specified only if the source file name in the SRCFILE parameter is a database file. 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. An SQL package object is created if a relational database name is specified on the RDB parameter. Note: If QDECFMT specifies that the value used as the decimal point is a comma. *NOGEN: The precompiler does not call the COBOL compiler. device file. Element 2: Cross-Reference Options *NOXREF: The precompiler does not cross-reference names. If this parameter is not specified. Element 3: Program Creation Options *GEN: The compiler creates a program that can run after the program is compiled. If an option is specified more than once. DB2 UDB for AS/400 CL Command Descriptions 649 . or an inline data file. *SYSVAL: The value used as the decimal point for numeric constants in SQL statements is the QDECFMT system value. 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. SRCMBR Specifies the name of the source file member that contains the COBOL source. *XREF: The precompiler cross-references items in the program to the statement numbers in the program that refer to those items. the last option specified is used. This source file should have a record length of 92 bytes. The source file can be a database file. and a program and SQL package are not created. or if two options conflict. 650 DB2 UDB for AS/400 SQL Programming V4R4 . TGTRLS Specifies the release of the operating system on which the user intends to use the object being created.23.23. *LSTDBG: The SQL precompiler generates a listing view. 2. VALUES(1.23. When creating a program on a remote database other than an AS/400 system. Element 5: String Delimiter Options *QUOTESQL: A double quote (") is the string delimiter in the SQL statements.1) is equivalent to VALUES(1. Element 7: Naming Convention Option *SYS: The system naming convention (library-name/file-name) is used. 4. VALUES(1.2.CRTSQLCBL blank.table-name) is used. *PERIOD: The value used as the decimal point for numeric constants in SQL statements is a period. Element 6: Literal Options *QUOTE: A double quote (") is used for non-numeric literals and Boolean literals in the COBOL statements. *SECLVL: Second-level text with replacement data is added for all messages on the listing.4.2.4.1. Element 9: Debug Listing View *NOLSTDBG: Error and debug information is not generated.23. *APOSTSQL: An apostrophe (') is the string delimiter in the SQL statements.1. 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. Element 8: Second-Level Message Text Option *NOSECLVL: Second-level text descriptions are not added to the listing. *APOST: An apostrophe (') is used for non-numeric literals and Boolean literals in the COBOL statements. 4.1) in which the decimal point is a period.1) is equivalent to VALUES(1. 2. 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. For example. For example. *COMMA: The value used as the decimal point for numeric constants in SQL statements is a comma.1. *SQL: The SQL naming convention (collection-name.1) where the decimal point is a period.1. *SQL must be specified as the naming convention. modification level 0. For example. Note: If V2R3M5 is running on the system. For example. If no library is specified as the current library for the job. *CURRENT: The object is to be used on the release of the operating system currently running on the user’s system. 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. if V2R3M5 is running on the system. Only SQL tables. 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. 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. and modification level. if V2R3M5 is running on the user’s system.CRTSQLCBL In the examples given for the *CURRENT and *PRV values. *SRCFILE: The qualified source file specified in the SRCFILE parameter contains the source file member(s) specified on any SQL INCLUDE statement. COMMIT Specifies whether SQL statements in the compiled program are run under commitment control. *PRV means the user intends to use the object on a system with V2R2M0 installed. Note: Files referenced in the COBOL source are not affected by this option. Files referred to in the host language source are not affected by this option. *CURLIB: The current library for the job is searched. If you specify a release-level which is earlier than the earliest release level supported by this command. and when specifying the release-level value. the format VxRxMx is used to specify the release. library-name: Specify the name of the library to be searched. V2R3M0 is version 2. For example. *CURRENT means the user intends to use the object on a system with V2R3M5 installed. the QGPL library is used. DB2 UDB for AS/400 CL Command Descriptions 651 . Valid values depend on the current version. Appendix D. and they change with each new release. and Mx is the modification level. release 3. The name of the source file can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. source-file-name: Specify the name of the source file that contains the source file member(s) specified on any SQL INCLUDE statement. release. where Vx is the version. SQL views. *PRV: The object is to be used on the previous release with modification level 0 of the operating system. Rx is the release. The object can be used on a system with the specified release or with any subsequent release of the operating system installed. and SQL packages referred to in SQL statements are affected. specify TGTRLS(V2R3M0) not TGTRLS(*CURRENT). and the object is to be used on a system with V2R3M0 installed. The user can also use the object on a system with any subsequent release of the operating system installed. or ROLLBACK (without HOLD) SQL statements. The programs higher on the call stack do not need to have run SQL statements. *ALL or *RS: Specifies the objects referred to in SQL ALTER. Uncommitted changes in other jobs cannot be seen. deleted. CREATE. *RR: Specifies the objects referred to in SQL ALTER. SQL cursors are explicitly closed when you issue the CLOSE. RENAME. SQL cursors are left open. 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. and inserted are locked until the end of the unit of work (transaction). and LOCK TABLE locks are released. and REVOKE statements and the rows updated. RENAME. LOCK TABLE locks are released when the first SQL program on the call stack ends. CLOSQLCSR Specifies when SQL cursors are implicitly closed. All tables referred to in SELECT. updated. and LOCK TABLE locks are held when the first SQL program on the call stack ends. RENAME. RENAME. COMMENT ON. CREATE. COMMIT. SQL prepared statements are discarded. deleted. deleted. and REVOKE statements and the rows updated. and LOCK TABLE locks are released when the first SQL program on the call stack ends. and INSERT statements are locked exclusively until the end of the unit of work (transaction). CREATE. and REVOKE statements and the rows selected. CALL. and inserted are locked until the end of the unit of work (transaction). LABEL ON. GRANT. LABEL ON. and LOCK TABLE locks are released when the job ends. *NONE or *NC: Specifies that commitment control is not used. SQL prepared statements are discarded. *CS: Specifies the objects referred to in SQL ALTER. and inserted are locked until the end of the unit of work (transaction). CREATE. CALL. DROP. A row that is selected. Uncommitted changes in other jobs cannot be seen. LABEL ON. Uncommitted changes in other jobs can be seen. GRANT. DROP. SQL cursors are closed. GRANT. and REVOKE statements and the rows selected. and inserted are locked until the end of the unit of work (transaction). LABEL ON. DROP. updated. SQL prepared statements are implicitly discarded. UPDATE. SQL prepared statements are preserved. *ENDJOB: SQL cursors remain open between calls and can be fetched without running another SQL OPEN. GRANT. DELETE. SQL cursors are closed. Uncommitted changes in other jobs cannot be seen. *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. DROP. If *ENDSQL is specified for a program that is the first SQL program called (the first SQL program on the call stack). 652 DB2 UDB for AS/400 SQL Programming V4R4 . *ENDPGM: SQL cursors are closed and SQL prepared statements are discarded when the program ends. CALL. Uncommitted changes in other jobs can be seen. *NONE or *NC must be used. is locked until the next row is selected. deleted. COMMENT ON.CRTSQLCBL *CHG or *UR: Specifies the objects referred to in SQL ALTER. the program is treated as if *ENDPGM was specified. If the SQL DROP COLLECTION statement is included in the program. *NONE or *NC cannot be specified. COMMENT ON. COMMENT ON. CALL. but not updated. *OPTIMIZE: The system determines whether to use the data retrieved directly from the database or to use a copy of the data. *ALLREAD: Rows are blocked for read-only cursors if *NONE or *CHG is specified on the COMMIT parameter. *YES: A copy of the data is used only when necessary. v May reduce the amount of time required to retrieve the first row of data for a query. Specifying *NONE: v Guarantees that the data retrieved is current. DB2 UDB for AS/400 CL Command Descriptions 653 . Specifying *ALLREAD: v Allows record blocking under commitment control level *CHG in addition to the blocking allowed for *READ. If a temporary copy of the data is required to perform the query. a ROLLBACK statement in host languages. or the ROLLBACK HOLD SQL statement does not reposition a read-only cursor when *ALLREAD is specified. If COMMIT is *CHG or *CS and ALWBLK is not *ALLREAD. 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. an error message is returned. *NO: A copy of the data is not allowed. using EXECUTE IMMEDIATE). 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. but limits queries in the following ways: – The Rollback (ROLLBACK) command. *NONE: Rows are not blocked for retrieval of data for cursors. Appendix D. v Can degrade the overall performance of a query that retrieves a large number of rows. v Can improve the performance of almost all read-only cursors in programs. and the extent to which blocking can be used for read-only cursors. then a copy of the data is used only when it is necessary to run a query. – Dynamic running of a positioned UPDATE or DELETE statement (for example. *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. cannot be used to update a row in a cursor unless the DECLARE statement for the cursor includes the FOR UPDATE clause. The decision is based on which method provides the best performance.CRTSQLCBL | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ALWCPYDTA Specifies whether a copy of the data can be used in a SELECT statement. or if COMMIT is *ALL or *RR. ALWBLK Specifies whether the database manager can use record blocking. 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. *ISO. EXECUTE. Note: An input date string that uses the format *USA. When the dynamic statement is used. If you specify *YES on this parameter. 10: The default severity level is 10. 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. you should check the SQLCODE and SQLSTATE after running an OPEN. *NO: Dynamic statement validation is not delayed.mm. the validation is completed and an access plan is built.CRTSQLCBL | | Specifying *READ can improve the overall performance of queries that meet the above conditions and retrieve a large number of records. severity-level: Specify a value ranging from 0 through 40. GENLVL Specifies the severity level at which the create operation fails. the access plan is revalidated.yyyy) is used. When the dynamic statement is prepared. DATFMT Specifies the format used when accessing date result columns. the access plan is validated. For input date strings. *JOB: The format specified for the job is used. All output date fields are returned in the specified format. or DESCRIBE SQL statement. DLYPRP Specifies whether the dynamic statement validation for a PREPARE statement is delayed until an OPEN. Because the authority or the existence of objects referred to by the dynamic statement may change. *EUR. If errors occur that have a severity level greater than or equal to this value. the specified value is used to determine whether the date is specified in a valid format. EXECUTE. *EUR. you must still check the SQLCODE or SQLSTATE after issuing the OPEN or EXECUTE statement to ensure that the dynamic statement is still valid. When the dynamic statement is used in an OPEN or EXECUTE statement. or DESCRIBE statement to ensure that the dynamic statement is valid. 654 DB2 UDB for AS/400 SQL Programming V4R4 . 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. or *JIS is always valid. Delaying validation improves performance by eliminating redundant validation. or *JIS must be specified. EXECUTE. *ISO. *EUR: The European date format (dd. 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. or DESCRIBE statement is run. *ISO: The International Organization for Standardization (ISO) date format (yyyy-mm-dd) is used. Note: If you specify *YES. *YES: Dynamic statement validation is delayed until the dynamic statement is used in an OPEN. the operation ends. *YMD: The date format (yy/mm/dd) is used. *HMS: The (hh:mm:ss) format is used. or *HMS with a time separator of colon or period. *JIS. *JIS: The Japanese Industrial Standard time format (hh:mm:ss) is used. If a relational database is specified on the RDB parameter and the database is on a system that is not another AS/400 system.CRTSQLCBL *JIS: The Japanese Industrial Standard date format (yyyy-mm-dd) is used. *DMY. Note: An input date string that uses the format *USA. TIMFMT Specifies the format used when accessing time result columns. ’ ’: A blank ( ) is used. Use the Display Job (DSPJOB) command to determine the current value for the job. *BLANK: A blank ( ) is used.’: A comma (. the specified value is used to determine whether the time is specified in a valid format. *ISO. Note: This parameter applies only when *JOB.ss) is used. *DMY: The date format (dd/mm/yy) is used. *EUR.mm. For input time strings. where xx is AM or PM. or *JUL is specified on the DATFMT parameter. ’/’: A slash (/) is used. *MDY.’: A period (. DB2 UDB for AS/400 CL Command Descriptions 655 . *EUR. Appendix D. ’.) is used.) is used. *ISO: The International Organization for Standardization (ISO) time format (hh. the time format must be *USA.mm. *MDY: The date format (mm/dd/yy) is used. *JUL: The Julian date format (yy/ddd) is used.ss) is used. *JOB: The date separator specified for the job at precompile time is used. ’. *ISO. DATSEP Specifies the separator used when accessing date result columns. *YMD. *EUR: The European time format (hh. ’-’: A dash (-) is used. or *JIS is always valid. *USA: The United States time format (hh:mm xx) is used. *YES: A new program or SQL package is created. *CURRENT: The user profile under which the current job is running is used. ’ ’: A blank ( ) is used. The value of this parameter is passed to the CRTCBLPGM command. ’:’: A colon (:) is used.CRTSQLCBL TIMSEP Specifies the separator used when accessing time result columns. USER Specifies the user name sent to the remote system when starting the conversation.’: A period (. RDB Specifies the name of the relational database where the SQL package object is created. ’. The SQL statements will access the local database. More information on this parameter is in Appendix A. *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.’: A comma (. *JOB: The time separator specified for the job at precompile time 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. ’. *BLANK: A blank ( ) is used. *LOCAL: The program is created as a distributed SQL program. When the name of the local relational database is specified. the program created is still a distributed SQL program. An SQL package object is not created as part of the precompile process. Note: This parameter applies only when *HMS is specified on the TIMFMT parameter. ″Expanded Parameter Descriptions″ in the CL Reference (Abridged) book. 656 DB2 UDB for AS/400 SQL Programming V4R4 . This parameter is valid only when RDB is specified. The program object is not a distributed program and the Create Structured Query Language Package (CRTSQLPKG) command cannot be used. *NONE: An SQL package object is not created. Use the Display Job (DSPJOB) command to determine the current value for the job.) is used. and any existing program or SQL package of the same name and type in the specified library is moved to QRPLOBJ.) is used. 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. The SQL statements will access the local database. indexes. *PGM: The package name is the same as the program name. Consecutive CONNECT statements to additional relational databases do not result in disconnection of previous connections. This parameter applies only to static SQL statements. library-name: Specify the name of the library where the package is created. This parameter is valid only if RDB is specified. *NO: Do not use the value specified on the DFTRDBCOL parameter for unqualified names of tables. indexes. views. DFTRDBCOL Specifies the collection name used for the unqualified names of tables. Consecutive CONNECT statements result in the previous connection being disconnected before a new connection is established. If this value is specified. collection-name: Specify the name of the collection identifier. views.CRTSQLCBL user-name: Specify the user name to be used for the application server job. *NONE: The naming convention defined on the OPTION parameter is used. The naming convention specified on the OPTION parameter is used. *DUW: CONNECT (Type 2) semantics are used to support distributed unit of work. indexes. *NONE: No password is sent. DB2 UDB for AS/400 CL Command Descriptions 657 . and SQL packages in dynamic SQL statements. The library values are: *PGMLIB: The package is created in the library with the same name as the library containing the program. SQLPKG Specifies the qualified name of the SQL package created on the relational database specified on the RDB parameter of this command. Refer to the SQL Reference book for more information. *YES: The collection name specified on the DFTRDBCOL parameter will be used for the unqualified names of the tables. | | | | | | | | | | DYNDFTCOL Specifies whether the default collection name specified for the DFTRDBCOL parameter is also used for dynamic statements. This value is used instead of the naming convention specified on the OPTION parameter. PASSWORD Specifies the password to be used on the remote system. views. *RUW: CONNECT (Type 1) semantics are used to support remote unit of work. RDBCNNMTH Specifies the semantics used for CONNECT statements. password: Specify the password of the user name specified on the USER parameter. and SQL packages. Appendix D. and SQL packages for dynamic SQL statements. USER(*CURRENT) must also be specified. and user defined types in static SQL statements. *LIBL: The path used is the library list at runtime. A maximum of 43 individual collections may be specified. This parameter flags SQL statements to verify whether they conform to the following standards. ANSI X3. where ″userid″ is the value of the USER special register.2 entry *NONE: The precompiler does not check to see whether SQL statements conform to ANSI standards. *NAMING: The path used depends on the naming convention specified on the OPTION parameter. SC26-3255-00.135-1992 entry ISO 9075-1992 entry FIPS 127. If no library is specified as the current library for the job. the QGPL library is used. *FLAG: The precompiler checks to see whether SQL statements conform to IBM SQL syntax. FLAGSTD Specifies the American National Standards Institute (ANSI) flagging function.CRTSQLCBL package-name: Specify the name of the package created on the remote database specified on the RDB parameter. *NOFLAG: The precompiler does not check to see whether SQL statements conform to IBM SQL syntax. the path used is *LIBL. 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. collection-name: Specify a list of one or more collection names. | | | | | | | | | | | | SQLPATH Specifies the path to be used to find procedures. functions. the path used is ″QSYS″. the collection-name takes the place of userid. For *SYS naming. SAAFLAG Specifies the IBM SQL flagging function. the current library list at runtime. PRTFILE Specifies the qualified name of the printer device file to which the listing is directed. ″userid″. 658 DB2 UDB for AS/400 SQL Programming V4R4 . 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 job’s library list are searched until the first match is found. ″QSYS2″. *ANS: The precompiler checks to see whether SQL statements conform to ANSI standards. For *SQL naming. If a collection-name is specified on the DFTRDBCOL parameter. *CURLIB: The current library for the job is searched. SRTSEQ(*JOBRUN) is valid only when LANGID(*JOBRUN) is also specified. *HEX: A sort sequence table is not used. Appendix D. The profile of either the program owner or the program user is used to control which objects can be used by the program object. For distributed applications. *JOB: The LANGID value for the job is retrieved during the precompile. printer-file-name: Specify the name of the printer device file to which the precompiler printout is directed. 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. For distributed applications. SRTSEQ Specifies the sort sequence table to be used for string comparisons in SQL statements. the QGPL library is used. LANGID Specifies the language identifier to be used when SRTSEQ(*LANGIDUNQ) or SRTSEQ(*LANGIDSHR) is specified. including the authority that the program object has for each object in static SQL statements. DB2 UDB for AS/400 CL Command Descriptions 659 . If no library is specified as the current library for the job. *LANGIDSHR: The shared-weight sort table for the language specified on the LANGID parameter is used. library-name: Specify the name of the library to be searched. The name of the sort sequence table can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. The hexadecimal values of the characters are used to determine the sort sequence.CRTSQLCBL QSYSPRT: If a file name is not specified. table-name: Specify the name of the sort sequence table to be used. *JOBRUN: The LANGID value for the job is retrieved when the program is run. *LANGIDUNQ: The unique-weight sort table for the language specified on the LANGID parameter is used. *JOB: The SRTSEQ value for the job is retrieved during the precompile. language-id: Specify a language identifier to be used by the program. the precompiler printout is directed to the IBM-supplied printer file QSYSPRT. *CURLIB: The current library for the job is searched. *JOBRUN: The SRTSEQ value for the job is retrieved when the program is run. USRPRF Specifies the user profile that is used when the compiled program object is run. LANGID(*JOBRUN) is valid only when SRTSEQ(*JOBRUN) is also specified. More information on this parameter is in Appendix A. the text is blank. library-name: Specify the name of the library that is to contain the output source file. *LIBL: The job’s library list is searched for the specified file. *SRCMBRTXT: The text is taken from the source file member being used to create the COBOL program. Distributed dynamic SQL statements are run under the user profile of the SQL package’s owner. QSQLTEMP: The source file QSQLTEMP will be used. USRPRF(*OWNER) is used. | | | | | | | | | | | | | | | | | 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. Distributed dynamic SQL statements are run under the user profile of the application server job. *OWNER: The user profiles of both the program owner and the program user are used when the program is run. source-file-name: Specify the name of the source file to contain the output source member. the QGPL library will be used.CRTSQLCBL *NAMING: The user profile is determined by the naming convention. *BLANK: Text is not specified. *OWNER: Local dynamic SQL statements are run under the user profile of the program’s owner. or by using either the Add Physical File Member (ADDPFM) or Change Physical File Member (CHGPFM) command. The possible library values are: QTEMP: The library QTEMP will be used. the file will be created in the current library. *CURLIB: The current library for the job will be used. ″Expanded Parameter Descriptions″ in the CL Reference (Abridged) book. If no library is specified as the current library for the job. *USER: The profile of the user running the program object is used. If the naming convention is *SQL. If the source file is an inline file or a device file. If the naming convention is *SYS. *USER: Local dynamic SQL statements are run under the user profile of the job. TEXT Specifies the text that briefly describes the program and its function. The output member will have the same name as the name that is specified for the SRCMBR parameter. DYNUSRPRF Specifies the user profile used for dynamic SQL statements. USRPRF(*USER) is used. If the specified source file is not found. If the file is not found in any library in the library list. it will be created. Text for a database source member can be added or changed by using the Start Source Entry Utility (STRSEU) command. 660 DB2 UDB for AS/400 SQL Programming V4R4 . CRTSQLCBLI (Create SQL ILE COBOL Object) Command Job: B.CRTSQLCBL ’description’: Specify no more than 50 characters of text.I OBJ( library-name/ REXX: B. 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. enclosed in apostrophes. DB2 UDB for AS/400 CL Command Descriptions 661 .I Pgm: B.I *CURLIB/ Exec object-name ) CRTSQLCBLI *LIBL/ SRCFILE( *CURLIB/ library-name/ QCBLLESRC source-file-name ) (1) *OBJ source-file-member-name SRCMBR( ) OPTION( OPTION Details ) TGTRLS( *CURRENT *PRV VxRxMx ) OBJTYPE( *PGM *MODULE *SRVPGM ) *LIBL/ INCFILE( *CURLIB/ library-name/ *SRCFILE source-file-name ) Appendix D. ' '-' ' ' *BLANK ) 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 ) RDBCNNMTH( *DUW *RUW ) DFTRDBCOL( *NONE collection-name ) 662 DB2 UDB for AS/400 SQL Programming V4R4 .' '.' '.CRTSQLCBLI *UR *CHG *ALL *RS *CS *NONE *NC *RR *ENDACTGRP *ENDMOD CLOSQLCSR( ) ) COMMIT( ALWCPYDTA( *OPTIMIZE *YES *NO ) ALWBLK( *ALLREAD *NONE *READ ) DLYPRP( *NO *YES ) GENLVL( 10 severity-level ) DATFMT( *JOB *USA *ISO *EUR *JIS *MDY *DMY *YMD *JUL ) DATSEP( *JOB '/' '. DB2 UDB for AS/400 CL Command Descriptions 663 .CRTSQLCBLI *NO *YES DYNDFTCOL( ) *OBJLIB/ SQLPKG( library-name/ *OBJ package-name ) SQLPATH( *NAMING *LIBL ) collection-name SAAFLAG( *NOFLAG *FLAG ) FLAGSTD( *NONE *ANS ) DBGVIEW( *NONE *SOURCE ) USRPRF( *NAMING *OWNER *USER ) DYNUSRPRF( *USER *OWNER ) SRTSEQ( *JOB *JOBRUN *LANGIDUNQ *LANGIDSHR *HEX *LIBL/ table-name *CURLIB/ library-name/ ) LANGID( *JOB *JOBRUN language-identifier ) OUTPUT( *NONE *PRINT ) *LIBL/ PRTFILE( *CURLIB/ library-name/ QSYSPRT printer-file-name ) Appendix D. a program. or a service program. produces a temporary source member. and then optionally calls the ILE COBOL compiler to create a module.CRTSQLCBLI QTEMP/ TOSRCFILE( *LIBL/ *CURLIB/ library-name/ QSQLTEMP source-file-name ) TEXT( *SRCMBRTXT *BLANK 'description' ) OPTION Details: *XREF *NOXREF *GEN *NOGEN *JOB *SYSVAL *PERIOD *COMMA *SYS *SQL *NOSECLVL *SECLVL *QUOTESQL *APOSTSQL *QUOTE *APOST *NOEVENTF *EVENTF *OPTLOB *NOOPTLOB Notes: 1. If no library is specified as the current library for the job. SRCFILE Specifies the qualified name of the source file that contains the COBOL source with SQL statements. object-name: Specify the name of the object that is being created. The name of the source file can be qualified by one of the following library values: 664 DB2 UDB for AS/400 SQL Programming V4R4 . the QGPL library is used. *CURLIB: The new object is created in the current library for the job. 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. Parameters OBJ Specifies the qualified name of the object being created. library-name: Specify the name of the library where the object is created. 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. library-name: Specify the name of the library to be searched. service program. *CURLIB The current library for the job is searched. or SQL package are not created. source-file-name: Specify the name of the source file that contains the COBOL source. 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. *PERIOD: The value used as the decimal point for numeric constants in SQL statements is a period (. *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. source-file-member-name: Specify the name of the member that contains the COBOL source. the source file QCBLLESRC contains the COBOL source. or if two options conflict. If an option is specified more than once.CRTSQLCBLI *LIBL All libraries in the job’s library list are searched until the first match is found. If this parameter is not specified. SRCMBR Specifies the name of the source file member that contains the COBOL source. and a module. *NOGEN: The precompiler does not call the ILE COBOL compiler. QCBLLESRC: If the source file name is not specified.). DB2 UDB for AS/400 CL Command Descriptions 665 . Appendix D. *SYSVAL: The value used as the decimal point for numeric constants in SQL statements is the QDECFMT system value. program. the last option specified is used. the QGPL library is used. the OBJ name specified on the OBJ parameter is used. If no library is specified as the current library for the job. *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. This parameter is specified only if the source file name in the SRCFILE parameter is a database file. OPTION Specifies whether one or more of the following options are used when the COBOL source is precompiled. Element 8: Event File Creation *NOEVENTF: The compiler will not produce an event file for use by CoOperative Development Environment/400 (CODE/400).1) is equivalent to VALUES(1. *APOST: An apostrophe (') is used for literals which are not numeric and Boolean literals in the COBOL statements.23. *SECLVL: Second-level text with replacement data is added for all messages on the listing. | Element 9: Large Object Optimization for DRDA 666 DB2 UDB for AS/400 SQL Programming V4R4 . CODE/400 uses this file to offer error feedback integrated with the CODE/400 editor.1.23.1.). VALUES(1. 4. For example.23.CRTSQLCBLI Note: If QDECFMT specifies that the value used as the decimal point is a comma (.). Element 5: Second-Level Message Text Option *NOSECLVL: Second-level text descriptions are not added to the listing. Element 6: String Delimiter Options *QUOTESQL: A double quote (") is the string delimiter in the SQL statements. 4.1) is equivalent to VALUES(1. 2.) followed by a blank ( ).) followed by a blank( ). *SQL: The SQL naming convention is used (collection-name.).4. VALUES(1.).4. For example.2.1. *SQL must be specified as the naming convention. *EVENTF: The compiler produces an event file for use by CoOperative Development Environment/400 (CODE/400).1) where the decimal point is a period(.1.table-name). The event file will be created as a member in the file EVFEVENT in your source library.23. Note: Any numeric constants in lists (such as in the SELECT clause or the VALUES clause) must be separated by a comma (. When creating a program on a remote database other than an AS/400 system. *APOSTSQL: An apostrophe (') is the string delimiter in the SQL statements.2. Element 4: Naming Convention Options *SYS: The system naming convention (library-name/file-name) is used. Element 7: Literal Options *QUOTE: A double quote (") is used for literals which are not numeric and Boolean literals in the COBOL statements.1) in which the decimal point is a period (. 2. This option is normally specified by CODE/400 on your behalf. *COMMA: The value used as the decimal point for numeric constants in SQL statements is a comma (. any numeric constants in lists (such as in the SELECT clause or the VALUES clause) must be separated by a comma (. Rx is the release. *CURRENT: The object is to be used on the release of the operating system currently running on the user’s system. Note: If V2R3M5 is running on the system. The user can also use the object on a system with any subsequent release of the operating system installed. *PRV: The object is to be used on the previous release with modification level 0 of the operating system. release. TGTRLS Specifies the release of the operating system on which the user intends to use the object being created. This option can cause performance to degrade. *NOOPTLOB:There is no restriction on whether a column is retrieved into a LOB locator or into a LOB host variable. If you specify a release-level which is earlier than the earliest release level supported by this command. modification level 0. This option remains in effect until the cursor is closed. no subsequent FETCH for that cursor can use a LOB locator for that column. specify TGTRLS(V2R3M0) not TGTRLS(*CURRENT). Valid values depend on the current version. *CURRENT means the user intends to use the object on a system with V2R3M5 installed. and Mx is the modification level. and they change with each new release. The user can also use the object on a system with any subsequent release of the operating system installed. V2R3M0 is version 2. In the examples given for the *CURRENT and *PRV values.CRTSQLCBLI *OPTLOB: The first FETCH for a cursor derermines how the cursor will be used for LOBs (Large Objects) on all subsequent FETCHes. OBJTYPE Specifies the type of object being created. If the first FETCH places the LOB column into a LOB host variable. The object can be used on a system with the specified release or with any subsequent release of the operating system installed. the format VxRxMx is used to specify the release. *PRV means the user intends to use the object on a system with V2R2M0 installed. and the object is to be used on a system with V2R3M0 installed. For example. if V2R3M5 is running on the system. and when specifying the release-level value. *PGM: The SQL precompiler issues the CRTBNDCBL command to create the bound program. if V2R3M5 is running on the user’s system. Appendix D. release-level: Specify the release in the format VxRxMx. For example. release 3. DB2 UDB for AS/400 CL Command Descriptions 667 . *MODULE: The SQL precompiler issues the CRTCBLMOD command to create the module. and modification level. If the first FETCH uses a LOB locator to access a LOB column. an error message is sent indicating the earliest supported release. where Vx is the version. no subsequent FETCH for that cursor can fetch that LOB column into a LOB host variable. For example. and REVOKE statements and the rows selected. CREATE. source-file-name: Specify the name of the source file that contains the source file members specified on any SQL INCLUDE statement. INCFILE Specifies the qualified name of the source file that contains members included in the program with any SQL INCLUDE statement. library-name: Specify the name of the library to be searched. updated. CREATE. DROP. GRANT. When OBJTYPE(*PGM) or OBJTYPE(*SRVPGM) is specified and the RDB parameter is also specified. or SQL package are not created. GRANT. 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. GRANT. service program. COMMENT ON. LABEL ON. *CS: Specifies the objects referred to in SQL ALTER. *CURLIB: The current library for the job is searched. LABEL ON. CREATE. an SQL package is not created and you must issue the CRTSQLPKG command after the CRTPGM or CRTSRVPGM command has created the program. *CHG or *UR: Specifies the objects referred to in SQL ALTER. RENAME. only the SQL temporary source member is generated and a module. CALL. *ALL or *RS: Specifies the objects referred to in SQL ALTER. and inserted are locked until the end of the unit of 668 DB2 UDB for AS/400 SQL Programming V4R4 . program. The name of the source file can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. and inserted are locked until the end of the unit of work (transaction). DROP. Uncommitted changes in other jobs can be seen. If *NOGEN is specified. COMMIT Specifies whether SQL statements in the compiled unit are run under commitment control. and REVOKE statements and the rows updated. If no library is specified as the current library for the job. CALL. RENAME. and SQL packages referred to in SQL statements are affected. and inserted are locked until the end of the unit of work (transaction). 2. the QGPL library is used. When OBJTYPE(*MODULE) is specified. SQL views. DROP. Notes: 1. and REVOKE statements and the rows updated. *SRCFILE: The qualified source file specified in the SRCFILE parameter contains the source file members specified on any SQL INCLUDE statement. deleted. deleted. Only SQL tables. COMMENT ON. Uncommitted changes in other jobs cannot be seen. Files referred to in the host language source are not affected by this option. COMMENT ON. LABEL ON. deleted.CRTSQLCBLI *SRVPGM: The SQL precompiler issues the CRTCBLMOD and CRTSRVPGM commands to create the service program. the CRTSQLPKG command is issued by the SQL precompiler after the program has been created. RENAME. CALL. deleted. an error message is returned. *NONE or *NC must be used.CRTSQLCBLI work (transaction). is locked until the next row is selected. and REVOKE statements and the rows selected. *ENDACTGRP: SQL cursors are closed. *ENDMOD: SQL cursors are closed and SQL prepared statements are implicitly discarded when the module is exited. GRANT. If the SQL DROP COLLECTION statement is included in the program. COMMENT ON. or ROLLBACK (without HOLD) SQL statements. DROP. RENAME. Uncommitted changes in other jobs cannot be seen. The decision is based on which method provides the best performance. then a copy of the data is used only when it is necessary to run a query. UPDATE. *NO: A copy of the data is not allowed. All tables referred to in SELECT. 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. LOCK TABLE locks are released when the activation group ends. *OPTIMIZE: The system determines whether to use the data retrieved directly from the database or to use a copy of the data. CREATE. Uncommitted changes in other jobs can be seen. SQL cursors are explicitly closed when you issue the CLOSE. SQL prepared statements are implicitly discarded. If a temporary copy of the data is required to perform the query. or if COMMIT is *ALL or *RR. and the extent to which blocking can be used for read-only cursors. and LOCK TABLE locks are released when the activation group ends. Uncommitted changes in other jobs cannot be seen. updated. Specifying *ALLREAD: v Allows record blocking under commitment control level *CHG in addition to the blocking allowed for *READ. 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. COMMIT. ALWBLK Specifies whether the database manager can use record blocking. *YES: A copy of the data is used only when necessary. If COMMIT is *CHG or *CS and ALWBLK is not *ALLREAD. *RR: Specifies the objects referred to in SQL ALTER. CALL. *NONE or *NC cannot be specified. and LOCK TABLE locks are released. DB2 UDB for AS/400 CL Command Descriptions 669 . SQL prepared statements are implicitly discarded. but not updated. and INSERT statements are locked exclusively until the end of the unit of work (transaction). *ALLREAD: Rows are blocked for read-only cursors if *NONE or *CHG is specified on the COMMIT parameter. and inserted are locked until the end of the unit of work (transaction). LABEL ON. DELETE. *NONE or *NC: Specifies that commitment control is not used. A row that is selected. Appendix D. CLOSQLCSR Specifies when SQL cursors are implicitly closed. | | | | | | | | | | | | | | | | | | | | ALWCPYDTA Specifies whether a copy of the data can be used in a SELECT statement. When the dynamic statement is used. EXECUTE. Specifying *NONE: v Guarantees that the data retrieved is current. When the dynamic statement is prepared. or DESCRIBE statement is run. *READ: Records are blocked for read-only retrieval of data for cursors when: v *NONE is specified on the COMMIT parameter. Delaying validation improves performance by eliminating redundant validation. 670 DB2 UDB for AS/400 SQL Programming V4R4 . EXECUTE. the access plan is revalidated. the validation is completed and an access plan is built. a ROLLBACK statement in host languages. 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.CRTSQLCBLI | | | | | | | | | | | | | | | | | | | | | | | | | | | v Can improve the performance of almost all read-only cursors in programs. or DESCRIBE statement to ensure that the dynamic statement is valid. you should check the SQLCODE and SQLSTATE after running an OPEN. 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. you must still check the SQLCODE or SQLSTATE after issuing the OPEN or EXECUTE statement to ensure that the dynamic statement is still valid. When the dynamic statement is used in an OPEN or EXECUTE statement. *YES: Dynamic statement validation is delayed until the dynamic statement is used in an OPEN. or DESCRIBE SQL statement. cannot be used to update a row in a cursor unless the DECLARE statement for the cursor includes the FOR UPDATE clause. *NO: Dynamic statement validation is not delayed. which indicates that commitment control is not used. EXECUTE. If you specify *YES on this parameter. Specifying *READ can improve the overall performance of queries that meet the above conditions and retrieve a large number of records. DLYPRP Specifies whether the dynamic statement validation for a PREPARE statement is delayed until an OPEN. *NONE: Rows are not blocked for retrieval of data for cursors. Because the authority or the existence of objects referred to by the dynamic statement may change. or the ROLLBACK HOLD SQL statement does not reposition a read-only cursor when *ALLREAD is specified. the access plan is validated. but limits queries in the following ways: – The Rollback (ROLLBACK) command. v May reduce the amount of time required to retrieve the first row of data for a query. – Dynamic running of a positioned UPDATE or DELETE statement (for example. using EXECUTE IMMEDIATE). GENLVL Specifies the severity level at which the create operation fails. Note: An input date string that uses the format *USA. *EUR: The European date format (dd. ’. *DMY: The date format (dd/mm/yy) is used. For input date strings. ’/’: A slash (/) is used. *YMD.mm. *MDY. *JIS: The Japanese Industrial Standard date format (yyyy-mm-dd) is used. *JOB: The format specified for the job is used. Appendix D. 10: The default severity level is 10. severity-level: Specify a value ranging from 0 through 40.yyyy) is used. or *JUL is specified on the DATFMT parameter. All output date fields are returned in the specified format. *ISO. *EUR. *JUL: The Julian date format (yy/ddd) is used. *ISO: The International Organization for Standardization (ISO) date format (yyyy-mm-dd) is used. *JOB: The date separator specified for the job at precompile time is used. Note: This parameter applies only when *JOB. Use the Display Job (DSPJOB) command to determine the current value for the job. *ISO. *DMY.) is used. DATSEP Specifies the separator used when accessing date result columns. If a relational database is specified on the RDB parameter and the database is on a system that is not an AS/400 system. *USA: The United States date format (mm/dd/yyyy) is used. or *JIS must be specified.’: A period (. the specified value is used to determine whether the date is specified in a valid format. then *USA. the operation ends. Use the Display Job (DSPJOB) command to determine the current date format for the job. *EUR. DB2 UDB for AS/400 CL Command Descriptions 671 .CRTSQLCBLI Note: If you specify *YES. *MDY: The date format (mm/dd/yy) is used. *YMD: The date format (yy/mm/dd) is used. If errors occur that have a severity level greater than this value. 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. DATFMT Specifies the format used when accessing date result columns. or *JIS is always valid. *JOB: The time separator specified for the job at precompile time is used.CRTSQLCBLI ’. ’:’: A colon (:) is used.’: A comma (. where xx is AM or PM. For input time strings. *JIS: The Japanese Industrial Standard time format hh:mm:ss is used. the time format must be *USA. *BLANK: A blank ( ) is used.mm. *EUR: The European time format hh. service program or package is created when there is an existing SQL module. the specified value is used to determine whether the time is specified in a valid format.) is used. *HMS: The hh:mm:ss format is used. *ISO. TIMSEP Specifies the separator used when accessing time result columns. REPLACE Specifies if a SQL module. or *HMS with a time separator of a colon or period. *JIS. Note: This parameter applies only when *HMS is specified on the TIMFMT parameter. TIMFMT Specifies the format used when accessing time result columns. service program.mm. ’. *ISO. Note: An input date string that uses the format *USA.ss is used. program. *EUR. If a relational database is specified on the RDB parameter and the database is on a system that is not another AS/400 system. Use the Display Job (DSPJOB) command to determine the current value for the job.ss is used. *USA: The United States time format hh:mm xx is used.) is used. ’. *BLANK: A blank ( ) is used. ’-’: A dash (-) is used. program.’: A comma (. ’ ’: A blank ( ) is used. or *JIS is always valid. *EUR.’: A period (.) is used. or package 672 DB2 UDB for AS/400 SQL Programming V4R4 . *ISO: The International Organization for Standardization (ISO) time format hh. ’ ’: A blank ( ) is used. or package is created. DB2 UDB for AS/400 CL Command Descriptions 673 . The value of this parameter is passed to the CRTCBLMOD. *NONE: No password is sent. *NONE: An SQL package object is not created. This parameter is valid only when RDB is specified. *YES: A new SQL module. PASSWORD Specifies the password to be used on the remote system. user-name: Specify the user name being used for the application server job. service program. password: Specify the password of the user name specified on the USER parameter. *NO: A new SQL module. any existing SQL object of the same name and type in the specified library is moved to QRPLOBJ. RDB Specifies the name of the relational database where the SQL package object is created. service program. Refer to the SQL Reference book for more information. When the name of the local relational database is specified. or package is not created if an SQL object of the same name and type already exists in the specified library. An SQL package object is not created as part of the precompile process. *DUW: CONNECT (Type 2) semantics are used to support distributed unit of work.CRTSQLCBLI of the same name and type in the same library. USER(*CURRENT) must also be specified. The Create Structured Query Language Package (CRTSQLPKG) command can be used. Appendix D. relational-database-name: Specify the name of the relational database where the new SQL package object is to be created. *CURRENT: The user profile under which the current job is running is used. *LOCAL: The program is created as a distributed SQL program. program. CRTSRVPGM. RDBCNNMTH Specifies the semantics used for CONNECT statements. This parameter is valid only if RDB is specified. The SQL statements will access the local database. If this value is specified. USER Specifies the user name sent to the remote system when starting the conversation. the program created is still a distributed SQL program. program. The SQL statements will access the local database. The program object is not a distributed program and the Create Structured Query Language Package (CRTSQLPKG) command cannot be used. and CRTSQLPKG commands. CRTBNDCBL. Consecutive CONNECT statements to additional relational databases do not result in disconnection of previous connections. The naming convention specified on the OPTION parameter is used. *LIBL: The path used is the library list at runtime. and SQL packages in dynamic SQL statements. *NO: Do not use the value specified on the DFTRDBCOL parameter for unqualified names of tables. package-name: Specify the name of the SQL package. where ″userid″ is the value of the USER special register. *YES: The collection name specified on the DFTRDBCOL parameter will be used for the unqualified names of the tables. DFTRDBCOL Specifies the collection name used for the unqualified names of tables. no more than 8 characters can be specified. indexes. For *SYS naming. views. If the remote system is not an AS/400 system. | | | | | | | | | | SQLPATH Specifies the path to be used to find procedures. If a collection-name is specified on the DFTRDBCOL parameter. and user defined types in static SQL statements. the current library list at runtime. | | | | | | | | | | DYNDFTCOL Specifies whether the default collection name specified for the DFTRDBCOL parameter is also used for dynamic statements. For *SQL naming. views. 674 DB2 UDB for AS/400 SQL Programming V4R4 . indexes. collection-name: Specify the name of the collection identifier. This parameter applies only to static SQL statements. *NONE: The naming convention defined on the OPTION parameter is used. functions. 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.CRTSQLCBLI *RUW: CONNECT (Type 1) semantics are used to support remote unit of work. library-name: Specify the name of the library where the package is created. the collection-name takes the place of userid. *NAMING: The path used depends on the naming convention specified on the OPTION parameter. Consecutive CONNECT statements result in the previous connection being disconnected before a new connection is established. ″QSYS2″. This value is used instead of the naming convention specified on the OPTION parameter. ″userid″. views. and SQL packages. and SQL packages for dynamic SQL statements. the path used is *LIBL. 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. indexes. the path used is ″QSYS″. A maximum of 43 individual collections may be specified. FLAGSTD Specifies the American National Standards Institute (ANSI) flagging function. ANSI X3. USRPRF(*USER) is used. *NONE: The source view is not generated. DB2 UDB for AS/400 CL Command Descriptions 675 . *OWNER: The user profiles of both the program owner and the program user are used when the program is run. DBGVIEW Specifies the type of source debug information to be provided by the SQL precompiler. SC26-3255-00. If the naming convention is *SQL. *SOURCE: The SQL precompiler provides the source views for the root and if necessary. 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. *USER: The profile of the user running the program object is used. Appendix D. USRPRF Specifies the user profile that is used when the compiled program object is run. *ANS: The precompiler checks to see whether SQL statements conform to ANSI standards. USRPRF(*OWNER) is used. This parameter flags SQL statements to verify whether they conform to the following standards. DYNUSRPRF Specifies the user profile to be used for dynamic SQL statements.CRTSQLCBLI | | collection-name: Specify a list of one or more collection names. *NAMING: The user profile is determined by the naming convention. SAAFLAG Specifies the IBM SQL flagging function. If the naming convention is *SYS.135-1992 entry ISO 9075-1992 entry FIPS 127. *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.2 entry *NONE: The precompiler does not check to see whether SQL statements conform to ANSI standards. A view is provided which contains the statements generated by the precompiler. including the authority that the program object has for each object in static SQL statements. SQL INCLUDE 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. the QGPL library is used. *LANGIDSHR: The sort sequence table uses the same weight for multiple characters. *JOB: The LANGID value for the job is retrieved during the precompile. *CURLIB: The current library for the job is searched. *JOBRUN: The LANGID value for the job is retrieved when the program is run. The name of the table name can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. *HEX: A sort sequence is not used. table-name: Specify the name of the sort sequence table to be used. 676 DB2 UDB for AS/400 SQL Programming V4R4 . If no library is specified as the current library for the job. and is the shared-weight sort sequence table associated with the language specified on the LANGID parameter. For distributed applications. dynamic SQL statements run under the profile of the program’s user. SRTSEQ(*JOBRUN) is valid only when LANGID(*JOBRUN) is also specified. library-name: Specify the name of the library to be searched. language-identifier: Specify a language identifier. dynamic SQL statements run under the profile of the program’s owner. For distributed programs. dynamic SQL statements run under the profile of the SQL package’s owner. *JOB: The SRTSEQ value for the job is retrieved during the precompile. For distributed applications. *LANGIDUNQ: The unique-weight sort table for the language specified on the LANGID parameter is used. 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. LANGID Specifies the language identifier to be used when SRTSEQ(*LANGIDUNQ) or SRTSEQ(*LANGIDSHR) is specified. SRTSEQ Specifies the sort sequence table to be used for string comparisons in SQL statements. OUTPUT Specifies whether the precompiler listing is generated. LANGID(*JOBRUN) is valid only when SRTSEQ(*JOBRUN) is also specified. For distributed programs. dynamic SQL statements run under the profile of the SQL package’s user. The hexadecimal values of the characters are used to determine the sort sequence.CRTSQLCBLI *USER: For local programs. *JOBRUN: The SRTSEQ value for the job is retrieved when the program is run. *OWNER: For local programs. or by using either the Add Physical File Member (ADDPFM) or Change Physical File Member (CHGPFM) command. The file must have a minimum length of 132 bytes. *PRINT: The precompiler listing is generated. the text is blank. information is lost. If a file with a record length of less than 132 bytes is specified. If no library is specified as the current library for the job. If the specified source file is not found. QSYSPRT: If a file name is not specified.CRTSQLCBLI *NONE: The precompiler listing is not generated. | | | | | | | | | | | | | | | | | 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. The name of the printer file can be qualified by one of the following library values: *LIBL All libraries in the job’s library list are searched until the first match is found. More information on this parameter is in Appendix A. the precompiler printout is directed to the IBM-supplied printer file QSYSPRT. TEXT Specifies the text that briefly describes the printer file. ″Expanded Parameter Descriptions″ in the CL Reference (Abridged) book. QSQLTEMP: The source file QSQLTEMP will be used. the QGPL library will be used. *CURLIB The current library for the job is searched. Text can be added or changed for a database source member by using the Start Source Entry Utility (STRSEU) command. DB2 UDB for AS/400 CL Command Descriptions 677 . The output member will have the same name as the name that is specified for the SRCMBR parameter. *SRCMBRTXT: The text is taken from the source file member being used to create the COBOL program. printer-file-name: Specify the name of the printer device file to which the precompiler printout is directed. The possible library values are: QTEMP: The library QTEMP will be used. the QGPL library is used. Appendix D. If the source file is an inline file or a device file. library-name: Specify the name of the library to be searched. source-file-name: Specify the name of the source file to contain the output source member. it will be created. *CURLIB: The current library for the job will be used. library-name: Specify the name of the library that is to contain the output source file. PRTFILE Specifies the qualified name of the printer device file to which the precompiler printout is directed. If no library is specified as the current library for the job. If the file is not found in any library in the library list. *LIBL: The job’s library list is searched for the specified file. the file will be created in the current library. enclosed in apostrophes. The ILE COBOL compiler is called to create module PAYROLL in the current library by using the source member created by the SQL precompiler.I *CURLIB/ Exec object-name ) CRTSQLCI *LIBL/ SRCFILE( *CURLIB/ library-name/ QCSRC source-file-name ) (1) *OBJ source-file-member-name SRCMBR( ) OPTION( OPTION Details ) TGTRLS( *CURRENT *PRV VxRxMx ) OBJTYPE( *MODULE *PGM *SRVPGM ) *LIBL/ INCFILE( *CURLIB/ library-name/ *SRCFILE source-file-name ) 678 DB2 UDB for AS/400 SQL Programming V4R4 .I Pgm: B. CRTSQLCI (Create Structured Query Language ILE C Object) Command Job: B.I OBJ( library-name/ REXX: B.CRTSQLCBLI *BLANK: Text is not specified. ’description’: Specify no more than 50 characters of text. Example CRTSQLCBLI 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. CRTSQLCI *UR *CHG *ALL *RS *CS *NONE *NC *RR *ENDACTGRP *ENDMOD CLOSQLCSR( ) ) COMMIT( ALWCPYDTA( *OPTIMIZE *YES *NO ) ALWBLK( *ALLREAD *NONE *READ ) DLYPRP( *NO *YES ) GENLVL( 10 severity-level ) MARGINS( *SRCFILE left-right ) DATFMT( *JOB *USA *ISO *EUR *JIS *MDY *DMY *YMD *JUL ) DATSEP( *JOB '/' '. DB2 UDB for AS/400 CL Command Descriptions 679 .' '.' '-' ' ' *BLANK ) TIMFMT( *HMS *USA *ISO *EUR *JIS ) TIMSEP( *JOB ':' '.' ' ' *BLANK ) REPLACE( *YES *NO ) RDB( *LOCAL relational-database-name *NONE ) USER( *CURRENT user-name ) Appendix D.' '. CRTSQLCI *NONE password *DUW *RUW PASSWORD( ) RDBCNNMTH( ) DFTRDBCOL( *NONE collection-name ) DYNDFTCOL( *NO *YES ) SQLPKG( *OBJ package-name ) SQLPATH( *NAMING *LIBL ) collection-name SAAFLAG( *NOFLAG *FLAG ) FLAGSTD( *NONE *ANS ) DBGVIEW( *NONE *SOURCE ) USRPRF( *NAMING *OWNER *USER ) DYNUSRPRF( *USER *OWNER ) SRTSEQ( *JOB *JOBRUN *LANGIDUNQ *LANGIDSHR *HEX *LIBL/ table-name *CURLIB/ library-name/ ) LANGID( *JOB *JOBRUN language-identifier ) OUTPUT( *NONE *PRINT ) 680 DB2 UDB for AS/400 SQL Programming V4R4 . CRTSQLCI *LIBL/ PRTFILE( *CURLIB/ library-name/ QSYSPRT printer-file-name ) QTEMP/ TOSRCFILE( *LIBL/ *CURLIB/ library-name/ QSQLTEMP source-file-name ) TEXT( *SRCMBRTXT *BLANK 'description' ) OPTION Details: *XREF *NOXREF *GEN *NOGEN *PERIOD *JOB *SYSVAL *COMMA *SYS *SQL *NOSECLVL *SECLVL *NOCNULRQD *CNULRQD *NOEVENTF *EVENTF *OPTLOB *NOOPTLOB Notes: 1. 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. and then optionally calls the ILE C compiler to create a module. Parameters OBJ Specifies the qualified name of the object being created. the QGPL library is used. or create a service program. Appendix D. produces a temporary source member. DB2 UDB for AS/400 CL Command Descriptions 681 . If no library is specified as the current library for the job. library-name: Specify the name of the library where the object is created. All parameters preceding this point can be specified in positional form. create a program. 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. *CURLIB: The current library for the job is searched. *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-name: Specify the name of the source file that contains the C source. OPTION Specifies whether one or more of the following options are used when the C source is precompiled. *NOGEN: The precompiler does not call the C compiler. library-name: Specify the name of the library to be searched. source-file-member-name: Specify the name of the member that contains the C source. If this parameter is not specified. service program. SRCFILE Specifies the qualified name of the source file that contains the C source with SQL statements. the OBJ name specified on the OBJ parameter is used. 682 DB2 UDB for AS/400 SQL Programming V4R4 . or if two options conflict. the last option specified is used. the IBM-supplied source file QCSRC contains the C source. program. Element 3: Decimal Point Options *PERIOD: The value used as the decimal point for numeric constants in SQL statements is a period. and a module. Element 2: Program Creation Options *GEN: The precompiler creates the object that is specified by the OBJTYPE parameter. SRCMBR Specifies the name of the source file member that contains the C source. If an option is specified more than once. *NOXREF: The precompiler does not cross-reference names.CRTSQLCI object-name: Specify the name of the object that is being created. This parameter is only specified if the source file name in the SRCFILE parameter is a database file. 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. or SQL package is not created. QCSRC: If the source file name is not specified. The name of the source file can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. the QGPL library is used. If no library is specified as the current library for the job. Element 6: NUL Required Options *NOCNULRQD: For output character and graphic host variables. *SYSVAL: The value used as the decimal point for numeric constants in SQL statements is the QDECFMT system value. CODE/400 uses this file to Appendix D.1. *SECLVL: Second-level text with replacement data is added for all messages on the listing.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. *COMMA: The value used as the decimal point for numeric constants in SQL statements is a comma.23.table-name).1) in which the decimal point is a period. Element 7: Event File Creation *NOEVENTF: The compiler will not produce an event file for use by CoOperative Development Environment/400 (CODE/400). VALUES(1.1.23. 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. the data is truncated and the NUL-terminator is added. If there is not enough space for the NUL-terminator. Element 5: Second-Level Message Text Option *NOSECLVL: Second-level text descriptions are not added to the listing.1) is equivalent to VALUES(1. For example. 2.2. 4. Input character and graphic host variables require a NUL-terminator.1) is equivalent to VALUES(1. When creating a package on a remote database other than an AS/400 system. *SQL: The SQL naming convention is used (collection-name. *EVENTF: The compiler produces an event file for use by CoOperative Development Environment/400 (CODE/400).23.4. *CNULRQD: Output character and graphic host variables always contain the NUL-terminator. DB2 UDB for AS/400 CL Command Descriptions 683 . 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.1. Note: If QDECFMT specifies that the value used as the decimal point is a comma. Element 4: Naming Convention Options *SYS: The system naming convention (library-name/file-name) is used. VALUES(1. the NUL-terminator is not returned when the host variable is exactly the same length as the data.4. *SQL must be specified as the naming convention. The event file will be created as a member in the file EVFEVENT in your source library. For example.1.1) where the decimal point is a period.2.23. Input character and graphic host variables do not require a NUL-terminator. 2. 4. The user can also use the object on a system with any subsequent release of the operating system installed. This option remains in effect until the cursor is closed. specify TGTRLS(V2R3M0) not TGTRLS(*CURRENT). modification level 0. If you specify a release-level which is earlier than the earliest release level supported by this command. and modification level. and Mx is the modification level. *CURRENT: The object is to be used on the release of the operating system currently running on the user’s system. In the examples given for the *CURRENT and *PRV values. *PRV: The object is to be used on the previous release with modification level 0 of the operating system. | | | | Element 8: Large Object Optimization for DRDA *OPTLOB: The first FETCH for a cursor derermines how the cursor will be used for LOBs (Large Objects) on all subsequent FETCHes. *MODULE: The SQL precompiler issues the CRTCMOD command to create the module. release 3. If the first FETCH uses a LOB locator to access a LOB column. OBJTYPE Specifies the type of object being created. an error message is sent indicating the earliest supported release. For example. For example. Rx is the release. and the object is to be used on a system with V2R3M0 installed. release. *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. V2R3M0 is version 2. TGTRLS Specifies the release of the operating system on which the user intends to use the object being created. 684 DB2 UDB for AS/400 SQL Programming V4R4 . no subsequent FETCH for that cursor can use a LOB locator for that column. release-level: Specify the release in the format VxRxMx. For example. Valid values depend on the current version.CRTSQLCI offer error feedback integrated with the CODE/400 editor. The object can be used on a system with the specified release or with any subsequent release of the operating system installed. | | | *NOOPTLOB: There is no restriction on whether a column is retrieved into a LOB locator or into a LOB host variable. This option is normally specified by CODE/400 on your behalf. *PRV means the user intends to use the object on a system with V2R2M0 installed. the format VxRxMx is used to specify the release. This option can cause performance to degrade. and when specifying the release-level value. no subsequent FETCH for that cursor can fetch that LOB column into a LOB host variable. Note: If V2R3M5 is running on the system. if V2R3M5 is running on the system. and they change with each new release. If the first FETCH places the LOB column into a LOB host variable. if V2R3M5 is running on the user’s system. where Vx is the version. DB2 UDB for AS/400 CL Command Descriptions 685 . LABEL ON. library-name: Specify the name of the library to be searched. 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.CRTSQLCI *PGM: The SQL precompiler issues the CRTBNDC command to create the bound program. Uncommitted changes in other jobs can be seen. and Appendix D. CREATE. The name of the source file can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. CALL. If no library is specified as the current library for the job. SQL views. Files referred to in the host language source are not affected by this option. The source member must contain the export information for the module. source-file-name: Specify the name of the source file that contains the source file members specified on any SQL INCLUDE statement. RENAME. When OBJTYPE(*PGM) or OBJTYPE(*SRVPGM) is specified and the RDB parameter is also specified. *ALL or *RS: Specifies the objects referred to in SQL ALTER. CALL. DROP. the CRTSQLPKG command is issued by the SQL precompiler after the program has been created. When OBJTYPE(*MODULE) is specified. COMMENT ON. 2. and inserted are locked until the end of the unit of work (transaction). The user must create a source member in QSRVSRC that has the same name as the name specified on the OBJ parameter. and REVOKE statements and the rows updated. LABEL ON. service program. deleted. the QGPL library is used. *CURLIB: The current library for the job is searched. COMMENT ON. RENAME. GRANT. COMMIT Specifies whether SQL statements in the compiled unit are run under commitment control. or SQL package is not created. More information on the export file is in the Integrated Language Environment*C/400 Programmers Guide. If *NOGEN is specified. DROP. an SQL package is not created and the user must issue the CRTSQLPKG command after the CRTPGM or CRTSRVPGM command has created the program. only the SQL temporary source member is generated and a module. INCFILE Specifies the qualified name of the source file that contains members included in the program with any SQL INCLUDE statement. Only SQL tables. *CHG or *UR: Specifies the objects referred to in SQL ALTER. *SRCFILE: The qualified source file specified in the SRCFILE parameter contains the source file members specified on any SQL INCLUDE statement. CREATE. GRANT. *SRVPGM: The SQL precompiler issues the CRTCMOD and CRTSRVPGM commands to create the service program. and SQL packages referred to in SQL statements are affected. Notes: 1. program. or if COMMIT is *ALL or *RR. GRANT. and INSERT statements are locked exclusively until the end of the unit of work (transaction). deleted. an error message is returned. *OPTIMIZE: The system determines whether to use the data retrieved directly from the database or to use a copy of the data. and inserted are locked until the end of the unit of work (transaction). updated. or ROLLBACK (without HOLD) SQL statements. Uncommitted changes in other jobs cannot be seen. SQL prepared statements are implicitly discarded. is locked until the next row is selected. SQL prepared statements are implicitly discarded. *YES: A copy of the data is used only when necessary. COMMIT. but not updated. | | | | | | | | | | | | | | | ALWCPYDTA Specifies whether a copy of the data can be used in a SELECT statement.CRTSQLCI REVOKE statements and the rows selected. ALWBLK Specifies whether the database manager can use record blocking. A row that is selected. LOCK TABLE locks are released when the first SQL program on the call stack ends. DROP. SQL cursors are explicitly closed when you issue the CLOSE. and inserted are locked until the end of the unit of work (transaction). CLOSQLCSR Specifies when SQL cursors are implicitly closed. Uncommitted changes in other jobs can be seen. CALL. All cursors in a program that are not 686 DB2 UDB for AS/400 SQL Programming V4R4 . then a copy of the data is used only when it is necessary to run a query. CREATE. *ENDMOD: SQL cursors are closed and SQL prepared statements are implicitly discarded when the module is exited. If COMMIT is *CHG or *CS and ALWBLK is not *ALLREAD. RENAME. The decision is based on which method provides the best performance. deleted. 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 must be used. *RR: Specifies the objects referred to in SQL ALTER. CREATE. and REVOKE statements and the rows selected. updated. If a temporary copy of the data is required to perform the query. GRANT. *CS: Specifies the objects referred to in SQL ALTER. deleted. *ALLREAD: Rows are blocked for read-only cursors if *NONE or *CHG is specified on the COMMIT parameter. and the extent to which blocking can be used for read-only cursors. All tables referred to in SELECT. *NONE or *NC: Specifies that commitment control is not used. and LOCK TABLE locks are released when the activation group ends. COMMENT ON. COMMENT ON. LABEL ON. DROP. DELETE. RENAME. LABEL ON. *ENDACTGRP: SQL cursors are closed. Uncommitted changes in other jobs cannot be seen. Uncommitted changes in other jobs cannot be seen. and REVOKE statements and the rows updated. UPDATE. and inserted are locked until the end of the unit of work (transaction). and LOCK TABLE locks are released. If the SQL DROP COLLECTION statement is included in the program. *NONE or *NC cannot be specified. *NO: A copy of the data is not allowed. CALL. *YES: Dynamic statement validation is delayed until the dynamic statement is used in an OPEN. Because the authority or the existence of objects referred to by the dynamic statement may change. v Can improve the performance of almost all read-only cursors in programs. Specifying *READ can improve the overall performance of queries that meet the above conditions and retrieve a large number of records. EXECUTE. the access plan is validated. Specifying *NONE: v Guarantees that the data retrieved is current.CRTSQLCI | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | explicitly able to be updated are opened for read-only processing even though EXECUTE or EXECUTE IMMEDIATE statements may be in the program. When the dynamic statement is used. 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. the access plan is revalidated. *READ: Records are blocked for read-only retrieval of data for cursors when: v *NONE is specified on the COMMIT parameter. v Can degrade the overall performance of a query that retrieves a large number of rows. or DESCRIBE statement is run. *NO: Dynamic statement validation is not delayed. but limits queries in the following ways: – The Rollback (ROLLBACK) command. Specifying *ALLREAD: v Allows record blocking under commitment control level *CHG in addition to the blocking allowed for *READ. the validation is completed and an access plan is Appendix D. 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. cannot be used to update a row in a cursor unless the DECLARE statement for the cursor includes the FOR UPDATE clause. you must still check the SQLCODE or SQLSTATE after issuing the OPEN or EXECUTE statement to ensure that the dynamic statement is still valid. 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. Delaying validation improves performance by eliminating redundant validation. *NONE: Rows are not blocked for retrieval of data for cursors. When the dynamic statement is used in an OPEN or EXECUTE statement. When the dynamic statement is prepared. DB2 UDB for AS/400 CL Command Descriptions 687 . v May reduce the amount of time required to retrieve the first row of data for a query. or DESCRIBE SQL statement. EXECUTE. DLYPRP Specifies whether the dynamic statement validation for a PREPARE statement is delayed until an OPEN. which indicates that commitment control is not used. using EXECUTE IMMEDIATE). a ROLLBACK statement in host languages. Element 1: Left Margin left: Specify the beginning position for the statements. If a relational database is specified on the RDB parameter and the database is on a system that is not an AS/400 system. *JOB: The format specified for the job is used. the operation ends. Element 2: Right Margin right: Specify the ending position for the statements. 10: The default severity level is 10. 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. 688 DB2 UDB for AS/400 SQL Programming V4R4 . you should check the SQLCODE and SQLSTATE after running an OPEN. then *USA. or *JIS is always valid. Valid values range from 1 through 80. Use the Display Job (DSPJOB) command to determine the current date format for the job. *ISO: The International Organization for Standardization (ISO) date format (yyyy-mm-dd) is used. the specified value is used to determine whether the date is specified in a valid format. EXECUTE. *JIS: The Japanese Industrial Standard date format (yyyy-mm-dd) is used. GENLVL Specifies the severity level at which the create operation fails. *USA: The United States date format (mm/dd/yyyy) is used. The margin values default to 1 and 80. | | *SRCFILE: The precompiler uses file member margin values that are specified by the user on the SRCMBR parameter. All output date fields are returned in the specified format. or *JIS must be specified. *MDY: The date format (mm/dd/yy) is used. For input date strings. DATFMT Specifies the format used when accessing date result columns. MARGINS Specifies the part of the precompiler input record that contains source text.CRTSQLCI built. severity-level: Specify a value ranging from 0 through 40. Note: If you specify *YES. If errors occur that have a severity level greater than this value. *EUR. If you specify *YES on this parameter.mm. *ISO. or DESCRIBE statement to ensure that the dynamic statement is valid. *EUR: The European date format (dd. Valid values range from 1 through 80. Note: An input date string that uses the format *USA.yyyy) is used. *ISO. *EUR. *JIS. Note: An input time string that uses the format *USA. ’ ’: A blank ( ) is used. If a relational database is specified on the RDB parameter and the database is on a system that is not another AS/400 system. *JIS: The Japanese Industrial Standard time format hh:mm:ss is used.’: A comma (. or *HMS with a time separator of colon or period. *BLANK: A blank ( ) is used. DB2 UDB for AS/400 CL Command Descriptions 689 .’: A period (.) is used. *USA: The United States time format hh:mm xx is used. *JOB:The date separator specified for the job at precompile time is used. *EUR. ’/’: A slash (/) is used. *HMS: The hh:mm:ss format is used. where xx is AM or PM. ’. *DMY. or *JUL is specified on the DATFMT parameter. TIMFMT Specifies the format used when accessing time result columns. the time format must be *USA. ’-’: A dash (-) is used.CRTSQLCI *DMY: The date format (dd/mm/yy) is used. *JUL: The Julian date format (yy/ddd) is used. or *JIS is always valid.mm. ’.ss is used. *YMD: The date format (yy/mm/dd) is used. For input time strings. *ISO. DATSEP Specifies the separator used when accessing date result columns. *EUR: The European time format hh. the specified value is used to determine whether the time is specified in a valid format. Appendix D. *ISO. *EUR. Note: This parameter applies only when *JOB. *MDY. *ISO: The International Organization for Standardization (ISO) time format hh. *YMD. Note: This parameter applies only when *HMS is specified on the TIMFMT parameter. Use the Display Job (DSPJOB) command to determine the current value for the job.) is used.ss is used.mm. TIMSEP Specifies the separator used when accessing time result columns. program. service program. *BLANK: A blank ( ) is used. service program.CRTSQLCI *JOB: The time separator specified for the job at precompile time is used. *LOCAL: The program is created as a distributed SQL program. CRTBNDC.) is used. This parameter is valid only when RDB is specified. The program object is not a distributed program and the Create Structured Query Language Package (CRTSQLPKG) command cannot be used. PASSWORD Specifies the password to be used on the remote system. The SQL statements will access the local database. ’. CRTSRVPGM. or package is not created if an object of the same name and type already exists in the specified library. The Create Structured Query Language Package (CRTSQLPKG) command can be used. service program. *YES: A new SQL module. relational-database-name: Specify the name of the relational database where the new SQL package object is to be created. ’ ’: A blank ( ) is used. service program or package is created when there is an existing SQL module. REPLACE Specifies if a SQL module. user-name: Specify the user name being used for the application server job. the program created is still a distributed SQL program. Use the Display Job (DSPJOB) command to determine the current value for the job. RDB Specifies the name of the relational database where the SQL package object is created. *CURRENT: The user profile under which the current job is running is used. program. program.) is used. *NO: A new SQL module. When the name of the local relational database is specified. *NONE: An SQL package object is not created. The value of this parameter is passed to the CRTCMOD. or package is created.’: A comma (. and any existing object of the same name and type in the specified library is moved to QRPLOBJ. An SQL package object is not created as part of the precompile process. program. or package of the same name and type in the same library.’: A period (. The SQL statements will access the local database. ’:’: A colon (:) is used. USER Specifies the user name sent to the remote system when starting the conversation. and CRTSQLPKG commands. This parameter is valid only if RDB is specified. ’. 690 DB2 UDB for AS/400 SQL Programming V4R4 . The naming convention specified on the OPTION parameter is used. | | | | | | | | | | DYNDFTCOL Specifies whether the default collection name specified for the DFTRDBCOL parameter is also used for dynamic statements. *OBJ: The name of the SQL package is the same as the object name specified on the OBJ parameter. SC41-3612 book for more information. RDBCNNMTH Specifies the semantics used for CONNECT statements. collection-name: Specify the name of the collection identifier. If the remote system is not an AS/400 system. DFTRDBCOL Specifies the collection name used for the unqualified names of tables. views. *NONE: The naming convention defined on the OPTION parameter is used. indexes. This value is used instead of the naming convention specified on the OPTION parameter. Consecutive CONNECT statements to additional relational databases do not result in disconnection of previous connections. If this value is specified. and SQL packages for dynamic SQL statements. USER(*CURRENT) must also be specified.CRTSQLCI *NONE: No password is sent. and SQL packages. DB2 UDB for AS/400 CL Command Descriptions 691 . library-name: Specify the name of the library where the package is created. and SQL packages in dynamic SQL statements. no more than 8 characters can be specified. password: Specify the password of the user name specified on the USER parameter. 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. *RUW: CONNECT (Type 1) semantics are used to support remote unit of work. views. indexes. Consecutive CONNECT statements result in the previous connection being disconnected before a new connection is established. *NO: Do not use the value specified on the DFTRDBCOL parameter for unqualified names of tables. indexes. package-name: Specify the name of the SQL package. SQLPKG Specifies the qualified name of the SQL package created on the relational database specified on the RDB parameter of this command. *DUW: CONNECT (Type 2) semantics are used to support distributed unit of work. Refer to the SQL Reference. *YES: The collection name specified on the DFTRDBCOL parameter will be used for the unqualified names of the tables. Appendix D. views. This parameter applies only to static SQL statements. 135-1992 entry ISO 9075-1992 entry FIPS 127. SQL INCLUDE statements. ″QSYS2″. *FLAG: The precompiler checks to see whether SQL statements conform to IBM SQL syntax FLAGSTD Specifies the American National Standards Institute (ANSI) flagging function. the current library list at runtime. *NOFLAG: The precompiler does not check to see whether SQL statements conform to IBM SQL syntax. *LIBL: The path used is the library list at runtime. *NAMING: The path used depends on the naming convention specified on the OPTION parameter. SC26-3255-00. ANSI X3. *ANS: The precompiler checks to see whether SQL statements conform to ANSI standards. collection-name: Specify a list of one or more collection names. *NONE: The source view will not be generated. If a collection-name is specified on the DFTRDBCOL parameter. USRPRF Specifies the user profile that is used when the compiled program object is run. where ″userid″ is the value of the USER special register. ″userid″. the collection-name takes the place of userid. A view is provided that contains the statements generated by the precompiler. the path used is *LIBL. *SOURCE: The SQL precompiler provides the source views for the root and if necessary. DBGVIEW This parameter specifies the type of source debug information to be provided by the SQL precompiler. For *SQL naming. including the authority that the program object has for each object in static SQL 692 DB2 UDB for AS/400 SQL Programming V4R4 . For *SYS naming. functions. and user defined types in static SQL statements. the path used is ″QSYS″. SAAFLAG Specifies the IBM SQL flagging function. A maximum of 43 individual collections may be specified.2 entry *NONE: The precompiler does not check to see whether SQL statements conform to ANSI standards. 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. This parameter flags SQL statements to verify whether they conform to the following standards.CRTSQLCI | | | | | | | | | | | | SQLPATH Specifies the path to be used to find procedures. *JOBRUN: The SRTSEQ value for the job is retrieved when the program is run.CRTSQLCI statements. *LANGIDUNQ: The unique-weight sort table for the language specified on the LANGID parameter is used. USRPRF(*USER) is used. Appendix D. For distributed applications. *JOB: The SRTSEQ value for the job is retrieved during the precompile. The hexadecimal values of the characters are used to determine the sort sequence. The profile of either the program owner or the program user is used to control which objects can be used by the program object. 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. *HEX: A sort sequence table is not used. Distributed dynamic SQL statements are run under the profile of the SQL package’s user. *LANGIDSHR: The sort sequence table uses the same weight for multiple characters. DYNUSRPRF Specifies the user profile to be used for dynamic SQL statements. the QGPL library is used. DB2 UDB for AS/400 CL Command Descriptions 693 . *USER: Local dynamic SQL statements are run under the profile of the program’s user. *OWNER: The user profiles of both the program owner and the program user are used when the program is run. *USER: The profile of the user running the program object is used. table-name: Specify the name of the sort sequence table to be used. *CURLIB: The current library for the job is searched. and is the shared-weight sort sequence table associated with the language specified on the LANGID parameter. If no library is specified as the current library for the job. USRPRF(*OWNER) is used. SRTSEQ Specifies the sort sequence table to be used for string comparisons in SQL statements. *OWNER: Local dynamic SQL statements are run under the profile of the program’s owner. SRTSEQ(*JOBRUN) is valid only when LANGID(*JOBRUN) is also specified. library-name: Specify the name of hte library to be searched. If the naming convention is *SYS. Distributed dynamic SQL statements are run under the profile of the SQL package’s owner. If the naming convention is *SQL. The name of the table name can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. *NAMING: The user profile is determined by the naming convention. printer-file-name: Specify the name of the printer device file to which the precompiler printout is directed. the QGPL library is used. *CURLIB: The current library for the job is searched. *JOB: The LANGID value for the job is retrieved during the precompile. QSQLTEMP: The source file QSQLTEMP will be used. The file must have a minimum length of 132 bytes. language-identifier: Specify a language identifier. If the file is not found in any library in the library list. *JOBRUN: The LANGID value for the job is retrieved when the program is run. it creates the file. If the precompiler cannot find the specified source file. PRTFILE Specifies the qualified name of the printer device file to which the precompiler printout is directed. *CURLIB: The current library for the job will be used. For distributed applications. If no library is specified as the current library for the job. *NONE: The precompiler listing is not generated. the file will be created in the current library.CRTSQLCI LANGID Specifies the language identifier to be used when SRTSEQ(*LANGIDUNQ) or SRTSEQ(*LANGIDSHR) is specified. 694 DB2 UDB for AS/400 SQL Programming V4R4 . 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. the precompiler printout is directed to the IBM-supplied printer file QSYSPRT. OUTPUT Specifies whether the precompiler listing is generated. library-name: Specify the name of the library that is to contain the output source file. *LIBL: The job’s library list is searched for the specified file. *PRINT: The precompiler listing is generated. If a file with a record length of less than 132 bytes is specified. | | | | | | | | | | | | | | | TOSRCFILE Specifies the qualified name of the source file that is to contain the output source member that the SQL precompiler has processed. QSYSPRT: If a file name is not specified. the QGPL library will be used. The name of the printer file can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. If no library is specified as the current library for the job. LANGID(*JOBRUN) is valid only when SRTSEQ(*JOBRUN) is also specified. library-name: Specify the name of the library to be searched. information is lost. I Pgm: B. More information on this parameter is in Appendix A. Text can be added or changed for a database source member by using the Start Source Entry Utility (STRSEU) command.CRTSQLCI | | source-file-name: Specify the name of the source file to contain the output source member. *BLANK: Text is not specified. 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. or by using either the Add Physical File Member (ADDPFM) command or the Change Physical File Member (CHGPFM) command. DB2 UDB for AS/400 CL Command Descriptions 695 . TEXT Specifies the text that briefly describes the program and the function. *SRCMBRTXT: The text is taken from the source file member being used to create the C program. enclosed in apostrophes. If the source file is an inline file or a device file. 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.I *CURLIB/ Exec object-name ) CRTSQLCPPI | | SRCFILE( *LIBL/ *CURLIB/ library-name/ QCSRC source-file-name ) | | SRCMBR( *OBJ source-file-member-name ) (1) | Appendix D.I OBJ( library-name/ REXX: B. CRTSQLCPPI (Create Structured Query Language C++ Object) Command Job: B. ’description’: Specify no more than 50 characters of text. the text is blank. ″Expanded Parameter Descriptions″ in the CL Reference book. ' '-' ' ' *BLANK ) TIMFMT( *HMS *USA *ISO *EUR *JIS ) | 696 DB2 UDB for AS/400 SQL Programming V4R4 .' '.CRTSQLCPPI | | OPTION( OPTION Details ) TGTRLS( *CURRENT VxRxMx ) | | INCFILE( *LIBL/ *CURLIB/ library-name/ *SRCFILE source-file-name ) | | COMMIT( *UR *CHG *ALL *RS *CS *NONE *NC *RR CLOSQLCSR( ) *ENDACTGRP *ENDMOD ) | | ALWCPYDTA( *OPTIMIZE *YES *NO ) ALWBLK( *ALLREAD *NONE *READ ) | | DLYPRP( *NO *YES ) GENLVL( 10 severity-level ) | | MARGINS( *SRCFILE left-right ) DATFMT( *JOB *USA *ISO *EUR *JIS *MDY *DMY *YMD *JUL ) | | DATSEP( *JOB '/' '. CRTSQLCPPI | 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 ) | | DYNDFTCOL( *NO *YES ) | | SQLPKG( *OBJLIB/ library-name/ *OBJ package-name ) | | SQLPATH( *NAMING *LIBL ) collection-name | | SAAFLAG( *NOFLAG *FLAG ) FLAGSTD( *NONE *ANS ) | | DBGVIEW( *NONE *SOURCE ) USRPRF( *NAMING *OWNER *USER ) | Appendix D. DB2 UDB for AS/400 CL Command Descriptions 697 .' '. CRTSQLCPPI | | DYNUSRPRF( *USER *OWNER ) | | SRTSEQ( *JOB *JOBRUN *LANGIDUNQ *LANGIDSHR *HEX *LIBL/ table-name *CURLIB/ library-name/ ) | | LANGID( *JOB *JOBRUN language-identifier ) OUTPUT( *NONE *PRINT ) | | PRTFILE( *LIBL/ *CURLIB/ library-name/ QSYSPRT printer-file-name ) | | | TOSRCFILE( *LIBL/ *CURLIB/ library-name/ QTEMP/ QSQLTEMP source-file-name ) | | TEXT( *SRCMBRTXT *BLANK 'description' ) | | | | OPTION Details: *XREF *NOXREF *GEN *NOGEN *JOB *PERIOD *SYSVAL *COMMA *SYS *SQL *NOSECLVL *SECLVL | | *NOCNULRQD *CNULRQD *NOEVENTF *EVENTF *OPTLOB *NOOPTLOB | 698 DB2 UDB for AS/400 SQL Programming V4R4 . produces a temporary source member. All parameters preceding this point can be specified in positional form. If you do not specify a library as the current library for the job. DB2 UDB for AS/400 CL Command Descriptions 699 . Specify this parameter only if the source file name in the SRCFILE parameter is a database file. the precompiler uses QGPL library. Appendix D. SRCMBR Specifies the name of the source file member that contains the C++ source. object-name: Specify the name of the object that the precompiler creates. Parameters OBJ Specifies the qualified name of the object that the precompiler creates. Purpose The Create Structured Query Language C++ Object (CRTSQLCPPI) command calls the Structured Query Language (SQL) precompiler.CRTSQLCPPI | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Notes: 1. If you do not specify this parameter. To precompile for the VisualAge C++ for OS/400 compiler. source-file-member-name: Specify the name of the member that contains the C++ source. source-file-name: Specify the name of the source file that contains the C++ source. library-name: Specify the name of the library that the precompiler searches. QCSRC: If you do not specify the source file name. If you do not specify a library as the current library for the job. it uses the QGPL library. and then optionally calls the C++ compiler to create a module. *CURLIB: The precompiler searches the current library for the job. SRCFILE Specifies the qualified name of the source file that contains the C++ source with SQL statements. *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. 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. use the CVTSQLCPP command. One of the following library values can qualify the name of the source file: *LIBL: The precompiler searches all libraries in the job’s library list until it finds the first match. library-name: Specify the name of the library where the object is created. the IBM-supplied source file QCSRC contains the C++ source. The SQL precompiler precompiles C++ source containing SQL statements. the precompiler uses the OBJ name that is specified on the OBJ parameter. 1) is equivalent to VALUES(1. *PERIOD:The value used as the decimal point for numeric constants in SQL statements is a period.table-name). 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.4. For example.1. When creating a package on a remote database other than an AS/400 system.1. you must specify *SQL as the naming convention. 700 DB2 UDB for AS/400 SQL Programming V4R4 . For example. Element 4: Naming Convention Options *SYS: The system naming convention (library-name/file-name) is used. *NOXREF: The precompiler does not cross-reference names.2. *SECLVL: Second-level text with replacement data is added for all messages on the listing.23.4.23. 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.CRTSQLCPPI | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | OPTION Specifies whether one or more of the following options are used when the C++ source is precompiled. *COMMA: The value used as the decimal point for numeric constants in SQL statements is a comma. or if two options conflict. VALUES(1.2. 4. If an option is specified more than once.1.23. Element 2: Program Creation Options *GEN: The precompiler creates the module object.1) is equivalent to VALUES(1. and does not create a module.1) in which the decimal point is a period.23.1. VALUES(1. Note: If the job specifies that the value used as the decimal point is a comma. 4. Element 5: Second-Level Message Text Option *NOSECLVL: Second-level text descriptions are not added to the listing. 2.1) where the decimal point is a period. 2. 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. the last option specified is used. *NOGEN: The precompiler does not call the C++ compiler. *SQL: The SQL naming convention is used (collection-name. Element 3: Decimal Point Options *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. CODE/400 uses this file to offer error feedback that is integrated with the CODE/400 editor. Rx is the release. *CURRENT: The object is to be used on the release of the operating system that is currently running on the user’s system.CRTSQLCPPI | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Element 6: NUL Required Options *NOCNULRQD: For output character and graphic host variables. For example. Vx is the version. use the format VxRxMx to specify the release. Input character and graphic host variables require a NUL-terminator. For example. Input character and graphic host variables do not require a NUL-terminator. no subsequent FETCH for that cursor can use a LOB locator for that column. Element 7: Event File Creation *NOEVENTF: The compiler will not produce an event file for use by CoOperative Development Environment/400 (CODE/400). as well as the release-level value. TGTRLS Specifies the release of the operating system on which the user intends to use the object that is being created. and the NUL-terminator is added. It creates the event file as a member in the file EVFEVENT in your source library. *CURRENT means that the user intends to use the object on a system with V2R3M5 installed. CODE/400 normally specifies this option on your behalf. This option remains in effect until the cursor is closed. The user can also use the object on a system with any subsequent release of the operating system installed. release 3. This option can cause performance to degrade. no subsequent FETCH for that cursor can fetch that LOB column into a LOB host variable. V2R3M0 is version 2. the data is truncated. and Mx is the modification level. If the first FETCH places the LOB column into a LOB host variable. The examples given for the *CURRENT value. DB2 UDB for AS/400 CL Command Descriptions 701 . *EVENTF: The compiler produces an event file for use by CoOperative Development Environment/400 (CODE/400). If the first FETCH uses a LOB locator to access a LOB column. Appendix D. Element 8: Large Object Optimization for DRDA *OPTLOB: The first FETCH for a cursor derermines how the cursor will be used for LOBs (Large Objects) on all subsequent FETCHes. if V2R3M5 is running on the system. modification level 0. *NOOPTLOB: There is no restriction on whether a column is retrieved into a LOB locator or into a LOB host variable. *CNULRQD: Output character and graphic host variables always contain the NUL-terminator. In this format. the NUL-terminator is not returned when the host variable is exactly the same length as the data. If there is not enough space for the NUL-terminator. GRANT. The object can be used on a system with the specified release or with any subsequent release of the operating system installed. Uncommitted changes in other jobs cannot be seen. Uncommitted changes in other jobs can be seen. CREATE. INCFILE Specifies the qualified name of the source file that contains members that are included in the program with any SQL INCLUDE statement. A row that is selected. the QGPL library is used. deleted. CALL. source-file-name: Specify the name of the source file that contains the source file members that are specified on any SQL INCLUDE statement. Files referred to in the host language source are not affected by this option. updated. LABEL ON. RENAME. CREATE. COMMENT ON. specify TGTRLS(V2R3M0) not TGTRLS(*CURRENT). If no library is specified as the current library for the job. release. GRANT. Only SQL tables. library-name: Specify the name of the library to be searched. and REVOKE statements and the rows updated. *CS: Specifies the objects referred to in SQL ALTER. COMMENT ON. and they change with each new release. and the object is to be used on a system with V2R3M0 installed. 702 DB2 UDB for AS/400 SQL Programming V4R4 . *ALL or *RS: Specifies the objects referred to in SQL ALTER. One of the following library values can qualify the name of the source file: *LIBL: All libraries in the job’s library list are searched until the first match is found. If you specify a release-level which is earlier than the earliest release level that is supported by this command. *CURLIB: The current library for the job is searched. CALL. RENAME. and REVOKE statements and the rows updated. and modification level. but not updated. LABEL ON. *SRCFILE: The qualified source file specified in the SRCFILE parameter contains the source file members that are specified on any SQL INCLUDE statement. deleted. and inserted are locked until the end of the unit of work (transaction). Uncommitted changes in other jobs cannot be seen. CREATE. COMMIT Specifies whether SQL statements in the compiled unit are run under commitment control. *CHG or *UR: Specifies the objects referred to in SQL ALTER. DROP. GRANT. COMMENT ON. 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. LABEL ON. DROP.CRTSQLCPPI | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Note: If V2R3M5 is running on the system. and inserted are locked until the end of the unit of work (transaction). SQL views. and inserted are locked until the end of the unit of work (transaction). release-level: Specify the release in the format VxRxMx. DROP. RENAME. CALL. deleted. Valid values depend on the current version. and SQL packages referred to in SQL statements are affected. and REVOKE statements and the rows selected. is locked until the next row is selected. an error message is sent indicating the earliest supported release. CLOSQLCSR Specifies when SQL cursors are implicitly closed. Uncommitted changes in other jobs cannot be seen. and INSERT statements are locked exclusively until the end of the unit of work (transaction). and 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. LABEL ON. and SQL prepared statements are implicitly discarded when the module is exited. *ALLREAD: Rows are blocked for read-only cursors if *NONE or *CHG is specified on the COMMIT parameter. and LOCK TABLE locks are released. and REVOKE statements and the rows selected. or if COMMIT is *ALL or *RR. *YES: A copy of the data is used only when necessary.CRTSQLCPPI | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | *NONE or *NC: Specifies that commitment control is not used. 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. SQL prepared statements are implicitly discarded. *ENDMOD: SQL cursors are closed. *NONE or *NC cannot be specified. If COMMIT is *CHG or *CS and ALWBLK is not *ALLREAD. or ROLLBACK (without HOLD) SQL statements. and inserted are locked until the end of the unit of work (transaction). DELETE. SQL cursors are explicitly closed when you issue the CLOSE. COMMIT. COMMENT ON. The decision is based on which method provides the best performance. ALWBLK Specifies whether the database manager can use record blocking. 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. updated. then a copy of the data is used only when it is necessary to run a query. *NONE or *NC must be used. CREATE. GRANT. an error message is returned. *RR: Specifies the objects referred to in SQL ALTER. Uncommitted changes in other jobs can be seen. *ENDACTGRP: SQL cursors are closed. 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. but limits queries in the following ways: Appendix D. DB2 UDB for AS/400 CL Command Descriptions 703 . RENAME. If a temporary copy of the data is required to perform the query. *NO: A copy of the data is not allowed. CALL. SQL prepared statements are implicitly discarded. LOCK TABLE locks are released when the first SQL program on the call stack ends. All tables referred to in SELECT. DROP. *OPTIMIZE: The system determines whether to use the data retrieved directly from the database or to use a copy of the data. If the SQL DROP COLLECTION statement is included in the program. deleted. UPDATE. and the extent to which blocking can be used for read-only cursors. When the dynamic statement is used in an OPEN or EXECUTE statement. Specifying *NONE: v Guarantees that the data retrieved is current. *YES: Dynamic statement validation is delayed until the dynamic statement is used in an OPEN. DLYPRP Specifies whether the dynamic statement validation for a PREPARE statement is delayed until an OPEN. *NONE: Rows are not blocked for retrieval of data for cursors. – Dynamic running of a positioned UPDATE or DELETE statement (for example. a ROLLBACK statement in host languages. v May reduce the amount of time required to retrieve the first row of data for a query. cannot be used to update a row in a cursor unless the DECLARE statement for the cursor includes the FOR UPDATE clause. EXECUTE. Delaying validation improves performance by eliminating redundant validation. When the dynamic statement is 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. 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. or DESCRIBE SQL statement. or DESCRIBE statement to ensure that the dynamic statement is valid.CRTSQLCPPI | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | – The Rollback (ROLLBACK) command. you must still check the SQLCODE or SQLSTATE after issuing the OPEN or EXECUTE statement to ensure that the dynamic statement is still valid. the access plan is revalidated. EXECUTE. *NO: Dynamic statement validation is not delayed. or the ROLLBACK HOLD SQL statement does not reposition a read-only cursor when *ALLREAD is specified. Specifying *READ can improve the overall performance of queries that meet the above conditions and retrieve a large number of records. When the dynamic statement is prepared. If you specify *YES on this parameter. 704 DB2 UDB for AS/400 SQL Programming V4R4 . the validation is completed. and an access plan is built. v Can degrade the overall performance of a query that retrieves a large number of rows. *READ: Records are blocked for read-only retrieval of data for cursors when: v *NONE is specified on the COMMIT parameter. using EXECUTE IMMEDIATE). EXECUTE. you should check the SQLCODE and SQLSTATE after running an OPEN. which indicates that commitment control is not used. Note: If you specify *YES. Because the authority or the existence of objects referred to by the dynamic statement may change. the access plan is validated. 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. or DESCRIBE statement is run. Note: An input date string that uses the format *USA. If errors occur that have a severity level greater than this value. For input date strings. *JIS: The Japanese Industrial Standard date format (yyyy-mm-dd) is used. the operation ends. DB2 UDB for AS/400 CL Command Descriptions 705 . Element 2: Right Margin right: Specify the ending position for the statements. SQLC. *USA: The United States date format (mm/dd/yyyy) is used.mm. the specified value is used to determine whether the date is specified in a valid format. the margin values are the default values of 1 and 80. Element 1: Left Margin left: Specify the beginning position for the statements. MARGINS Specifies the part of the precompiler input record that contains source text. severity-level: Specify a value ranging from 0 through 40. Use the Display Job (DSPJOB) command to determine the current date format for the job. Valid values range from 1 through 80. Appendix D. or *JIS must be specified. the margin values are the values that are specified on the SEU services display.CRTSQLCPPI | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | GENLVL Specifies the severity level at which the create operation fails. If a relational database is specified on the RDB parameter and the database is on a system that is not an AS/400 system. *EUR. *DMY: The date format (dd/mm/yy) is used. If the member is of SQLCLE. 10: The default severity level is 10. *SRCFILE: The file member margin values specified by the user on the SRCMBR parameter are used. or CLE source type. then *USA. *JOB: The format specified for the job is used. *EUR: The European date format (dd. *EUR. All output date fields are returned in the specified format. *MDY: The date format (mm/dd/yy) is used. or *JIS is always valid. *ISO. C. Valid values range from 1 through 80. *YMD: The date format (yy/mm/dd) is used.yyyy) is used. DATFMT Specifies the format used when accessing date result columns. If the member is a different source type. *ISO: The International Organization for Standardization (ISO) date format (yyyy-mm-dd) is used. *ISO. the time format must be *USA. where xx is AM or PM. or *HMS with a time separator of colon or period. *ISO. ’. For input time strings.mm. or *JUL is specified on the DATFMT parameter. or *JIS is always valid. *EUR: The European time format hh. *EUR. *ISO. *MDY. TIMSEP Specifies the separator used when accessing time result columns. ’. *JIS. Note: An input time string that uses the format *USA.ss is used. 706 DB2 UDB for AS/400 SQL Programming V4R4 .’: A comma (. ’-’: A dash (-) is used.mm.) is used. *BLANK: A blank ( ) is used. *HMS: The hh:mm:ss format is used.ss is used. Use the Display Job (DSPJOB) command to determine the current value for the job. If a relational database is specified on the RDB parameter and the database is on a system that is not another AS/400 system. *ISO: The International Organization for Standardization (ISO) time format hh. *JOB: The time separator specified for the job at precompile time is used.’: A period (. Note: This parameter applies only when *JOB. *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. *DMY.CRTSQLCPPI | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | *JUL: The Julian date format (yy/ddd) is used. Note: This parameter applies only when *HMS is specified on the TIMFMT parameter. the specified value is used to determine whether the time is specified in a valid format. ’ ’: A blank ( ) is used. TIMFMT Specifies the format used when accessing time result columns. *EUR. *USA: The United States time format hh:mm xx is used. DATSEP Specifies the separator used when accessing date result columns. ’/’: A slash (/) is used.) is used. *JIS: The Japanese Industrial Standard time format hh:mm:ss is used. *YMD. The value of this parameter is passed to the CRTCPPMOD command. *NO: A new SQL module is not created if an object of the same name already exists in the specified library. ’. USER Specifies the user name sent to the remote system when starting the conversation. relational-database-name: Specify the name of the relational database where the new SQL package object is to be created. RDB Specifies the name of the relational database where the SQL package object is created. ’ ’: A blank ( ) is used. USER(*CURRENT) must also be specified.) is used. *BLANK: A blank ( ) is used.’: A comma (. and any existing object of the same name in the specified library is moved to QRPLOBJ. password: Specify the password of the user name that is specified on the USER parameter. This parameter is valid only when RDB is specified. the program created is still a distributed SQL program.) is used. The program object is not a distributed program and the Create Structured Query Language Package (CRTSQLPKG) command cannot be used. Appendix D. REPLACE Specifies if an SQL module is created when there is an existing SQL module of the same name in the same library. ’. This parameter is valid only if RDB is specified. PASSWORD Specifies the password to be used on the remote system. *YES: A new SQL module is created. *LOCAL: The program is created as a distributed SQL program. *CURRENT: The user profile under which the current job is running is used.’: A period (. user-name: Specify the user name being used for the application server job. The Create Structured Query Language Package (CRTSQLPKG) command can be used. An SQL package object is not created as part of the precompile process. *NONE: No password is sent. DB2 UDB for AS/400 CL Command Descriptions 707 . The SQL statements will access the local database. *NONE: An SQL package object is not created.CRTSQLCPPI | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ’:’: A colon (:) is used. When the name of the local relational database is specified. The SQL statements will access the local database. If this value is specified. Consecutive CONNECT statements result in the previous connection being disconnected before a new connection is established. *OBJ: The name of the SQL package is the same as the object name specified on the OBJ parameter. views. indexes. *YES: The collection name specified on the DFTRDBCOL parameter will be used for the unqualified names of the tables. no more than 8 characters can be specified. 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. 708 DB2 UDB for AS/400 SQL Programming V4R4 . views. SQLPATH Specifies the path to be used to find procedures. *DUW: CONNECT (Type 2) semantics are used to support distributed unit of work. DFTRDBCOL Specifies the collection name used for the unqualified names of tables. Consecutive CONNECT statements to additional relational databases do not result in disconnection of previous connections. Refer to the SQL Reference. views. and SQL packages for dynamic SQL statements. *NONE: The naming convention defined on the OPTION parameter is used. library-name: Specify the name of the library where the package is created. If the remote system is not an AS/400 system. *NO: Do not use the value specified on the DFTRDBCOL parameter for unqualified names of tables. indexes. The naming convention specified on the OPTION parameter is used. and user defined types in static SQL statements. SC41-3612 book for more information. *NAMING: The path used depends on the naming convention specified on the OPTION parameter. *RUW: CONNECT (Type 1) semantics are used to support remote unit of work. package-name: Specify the name of the SQL package. collection-name: Specify the name of the collection identifier. and SQL packages. indexes. SQLPKG Specifies the qualified name of the SQL package created on the relational database specified on the RDB parameter of this command. and SQL packages in dynamic SQL statements. functions. This parameter applies only to static SQL statements.CRTSQLCPPI | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | RDBCNNMTH Specifies the semantics used for CONNECT statements. This value is used instead of the naming convention that is specified on the OPTION parameter. DYNDFTCOL Specifies whether the default collection name specified for the DFTRDBCOL parameter is also used for dynamic statements. ″userid″. A view is provided that contains the statements generated by the precompiler. where ″userid″ is the value of the USER special register. This parameter flags SQL statements to verify whether they conform to the following standards. If the naming convention is *SQL.CRTSQLCPPI | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | For *SYS naming. SQL INCLUDE statements. collection-name: Specify a list of one or more collection names. the collection-name takes the place of userid. *NONE: The source view will not be generated. 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. USRPRF Specifies the user profile that is used when the compiled program object is run. A maximum of 43 individual collections may be specified. Appendix D. *NAMING: The user profile is determined by the naming convention. USRPRF(*USER) is used. DBGVIEW This parameter specifies the type of source debug information to be provided by the SQL precompiler. USRPRF(*OWNER) is used. the path used is ″QSYS″. SAAFLAG Specifies the IBM SQL flagging function. *ANS: The precompiler checks to see whether SQL statements conform to ANSI standards. the current library list at runtime.135-1992 entry ISO 9075-1992 entry FIPS 127. including the authority that the program object has for each object in static SQL statements. For *SQL naming. *FLAG: The precompiler checks to see whether SQL statements conform to IBM SQL syntax. SC26-3255-00. The profile of either the program owner or the program user is used to control which objects can be used by the program object. FLAGSTD Specifies the American National Standards Institute (ANSI) flagging function. ANSI X3. *SOURCE: The SQL precompiler provides the source views for the root and if necessary. the path used is *LIBL. If the naming convention is *SYS. *USER: The profile of the user running the program object is used. *NOFLAG: The precompiler does not check to see whether SQL statements conform to IBM SQL syntax. DB2 UDB for AS/400 CL Command Descriptions 709 . If a collection-name is specified on the DFTRDBCOL parameter. ″QSYS2″.2 entry *NONE: The precompiler does not check to see whether SQL statements conform to ANSI standards. *LIBL: The path used is the library list at runtime. *HEX: A sort sequence table is not used. *JOBRUN: The LANGID value for the job is retrieved when the program is run. *LANGIDSHR: The sort sequence table uses the same weight for multiple characters. *LANGIDUNQ: The unique-weight sort table for the language that is specified on the LANGID parameter is used. DYNUSRPRF Specifies the user profile to be used for dynamic SQL statements. *JOB: The LANGID value for the job is retrieved during the precompile. and is the shared-weight sort sequence table associated with the language specified on the LANGID parameter. 710 DB2 UDB for AS/400 SQL Programming V4R4 . The hexadecimal values of the characters are used to determine the sort sequence. library-name: Specify the name of hte library to be searched. *JOBRUN: The SRTSEQ value for the job is retrieved when the program is run. Distributed dynamic SQL statements are run under the profile of the SQL package’s owner. The name of the table name can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. For distributed applications. the QGPL library is used. *OWNER: Local dynamic SQL statements are run under the profile of the program’s owner. *JOB: The SRTSEQ value for the job is retrieved during the precompile. *CURLIB: The current library for the job is searched. If no library is specified as the current library for the job. SRTSEQ(*JOBRUN) is valid only when LANGID(*JOBRUN) is also specified.CRTSQLCPPI | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | *OWNER: The user profiles of both the program owner and the program user are used when the program is run. LANGID Specifies the language identifier to be used when SRTSEQ(*LANGIDUNQ) or SRTSEQ(*LANGIDSHR) is specified. 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. Distributed dynamic SQL statements are run under the profile of the SQL package’s user. For distributed applications. table-name: Specify the name of the sort sequence table to be used. *USER: Local dynamic SQL statements are run under the profile of the program’s user. SRTSEQ Specifies the sort sequence table to be used for string comparisons in SQL statements. LANGID(*JOBRUN) is valid only when SRTSEQ(*JOBRUN) is also specified. information is lost. *SRCMBRTXT: The text is taken from the source file member being used to create the C++ program. the QGPL library is used. *PRINT: The precompiler listing is generated. 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. The output member will have the same name as the name that is specified for the SRCMBR parameter. You can add or change text for a database source Appendix D. *CURLIB: The current library for the job is searched. the precompiler printout is directed to the IBM-supplied printer file QSYSPRT. More information on this parameter is in Appendix A. *LIBL: The job’s library list is searched for the specified file. If a file with a record length of less than 132 bytes is specified. The file must have a minimum length of 132 bytes. PRTFILE Specifies the qualified name of the printer device file to which the precompiler printout is directed. ″Expanded Parameter Descriptions″ in the CL Reference book. If no library is specified as the current library for the job. library-name: Specify the name of the library to be searched. TEXT Specifies the text that briefly describes the program and the function. printer-file-name: Specify the name of the printer device file to which the precompiler printout is directed. source-file-name: Specify the name of the source file to contain the output source member. QSYSPRT: If a file name is not specified. the QGPL library will be used. *NONE: The precompiler listing is not generated. The name of the printer file can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. If the file is not found in any library in the library list. *CURLIB: The current library for the job will be used. OUTPUT Specifies whether the precompiler listing is generated. If the specified source file is not found. library-name: Specify the name of the library that is to contain the output source file. DB2 UDB for AS/400 CL Command Descriptions 711 . If no library is specified as the current library for the job. the file will be created in the current library. The possible library values are: QTEMP: The library QTEMP will be used. it will be created. QSQLTEMP: The source file QSQLTEMP will be used.CRTSQLCPPI | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | language-identifier: Specify a language identifier. I *CURLIB/ Exec program-name ) CRTSQLPLI *LIBL/ SRCFILE( *CURLIB/ library-name/ QPLISRC source-file-name ) (1) *PGM source-file-member-name SRCMBR( ) OPTION( Option Details TGTRLS( *CURRENT *PRV VxRxMx ) *LIBL/ INCFILE( *CURLIB/ library-name/ *SRCFILE source-file-name ) 712 DB2 UDB for AS/400 SQL Programming V4R4 . 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. *BLANK: Text is not specified. CRTSQLPLI (Create Structured Query Language PL/I) Command Job: B. ’description’: Specify no more than 50 characters of text. Example CRTSQLCPPI 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 text is blank. If the source file is an inline file or a device file. enclosed in apostrophes.I PGM( library-name/ REXX: B.CRTSQLCPPI | | | | | | | | | | | | | | 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.I Pgm: B. DB2 UDB for AS/400 CL Command Descriptions 713 .CRTSQLPLI *UR *CHG *ALL *RS *CS *NONE *NC *RR *ENDPGM *ENDSQL *ENDJOB CLOSQLCSR( ) ) COMMIT( ALWCPYDTA( *OPTIMIZE *YES *NO ) ALWBLK( *ALLREAD *NONE *READ ) DLYPRP( *NO *YES ) GENLVL( 10 severity-level ) MARGINS( *SRCFILE left-right ) DATFMT( *JOB *USA *ISO *EUR *JIS *MDY *DMY *YMD *JUL ) DATSEP( *JOB '/' '.' '.' '-' ' ' *BLANK ) TIMFMT( *HMS *USA *ISO *EUR *JIS ) TIMSEP( *JOB ':' '.' '.' ' ' *BLANK ) REPLACE( *YES *NO ) RDB( *LOCAL relational-database-name *NONE ) Appendix D. CRTSQLPLI *CURRENT user-name *NONE password USER( ) PASSWORD( ) RDBCNNMTH( *DUW *RUW ) DFTRDBCOL( *NONE collection-name ) DYNDFTCOL( *NO *YES ) *PGMLIB/ SQLPKG( library-name/ *PGM package-name ) SQLPATH( *NAMING *LIBL ) collection-name SAAFLAG( *NOFLAG *FLAG ) FLAGSTD( *NONE *ANS ) *LIBL/ PRTFILE( *CURLIB/ library-name/ QSYSPRT printer-file-name ) SRTSEQ( *JOB *JOBRUN *LANGIDUNQ *LANGIDSHR *HEX *LIBL/ table-name *CURLIB/ library-name/ ) LANGID( *JOB *JOBRUN language-ID ) USRPRF( *NAMING *OWNER *USER ) 714 DB2 UDB for AS/400 SQL Programming V4R4 . Purpose The Create Structured Query Language PL/I (CRTSQLPLI) command calls a Structured Query Language (SQL) precompiler. produces a temporary source member. All parameters preceding this point can be specified in positional form. the QGPL library is used. 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. program-name: Specify the name of the compiled program. Parameters PGM Specifies the qualified name of the compiled program. and optionally calls the PL/I compiler to compile the program. library-name: Specify the name of the library where the compiled PL/I program is created. Appendix D. DB2 UDB for AS/400 CL Command Descriptions 715 .CRTSQLPLI *USER *OWNER DYNUSRPRF( ) QTEMP/ TOSRCFILE( *LIBL/ *CURLIB/ library-name/ QSQLTEMP source-file-name ) TEXT( *SCRMBRTXT *BLANK 'description' ) Option Details: *NOSRC *NOSOURCE *SRC *SOURCE *NOXREF *XREF *GEN *NOGEN *JOB *PERIOD *SYSVAL *COMMA *SYS *SQL *NOSECLVL *SECLVL *OPTLOB ) *NOOPTLOB Notes: 1. If no library is specified as the current library for the job. which precompiles PL/I source containing SQL statements. the QGPL library is used. The name of the source file can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. Element 2: Cross-Reference Options *NOXREF: The precompiler does not cross-reference names. or if two options conflict. OPTION Specifies whether one or more of the following options are used when the PL/I source is precompiled. This parameter is specified only if the source file name in the SRCFILE parameter is a database file. the PGM name specified on the PGM parameter is used. 716 DB2 UDB for AS/400 SQL Programming V4R4 . If no library is specified as the current library for the job. An SQL package object is created if a relational database name is specified on the RDB parameter. source-file-member-name: Specify the name of the member that contains the PL/I source. QPLISRC: If the source file name is not specified. *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 or *SRC: The precompiler produces a source printout consisting of PL/I source input. 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. SRCMBR Specifies the name of the source file member that contains the PL/I source. source-file-name: Specify the name of the source file that contains the PL/I source. the last option specified is used. *CURLIB: The current library for the job is searched. library-name: Specify the name of the library to be searched. *XREF: The precompiler cross-references items in the program to the statement numbers in the program that refer to those items. If an option is specified more than once. the IBM-supplied source file QPLISRC contains the PL/I source. Element 3: Program Creation Options *GEN: The compiler creates a program that can run after the program is compiled. If this parameter is not specified.CRTSQLPLI SRCFILE Specifies the qualified name of the source file that contains the PL/I source with SQL statements. Appendix D. *SYSVAL: The value used as the decimal point for numeric constants in SQL statements is the QDECFMT system value. 2.4. VALUES(1. If the first FETCH uses a LOB locator to access a LOB column.4. 4. *PERIOD: The value used as the decimal point for numeric constants used in SQL statements is a period. VALUES(1. 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.table-name). This option remains in effect until the cursor is closed. Element 5: Naming Convention Options *SYS: The system naming convention (library-name/file-name) is used. no subsequent FETCH for that cursor can use a LOB locator for that column. For example. no subsequent FETCH for that cursor can fetch that LOB column into a LOB host variable.23. *COMMA: The value used as the decimal point for numeric constants in SQL statements is a comma. 4.1) is equivalent to VALUES(1.23.CRTSQLPLI *NOGEN: The precompiler does not call the C compiler.1. For example.1) where the decimal point is a period.1) in which the decimal point is a period. DB2 UDB for AS/400 CL Command Descriptions 717 . If the first FETCH places the LOB column into a LOB host variable. 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.1. *SECLVL: Second-level text with replacement data is added to the printout for all messages on the listing.23. Element 6: Second-Level Message Text Option *NOSECLVL: Second-level text descriptions are not added to the listing.2. 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. *SQL: The SQL naming convention is used (collection-name. 2. Element 7: Large Object Optimization for DRDA Option *OPTLOB: The first FETCH for a cursor determines how the cursor will be used for LOBs (Large Objects) on all subsequent FETCHes. *SQL must be specified as the naming convention.2.1. and a program and SQL package are not created. Note: If QDECFMT specifies that the value used as the decimal point is a comma. When creating a program on a remote database other than an AS/400 system.1) is equivalent to VALUES(1.1.23. modification level 0. if V2R3M5 is running on the system. the QGPL library is used. The user can also use the object on a system with any subsequent release of the operating system installed. This option can cause performance to degrade. source-file-name: Specify the name of the source file that contains the source file members specified on any SQL INCLUDE statement. TGTRLS Specifies the release of the operating system on which the user intends to use the object being created. and the object is to be used on a system with V2R3M0 installed.CRTSQLPLI *NOOPTLOB: There is no restriction on whether a column is retrieved into a LOB locator or into a LOB host variable. 718 DB2 UDB for AS/400 SQL Programming V4R4 . V2R3M0 is version 2. The object can be used on a system with the specified release or with any subsequent release of the operating system installed. Note: If V2R3M5 is running on the system. In the examples given for the *CURRENT and *PRV values. *SRCFILE: The qualified source file specified in the SRCFILE parameter contains the source file members specified on any SQL INCLUDE statement. an error message is sent indicating the earliest supported release. release. specify TGTRLS(V2R3M0) not TGTRLS(*CURRENT). The user can also use the object on a system with any subsequent release of the operating system installed. *PRV means the user intends to use the object on a system with V2R2M0 installed. *CURRENT means the user intends to use the object on a system with V2R3M5 installed. release-level: Specify the release in the format VxRxMx. *CURRENT: The object is to be used on the release of the operating system currently running on the user’s system. *CURLIB: The current library for the job is searched. if V2R3M5 is running on the user’s system. Valid values depend on the current version. If no library is specified as the current library for the job. Rx is the release. For example. the format VxRxMx is used to specify the release. 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. release 3. *PRV: The object is to be used on the previous release with modification level 0 of the operating system. and modification level. and they change with each new release. library-name: Specify the name of the library to be searched. INCFILE Specifies the qualified name of the source file that contains members included in the program with any SQL INCLUDE statement. and when specifying the release-level value. For example. and Mx is the modification level. where Vx is the version. For example. If you specify a release-level which is earlier than the earliest release level supported by this command. The name of the source file can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. is locked until the next row is selected. but not updated. the program is treated as if *ENDPGM was specified. Uncommitted changes in other jobs can be seen. LABEL ON. SQL prepared statements are discarded. and LOCK TABLE locks are released. COMMIT. or ROLLBACK (without HOLD) SQL statements. *CS: Specifies the objects referred to in SQL ALTER. *CHG or *UR: Specifies the objects referred to in SQL ALTER. *ENDPGM: SQL cursors are closed and SQL prepared statements are discarded when the program ends. *ALL or *RS: Specifies the objects referred to in SQL ALTER. GRANT. Uncommitted changes in other jobs cannot be seen. updated. CALL. deleted. SQL cursors are explicitly closed when you issue the CLOSE. updated. and REVOKE statements and the rows selected. RENAME. GRANT. DROP. CALL. and inserted are locked until the end of the unit of work (transaction). One of the programs higher on the call stack must have run at least one SQL statement. *RR: Specifies the objects referred to in SQL ALTER. SQL views. If the SQL DROP COLLECTION statement is included in the program. CREATE. LOCK TABLE locks are released when the first SQL program on the call stack ends. DB2 UDB for AS/400 CL Command Descriptions 719 . Files referred to in the host language source are not affected by this option. SQL prepared statements are implicitly discarded. and inserted are locked until the end of the unit of work (transaction). RENAME. RENAME. All tables referred to in SELECT. and inserted are locked until the end of the unit of work (transaction). A row that is selected. Appendix D. COMMENT ON. and REVOKE statements and the rows updated. Uncommitted changes in other jobs can be seen. deleted. GRANT. and LOCK TABLE locks are released when the first SQL program on the call stack ends. and inserted are locked until the end of the unit of work (transaction). Only SQL tables. *NONE or *NC cannot be specified. CALL. LABEL ON. RENAME. CREATE. CREATE. UPDATE. Uncommitted changes in other jobs cannot be seen. CALL. CREATE. LABEL ON.CRTSQLPLI COMMIT Specifies whether SQL statements in the compiled program are run under commitment control. LABEL ON. and REVOKE statements and the rows selected. COMMENT ON. DELETE. 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 must be used. Uncommitted changes in other jobs cannot be seen. SQL cursors are closed. and REVOKE statements and the rows updated. DROP. DROP. DROP. *ENDSQL: SQL cursors remain open between calls and can be fetched without running another SQL OPEN. COMMENT ON. If *ENDSQL is specified for a program that is the first SQL program called (the first SQL program on the call stack). COMMENT ON. GRANT. and SQL packages referred to in SQL statements are affected. CLOSQLCSR Specifies when SQL cursors are implicitly closed. deleted. deleted. *NONE or *NC: Specifies that commitment control is not used. and INSERT statements are locked exclusively until the end of the unit of work (transaction). an error message is returned. | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ALWCPYDTA Specifies whether a copy of the data can be used in a SELECT statement. ALWBLK Specifies whether the database manager can use record blocking. *OPTIMIZE: The system determines whether to use the data retrieved directly from the database or to use a copy of the data. v May reduce the amount of time required to retrieve the first row of data for a query. SQL cursors are closed. cannot be used to update a row in a cursor unless the DECLARE statement for the cursor includes the FOR UPDATE clause. *ALLREAD: Rows are blocked for read-only cursors if *NONE or *CHG is specified on the COMMIT parameter. 720 DB2 UDB for AS/400 SQL Programming V4R4 .CRTSQLPLI *ENDJOB: SQL cursors remain open between calls and can be fetched without running another SQL OPEN. Specifying *ALLREAD: v Allows record blocking under commitment control level *CHG in addition to the blocking allowed for *READ. If a temporary copy of the data is required to perform the query. v Can degrade the overall performance of a query that retrieves a large number of rows. 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. using EXECUTE IMMEDIATE). *YES: A copy of the data is used only when necessary. Specifying *NONE: v Guarantees that the data retrieved is current. or if COMMIT is *ALL or *RR. The decision is based on which method provides the best performance. SQL prepared statements are preserved. and the extent to which blocking can be used for read-only cursors. or the ROLLBACK HOLD SQL statement does not reposition a read-only cursor when *ALLREAD is specified. and LOCK TABLE locks are released when the job ends. SQL cursors are left open. and LOCK TABLE locks are held when the first SQL program on the call stack ends. *NONE: Rows are not blocked for retrieval of data for cursors. The programs higher on the call stack do not need to have run SQL statements. – Dynamic running of a positioned UPDATE or DELETE statement (for example. If COMMIT is *CHG or *CS and ALWBLK is not *ALLREAD. a ROLLBACK statement in host languages. 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. SQL prepared statements are discarded. v Can improve the performance of almost all read-only cursors in programs. 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. but limits queries in the following ways: – The Rollback (ROLLBACK) command. EXECUTE. or DESCRIBE SQL statement.CRTSQLPLI | | | | | | | | *READ: Records are blocked for read-only retrieval of data for cursors when: v *NONE is specified on the COMMIT parameter. If you specify *YES on this parameter. or DESCRIBE statement is run. the margin values are the default values of 2 and 72. *YES: Dynamic statement validation is delayed until the dynamic statement is used in an OPEN. the margin values are the values specified on the SEU services display. Appendix D. When the dynamic statement is prepared. you should check the SQLCODE and SQLSTATE after running an OPEN. Element 1: Left Margin left: Specify the beginning position for the statements. the validation is completed and an access plan is built. GENLVL Specifies the severity level at which the create operation fails. or DESCRIBE statement to ensure that the dynamic statement is valid. the access plan is validated. DLYPRP Specifies whether the dynamic statement validation for a PREPARE statement is delayed until an OPEN. EXECUTE. Specifying *READ can improve the overall performance of queries that meet the above conditions and retrieve a large number of records. If the member is a different source type. Valid values range from 1 through 80. Delaying validation improves performance by eliminating redundant validation. When the dynamic statement is used. 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. *SRCFILE: The file member margin values specified by the user on the SRCMBR parameter are used. the access plan is revalidated. Note: If you specify *YES. 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. When the dynamic statement is used in an OPEN or EXECUTE statement. the operation ends. Because the authority or the existence of objects referred to by the dynamic statement may change. which indicates that commitment control is not used. *NO: Dynamic statement validation is not delayed. If errors occur that have a severity level greater than or equal to this value. you must still check the SQLCODE or SQLSTATE after issuing the OPEN or EXECUTE statement to ensure that the dynamic statement is still valid. 10: The default severity level is 10. MARGINS Specifies the part of the precompiler input record that contains source text. DB2 UDB for AS/400 CL Command Descriptions 721 . EXECUTE. If the member is a SQLPLI source type. severity-level: Specify a value ranging from 0 through 40. *USA: The United States date format (mm/dd/yyyy) is used. DATSEP Specifies the separator used when accessing date result columns. Use the Display Job (DSPJOB) command to determine the current date format for the job. *YMD. *DMY. *ISO.yyyy) is used.CRTSQLPLI Element 2: Right Margin right: Specify the ending position for the statements. 722 DB2 UDB for AS/400 SQL Programming V4R4 . Use the Display Job (DSPJOB) command to determine the current value for the job. *EUR. Note: An input date string that uses the format *USA. *ISO: The International Organization for Standardization (ISO) date format (yyyy-mm-dd) is used. ’. If a relational database is specified on the RDB parameter and the database is on a system that is not an AS/400 system.) is used. the specified value is used to determine whether the date is specified in a valid format. *DMY: The date format (dd/mm/yy) is used. then *USA. *BLANK: A blank ( ) is used. DATFMT Specifies the format used when accessing date result columns.) is used. All output date fields are returned in the specified format. or *JUL is specified on the DATFMT parameter.mm. or *JIS is always valid. Valid values range from 1 through 80. *YMD: The date format (yy/mm/dd) is used. *EUR. *JUL: The Julian date format (yy/ddd) is used. *MDY: The date format (mm/dd/yy) is used. ’/’: A slash (/) is used. Note: This parameter applies only when *JOB. *JIS: The Japanese Industrial Standard date format (yyyy-mm-dd) is used.’: A period (. *ISO. ’-’: A dash (-) is used.’: A comma (. *EUR: The European date format (dd. *JOB: The date separator specified for the job at precompile time is used. ’ ’: A blank ( ) is used. or *JIS must be specified. *JOB: The format specified for the job is used. For input date strings. *MDY. ’. *HMS: The (hh:mm:ss) format is used.’: A comma (. *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. For input time strings. *YES: A new program or SQL package is created. the time format must be *USA.) is used. ’. ’. *BLANK: A blank ( ) is used. ’ ’: A blank ( ) is used. *JOB: The time separator specified for the job at precompile time is used. the specified value is used to determine whether the time is specified in a valid format.mm. DB2 UDB for AS/400 CL Command Descriptions 723 . *USA: The United States time format (hh:mm xx) is used. Note: This parameter applies only when *HMS is specified on the TIMFMT parameter. *JIS: The Japanese Industrial Standard time format (hh:mm:ss) is used. or *HMS with a time separator of colon or period.) is used. TIMSEP Specifies the separator used when accessing time result columns.’: A period (. where xx is AM or PM. *ISO: The International Organization for Standardization (ISO) time format (hh. *ISO. or *JIS is always valid. and any existing program or SQL package of the same name and type in the specified library is moved to QRPLOBJ. *ISO. ’:’: A colon (:) is used. *JIS.mm. Appendix D. Note: An input date string that uses the format *USA. Use the Display Job (DSPJOB) command to determine the current value for the job. *EUR: The European time format (hh. If a relational database is specified on the RDB parameter and the database is on a system that is not another AS/400 system. ″Expanded Parameter Descriptions″ in the CL Reference (Abridged) book. *EUR. More information on this parameter is in Appendix A. *EUR.ss) is used.ss) is used.CRTSQLPLI TIMFMT Specifies the format used when accessing time result columns. The value of this parameter is passed to the CRTPLIPGM command. 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. *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. This parameter is valid only when RDB is specified. This parameter applies only to static SQL statements. views. The SQL statements will access the local database. collection-name: Specify the name of the collection identifier. DFTRDBCOL Specifies the collection name used for the unqualified names of tables. *RUW: CONNECT (Type 1) semantics are used to support remote unit of work. relational-database-name: Specify the name of the relational database where the new SQL package object is to be created. *LOCAL: The program is created as a distributed SQL program. This parameter is valid only if RDB is specified. password: Specify the password of the user name specified on the USER parameter. and SQL packages. *NONE: No password is sent. user-name: Specify the user name being used for the application server job. Consecutive CONNECT statements to additional relational databases do not result in disconnection of previous connections. USER Specifies the user name sent to the remote system when starting the conversation. USER(*CURRENT) must also be specified. If this value is specified. This value is used instead of the naming convention specified on the OPTION parameter. The Create Structured Query Language Package (CRTSQLPKG) command can be used. *DUW: CONNECT (Type 2) semantics are used to support distributed unit of work. *NONE: The naming convention defined on the OPTION parameter is used.CRTSQLPLI RDB Specifies the name of the relational database where the SQL package object is created. *CURRENT: The user profile under which the current job is running is used. Consecutive CONNECT statements result in the previous connection being disconnected before a new connection is established. PASSWORD Specifies the password to be used on the remote system. When the name of the local relational database is specified. 724 DB2 UDB for AS/400 SQL Programming V4R4 . the program created is still a distributed SQL program. An SQL package object is not created as part of the precompile process. indexes. The SQL statements will access the local database. Refer to the SQL Reference book for more information. RDBCNNMTH Specifies the semantics used for CONNECT statements. SQLPKG Specifies the qualified name of the SQL package created on the relational database specified on the RDB parameter of this command. *NOFLAG: The precompiler does not check to see whether SQL statements conform to IBM SQL syntax. indexes.CRTSQLPLI | | | | | | | | | | DYNDFTCOL Specifies whether the default collection name specified for the DFTRDBCOL parameter is also used for dynamic statements. indexes. functions. views. For *SYS naming. Appendix D. the path used is *LIBL. 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. The possible library values are: *PGMLIB: The package is created in the library with the same name as the library containing the program. If a collection-name is specified on the DFTRDBCOL parameter. *PGM: The package name is the same as the program name. *FLAG: The precompiler checks to see whether SQL statements conform to IBM SQL syntax. the collection-name takes the place of userid. collection-name: Specify a list of one or more collection names. the path used is ″QSYS″. For *SQL naming. views. | | | | | | | | | | | | SQLPATH Specifies the path to be used to find procedures. package-name: Specify the name of the package created on the remote database specified on the RDBNAME parameter. *NAMING: The path used depends on the naming convention specified on the OPTION parameter. *LIBL: The path used is the library list at runtime. ″QSYS2″. and SQL packages for dynamic SQL statements. SC26-3255-00. *NO: Do not use the value specified on the DFTRDBCOL parameter for unqualified names of tables. and SQL packages in dynamic SQL statements. *YES: The collection name specified on the DFTRDBCOL parameter will be used for the unqualified names of the tables. ″userid″. and user defined types in static SQL statements. SAAFLAG Specifies the IBM SQL flagging function. where ″userid″ is the value of the USER special register. A maximum of 43 individual collections may be specified. DB2 UDB for AS/400 CL Command Descriptions 725 . The naming convention specified on the OPTION parameter is used. the current library list at runtime. library-name: Specify the name of the library where the package is created. 2 entry Specifies the American National Standards Institute (ANSI) flagging function. ANSI X3. *ANS: The precompiler checks to see whether SQL statements conform to ANSI standards. *JOBRUN: The SRTSEQ value for the job is retrieved when the program is run. The file must have a minimum record length of 132 bytes or information is lost. PRTFILE Specifies the qualified name of the printer device file to which the listing is directed. This parameter flags SQL statements to verify whether they conform to the following standards. library-name: Specify the name of the library to be searched. QSYSPRT: If a file name is not specified. SRTSEQ(*JOBRUN) is valid only when LANGID(*JOBRUN) is also specified.2 entry *NONE: The precompiler does not check to see whether SQL statements conform to ANSI standards. 726 DB2 UDB for AS/400 SQL Programming V4R4 . For distributed applications. *CURLIB: The current library for the job is searched.CRTSQLPLI FLAGSTD Specifies the American National Standards Institute (ANSI) flagging function.135-1992 entry ISO 9075-1992 entry FIPS 127. The name of the printer file can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. the QGPL library is used. 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. printer-file-name: Specify the name of the printer device file to which the precompiler printout is directed. *LANGIDUNQ: The unique-weight sort table for the language specified on the LANGID parameter is used.135-1992 entry ISO 9075-1992 entry FIPS 127. This parameter flags SQL statements to verify whether they conform to the following standards. If no library is specified as the current library for the job. ANSI X3. the precompiler printout is directed to the IBM-supplied printer file QSYSPRT. *JOB: The SRTSEQ value for the job is retrieved during the precompile. SRTSEQ Specifies the sort sequence table to be used for string comparisons in SQL statements. *USER: The profile of the user running the program object is used. *CURLIB: The current library for the job is searched. *OWNER: Local dynamic SQL statements are run under the user profile of the program’s owner. For distributed applications. Distributed dynamic SQL statements are run under the user profile of the SQL package’s owner. the QGPL library is used. USRPRF(*USER) is used. DB2 UDB for AS/400 CL Command Descriptions 727 . Distributed dynamic SQL statements are run under the user profile of the application server job. *HEX: A sort sequence table is not used.CRTSQLPLI *LANGIDSHR: The shared-weight sort table for the language specified on the LANGID parameter is used. *NAMING: The user profile is determined by the naming convention. table-name: Specify the name of the sort sequence table to be used. *OWNER: The user profiles of both the program owner and the program user are used when the program is run. USRPRF Specifies the user profile that is used when the compiled program object is run. The profile of either the program owner or the program user is used to control which objects can be used by the program object. The hexadecimal values of the characters are used to determine the sort sequence. USRPRF(*OWNER) is used. *JOB: The LANGID value for the job is retrieved during the precompile. If the naming convention is *SQL. LANGID Specifies the language identifier to be used when SRTSEQ(*LANGIDUNQ) or SRTSEQ(*LANGIDSHR) is specified. DYNUSRPRF Specifies the user profile used for dynamic SQL statements. If the naming convention is *SYS. | | | 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 no library is specified as the current library for the job. LANGID(*JOBRUN) is valid only when SRTSEQ(*JOBRUN) is also specified. *USER: Local dynamic SQL statements are run under the user profile of the job. library-name: Specify the name of the library to be searched. The name of the sort sequence table can be qualified by one of hte following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. including the authority that the program object has for each object in static SQL statements. *JOBRUN: The LANGID value for the job is retrieved when the program is run. If the Appendix D. language-id: Specify a language identifier to be used by the program. source-file-name: Specify the name of the source file to contain the output source member. If no library is specified as the current library for the job. library-name: Specify the name of the library that is to contain the output source file. *SCRMBRTXT: The text is taken from the source file member being used to create the PL/I program. the file will be created in the current library. TEXT Specifies the text that briefly describes the program and its function. QSQLTEMP: The source file QSQLTEMP will be used. *BLANK: Text is not specified. the QGPL library will be used. *CURLIB: The current library for the job will be used. ’description’: Specify no more than 50 characters of text. More information on this parameter is in Appendix A.I PGM( library-name/ REXX: B. If the file is not found in any library in the library list. The output member will have the same name as the name that is specified for the SRCMBR parameter.I Pgm: B. ″Expanded Parameter Descriptions″ in the CL Reference (Abridged) book. If the source file is an inline file or a device file. The PL/I compiler is called to create program PAYROLL in the current library using the source member created by the SQL precompiler. it will be created. the text is blank. or by using either the Add Physical File Member (ADDPFM) or Change Physical File Member (CHGPFM) command.I *CURLIB/ Exec program-name ) CRTSQLRPG 728 DB2 UDB for AS/400 SQL Programming V4R4 . The possible library values are: QTEMP: The library QTEMP will be used. which precompiles the source and stores the changed source in member PAYROLL in file QSQLTEMP in library QTEMP. Example CRTSQLPLI PAYROLL TEXT('Payroll Program') This command runs the SQL precompiler. The user can add or change text for a database source member by using the Start Source Entry Utility (STRSEU) command. *LIBL: The job’s library list is searched for the specified file. CRTSQLRPG (Create Structured Query Language RPG) Command Job: B.CRTSQLPLI | | | | | | | | | | | | | | specified source file is not found. enclosed in apostrophes. ' '-' ' ' *BLANK ) Appendix D.' '.CRTSQLRPG *LIBL/ SRCFILE( *CURLIB/ library-name/ QRPGSRC source-file-name ) (1) *PGM source-file-member-name SRCMBR( ) OPTION( OPTION DETAILS ) TGTRLS( *CURRENT *PRV VxRxMx ) *LIBL/ INCFILE( *CURLIB/ library-name/ *SRCFILE source-file-name ) COMMIT( *UR *CHG *ALL *RS *CS *NONE *NC *RR CLOSQLCSR( ) *ENDPGM *ENDSQL *ENDJOB ) ALWCPYDTA( *OPTIMIZE *YES *NO ) ALWBLK( *ALLREAD *NONE *READ ) DLYPRP( *NO *YES ) GENLVL( 10 severity-level ) DATFMT( *JOB *USA *ISO *EUR *JIS *MDY *DMY *YMD *JUL ) DATSEP( *JOB '/' '. DB2 UDB for AS/400 CL Command Descriptions 729 . ' '.' ' ' *BLANK TIMFMT( ) TIMSEP( ) REPLACE( *YES *NO ) RDB( *LOCAL relational-database-name *NONE ) USER( *CURRENT user-name ) PASSWORD( *NONE password ) RDBCNNMTH( *DUW *RUW ) DFTRDBCOL( *NONE collection-name ) DYNDFTCOL( *NO *YES ) *PGMLIB/ SQLPKG( library-name/ *PGM package-name ) SQLPATH( *NAMING *LIBL ) collection-name SAAFLAG( *NOFLAG *FLAG ) FLAGSTD( *NONE *ANS ) *LIBL/ PRTFILE( *CURLIB/ library-name/ QSYSPRT printer-file-name ) 730 DB2 UDB for AS/400 SQL Programming V4R4 .CRTSQLRPG *HMS *USA *ISO *EUR *JIS *JOB ':' '. DB2 UDB for AS/400 CL Command Descriptions 731 . 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 Appendix D.CRTSQLRPG *JOB *JOBRUN *LANGIDUNQ *LANGIDSHR *HEX *LIBL/ table-name *CURLIB/ library-name/ SRTSEQ( ) LANGID( *JOB *JOBRUN language-ID ) USRPRF( *NAMING *OWNER *USER ) DYNUSRPRF( *USER *OWNER ) QTEMP/ TOSRCFILE( *LIBL/ *CURLIB/ library-name/ QSQLTEMP source-file-name ) TEXT( *SRCMBRTXT *BLANK 'description' ) OPTION Details: *NOSRC *NOSOURCE *SOURCE *SRC *NOXREF *XREF *GEN *NOGEN *JOB *SYSVAL *PERIOD *COMMA *SYS *SQL *NOSECLVL *SECLVL *NOSEQSRC *SEQSRC *NOLSTDBG *LSTDBG Notes: 1. If no library is specified as the current library for the job. *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. OPTION Specifies whether one or more of the following options are used when the RPG source is precompiled. library-name: Specify the name of hte library where the compiled RPG program is created. the QGPL library is used. source-file-name: Specify the name of the source file that contains the RPG source. This parameter is specified only if the source file name in the SRCFILE parameter is a database file. *CURLIB: The current library for the job is searched. If an option is specified more than once.CRTSQLRPG containing the SQL statements. the IBM-supplied source file QRPGSRC contains the RPG source. QRPGSRC: If the source file name is not specified. and then optionally calls the RPG compiler to compile the program. The name of the source file can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. SRCFILE Specifies the qualified name of the source file that contains the RPG source with SQL statements. program-name: Specify the name of the compiled program. the last option specified is used. If no library is specified as the current library for the job. the QGPL library is used. source-file-member-name: Specify the name of the member that contains the RPG source. SRCMBR Specifies the name of hte source file member that contains the RPG source. or if two options conflict. the PGM name specified on the PGM parameter is used. Element 1: Source Listing Options 732 DB2 UDB for AS/400 SQL Programming V4R4 . Parameters PGM Specifies the qualified name of the compiled program. library-name: Specify the name of the library to be searched. If this parameter is not specified. 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. produces a temporary source member. 23. and a program and SQL package are not created.1.1.23. 2.1) is equivalent to VALUES(1.1. VALUES clause. VALUES(1. *SYSVAL: The value used as the decimal point for numeric constants in SQL statements is the QDECFMT system value. and so on. For example. consisting of RPG source input.2. 4. *XREF: The precompiler cross-references items in the program to the statement numbers in the program that refer to those items.23. DB2 UDB for AS/400 CL Command Descriptions 733 . Element 3: Program Creation Options *GEN: The compiler creates a program that can run after the program is compiled. 2.2. Note: If QDECFMT specifies that the value used as the decimal point is a comma.1) where the decimal point is a period. An SQL package object is created if a relational database name is specified on the RDB parameter. *SOURCE or *SRC: The precompiler produces a source printout. *COMMA: The value used as the decimal point for numeric constants in SQL statements is a comma.1. Element 6: Second-Level Message Text Option Appendix D. Note: Any numeric constants in lists (such as in the SELECT clause.table-name).1) is equivalent to VALUES(1.23. *NOGEN: The precompiler does not call the RPG compiler.) must be separated by a comma followed by a blank. *SQL must be specified as the naming convention. Element 5: Naming Convention Options *SYS: The system naming convention (library-name/file-name) is used. and so on.4.) must be separated by a comma followed by a blank. When creating a program on a remote database other than an AS/400 system.1) where the decimal point is a period. VALUES(1. any numeric constants in lists (such as in the SELECT clause. For example. *SQL: The SQL naming convention is used (collection-name.4.CRTSQLRPG *NOSOURCE or *NOSRC: A source printout is not produced by the precompiler unless errors are detected during precompile or create package. Element 2: Cross-Reference Options *NOXREF: The precompiler does not cross-reference names. 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. VALUES clause. *PERIOD: The value used as the decimal point for numeric constants used in SQL statements is a period. 4. *CURRENT means the user intends to use the object on a system with V2R3M5 installed. and modification level. The user can also use the object on a system with any subsequent release of the operating system installed. Element 8: Debug Listing View Option *NOLSTDBG: Error and debug information is not generated. INCFILE Specifies the qualified name of the source file that contains members included in the program with any SQL INCLUDE statement. For example. and they change with each new release. Note: If V2R3M5 is running on the system. *PRV: The object is to be used on the previous release with modification level 0 of the operating system. The user can also use the object on a system with any subsequent release of the operating system installed. In the examples given for the *CURRENT and *PRV values.CRTSQLRPG *NOSECLVL: Second-level text descriptions are not added to the listing. *PRV means the user intends to use the object on a system with V2R2M0 installed. an error message is sent indicating the earliest supported release. and the object is to be used on a system with V2R3M0 installed. where Vx is the version. The object can be used on a system with the specified release or with any subsequent release of the operating system installed. *CURRENT: The object is to be used on the release of the operating system currently running on the user’s system. release. For example. 734 DB2 UDB for AS/400 SQL Programming V4R4 . modification level 0. if V2R3M5 is running on the user’s system. You can use *LSTDBG only if you are using the CODE/400 product to compile your program. and Mx is the modification level. Rx is the release. specify TGTRLS(V2R3M0) not TGTRLS(*CURRENT). and when specifying the release-level value. Valid values depend on the current version. if V2R3M5 is running on the system. release 3. *LSTDBG: The SQL precompiler generates a listing view and error and debug information required for this view. *SECLVL: Second-level text with replacement data is added for all messages on the listing. release-level: Specify the release in the format VxRxMx. V2R3M0 is version 2. 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. TGTRLS Specifies the release of the operating system on which the user intends to use the object being created. For example. *SEQSRC: Source records written to the new source member in QSQLTEMP are numbered starting at 000001. If you specify a release-level which is earlier than the earliest release level supported by this command. the format VxRxMx is used to specify the release. *NONE or *NC: Specifies that commitment control is not used. DROP. CREATE. and inserted are locked until the end of the unit of work (transaction). *CS: Specifies the objects referred to in SQL ALTER. COMMENT ON. GRANT. *NONE or *NC cannot be specified. library-name: Specify the name of the library to be searched. RENAME. DROP. Uncommitted changes in other jobs cannot be seen. 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. If no library is specified as the current library for the job. GRANT. Uncommitted changes in other jobs cannot be seen. is locked until the next row is selected. *CURLIB: The current library for the job is searched. If the SQL DROP COLLECTION statement is included in the program. updated. deleted. and inserted are locked until the end of the unit of work (transaction). CREATE. RENAME. *SRCFILE: The qualified source file specified in the SRCFILE parameter contains the source file members specified on any SQL INCLUDE statement. *CHG or *UR: Specifies the objects referred to in SQL ALTER. LABEL ON. Only SQL tables. A row that is selected. 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. but not updated. CREATE. CREATE. COMMENT ON. *NONE or *NC must be used. and inserted are locked until the end of the unit of work (transaction). *ALL or *RS: Specifies the objects referred to in SQL ALTER. Appendix D.CRTSQLRPG The name of the source file can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. the QGPL library is used. updated. COMMENT ON. GRANT. COMMENT ON. and inserted are locked until the end of the unit of work (transaction). LABEL ON. and INSERT statements are locked exclusively until the end of the unit of work (transaction). CALL. and REVOKE statements and the rows selected. SQL views. Uncommitted changes in other jobs can be seen. CALL. LABEL ON. COMMIT Specifies whether SQL statements in the compiled program are run under commitment control. LABEL ON. DB2 UDB for AS/400 CL Command Descriptions 735 . Uncommitted changes in other jobs can be seen. All tables referred to in SELECT. Files referred to in the host language source are not affected by this option. UPDATE. *RR: Specifies the objects referred to in SQL ALTER. CALL. DROP. DROP. and REVOKE statements and the rows updated. GRANT. and REVOKE statements and the rows selected. deleted. RENAME. source-file-name: Specify the name of the source file that contains the source file members specified on any SQL INCLUDE statement. Uncommitted changes in other jobs cannot be seen. Note: Files referenced in the RPG source are not affected by this option. CALL. DELETE. deleted. deleted. RENAME. and REVOKE statements and the rows updated. and SQL packages referred to in SQL statements are affected. v Can improve the performance of almost all read-only cursors in programs. *YES: A copy of the data is used only when necessary. then a copy of the data is used only when it is necessary to run a query. and LOCK TABLE locks are held when the first SQL program on the call stack ends. and LOCK TABLE locks are released when the job ends. SQL prepared statements are implicitly discarded. *ALLREAD: Rows are blocked for read-only cursors if *NONE or *CHG is specified on the COMMIT parameter. COMMIT. Specifying *ALLREAD: v Allows record blocking under commitment control level *CHG in addition to the blocking allowed for *READ. an error message is returned. The decision is based on which method provides the best performance. the program is treated as if *ENDPGM was specified. ALWBLK Specifies whether the database manager can use record blocking. | | | | | | | | | | | | | | | | | | | | | | ALWCPYDTA Specifies whether a copy of the data can be used in a SELECT statement. SQL prepared statements are discarded. The programs higher on the call stack do not need to have run SQL statements. and LOCK TABLE locks are released when the first SQL program on the call stack ends. and the extent to which blocking can be used for read-only cursors. *OPTIMIZE: The system determines whether to use the data retrieved directly from the database or to use a copy of the data. SQL cursors are explicitly closed when you issue the CLOSE. SQL cursors are closed. or ROLLBACK (without HOLD) SQL statements. If a temporary copy of the data is required to perform the query. If *ENDSQL is specified for a program that is the first SQL program called (the first SQL program on the call stack). *NO: A copy of the data is not allowed. *ENDJOB: 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. *ENDSQL: SQL cursors remain open between calls and can be fetched without running another SQL OPEN. SQL prepared statements are preserved. or if COMMIT is *ALL or *RR. LOCK TABLE locks are released when the first SQL program on the call stack ends. but limits queries in the following ways: 736 DB2 UDB for AS/400 SQL Programming V4R4 . SQL cursors are left open.CRTSQLRPG CLOSQLCSR Specifies when SQL cursors are implicitly closed. *ENDPGM: SQL cursors are closed and SQL prepared statements are discarded when the program ends. SQL cursors are closed. SQL prepared statements are discarded. 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. and LOCK TABLE locks are released. If COMMIT is *CHG or *CS and ALWBLK is not *ALLREAD. Delaying validation improves performance by eliminating redundant validation. using EXECUTE IMMEDIATE). or the ROLLBACK HOLD SQL statement does not reposition a read-only cursor when *ALLREAD is specified. EXECUTE. Specifying *NONE: v Guarantees that the data retrieved is current. the validation is completed and an access plan is built. Specifying *READ can improve the overall performance of queries that meet the above conditions and retrieve a large number of records. *READ: Records are blocked for read-only retrieval of data for cursors when: v *NONE is specified on the COMMIT parameter. Appendix D. – Dynamic running of a positioned UPDATE or DELETE statement (for example. the access plan is validated. *NONE: Rows are not blocked for retrieval of data for cursors. DB2 UDB for AS/400 CL Command Descriptions 737 .CRTSQLRPG | | | | | | | | | | | | | | | | | | | | | | | | | – The Rollback (ROLLBACK) command. 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. the access plan is revalidated. Note: If you specify *YES. or DESCRIBE statement is run. or DESCRIBE statement to ensure that the dynamic statement is valid. If you specify *YES on this parameter. EXECUTE. When the dynamic statement is used in an OPEN or EXECUTE statement. Because the authority or the existence of objects referred to by the dynamic statement may change. a ROLLBACK statement in host languages. DLYPRP Specifies whether the dynamic statement validation for a PREPARE statement is delayed until an OPEN. When the dynamic statement is prepared. or DESCRIBE SQL statement. you should check the SQLCODE and SQLSTATE after running an OPEN. cannot be used to update a row in a cursor unless the DECLARE statement for the cursor includes the FOR UPDATE clause. 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. *YES: Dynamic statement validation is delayed until the dynamic statement is used in an OPEN. EXECUTE. you must still check the SQLCODE or SQLSTATE after issuing the OPEN or EXECUTE statement to ensure that the dynamic statement is still valid. 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. which indicates that commitment control is not used. v Can degrade the overall performance of a query that retrieves a large number of rows. When the dynamic statement is used. *NO: Dynamic statement validation is not delayed. v May reduce the amount of time required to retrieve the first row of data for a query. DATFMT Specifies the format used when accessing date result columns. *EUR. the specified value is used to determine whether the date is specified in a valid format. *DMY. For input date strings. Note: This parameter applies only when *JOB. *YMD. ’. ’. *JIS: The Japanese Industrial Standard date format (yyyy-mm-dd) is used. *JOB: The date separator specified for the job at precompile time is used. *EUR. *MDY. 10: The default severity level is 10. *YMD: The date format (yy/mm/dd) is used.CRTSQLRPG GENLVL Specifies the severity level at which the create operation fails. *MDY: The date format (mm/dd/yy) is used. *EUR: The European date format (dd.yyyy) is used. *ISO. If errors occur that have a severity level greater than or equal to this value. All output date fields are returned in the specified format.) is used. the operation ends. Use the Display Job (DSPJOB) command to determine the current date format for the job.) is used.’: A comma (. or *JIS is always valid. ’/’: A slash (/) is used. *JUL: The Julian date format (yy/ddd) is used. DATSEP Specifies the separator used when accessing date result columns. 738 DB2 UDB for AS/400 SQL Programming V4R4 . severity-level: Specify a value ranging from 0 through 40. then *USA. *JOB: The format specified for the job is used. Note: An input date string that uses the format *USA. or *JIS must be specified. ’-’: A dash (-) is used. If a relational database is specified on the RDB parameter and the database is on a system that is not an AS/400 system.’: A period (. Use the Display Job (DSPJOB) command to determine the current value for the job.mm. or *JUL is specified on the DATFMT parameter. *ISO. *DMY: The date format (dd/mm/yy) is used. *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. The value of this parameter is passed to the C command. or *HMS with a time separator of colon or period.’: A period (. *EUR: The European time format (hh. For input time strings. Use the Display Job (DSPJOB) command to determine the current value for the job.More information on this parameter is in Appendix A. *HMS: The (hh:mm:ss) format is used. 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. Note: This parameter applies only when *HMS is specified on the TIMFMT parameter. *ISO. ’. *EUR. *JOB: The time separator specified for the job at precompile time is used. DB2 UDB for AS/400 CL Command Descriptions 739 . *ISO. *JIS. TIMSEP Specifies the separator used when accessing time result columns. the time format must be *USA. *BLANK: A blank ( ) is used. ″Expanded Parameter Descriptions″ in the CL Reference (Abridged) book.CRTSQLRPG ’ ’: A blank ( ) is used. *BLANK: A blank ( ) is used. Note: An input date string that uses the format *USA.ss) is used.) is used. *EUR.’: A comma (. the specified value is used to determine whether the time is specified in a valid format.) is used. *ISO: The International Organization for Standardization (ISO) time format (hh.mm. TIMFMT Specifies the format used when accessing time result columns.mm. ’:’: A colon (:) is used. ’. *USA: The United States time format (hh:mm xx) is used. ’ ’: A blank ( ) is used.ss) is used. Appendix D. 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. where xx is AM or PM. *JIS: The Japanese Industrial Standard time format (hh:mm:ss) is used. the program created is still a distributed SQL program. *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. *NONE: An SQL package object is not created. and any existing program or SQL package of the same name and type in the specified library is moved to QRPLOBJ. USER Specifies the user name sent to the remote system when starting the conversation. *NONE: No password is sent. PASSWORD Specifies the password to be used on the remote system. *LOCAL: The program is created as a distributed SQL program. *DUW: CONNECT (Type 2) semantics are used to support distributed unit of work. Consecutive CONNECT statements result in the previous connection being disconnected before a new connection is established. The program object is not a distributed program and the Create Structured Query Language Package (CRTSQLPKG) command cannot be used. Refer to the SQL Reference.CRTSQLRPG *YES: A new program or SQL package is created. The SQL statements will access the local database. *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. When the name of the local relational database is specified. USER(*CURRENT) must also be specified. An SQL package object is not created as part of the precompile process. The SQL statements will access the local database. If this value is specified. relational-database-name: Specify the name of the relational database where the new SQL package object is to be created. Consecutive CONNECT statements to additional relational databases do not result in disconnection of previous connections. SC41-3612 book for more information. password: Specify the password of the user name specified on the USER parameter. *RUW: CONNECT (Type 1) semantics are used to support remote unit of work. RDBCNNMTH Specifies the semantics used for CONNECT statements. RDB Specifies the name of the relational database where the SQL package object is created. This parameter is valid only when RDB is specified. 740 DB2 UDB for AS/400 SQL Programming V4R4 . This parameter is valid only if RDB is specified. The Create Structured Query Language Package (CRTSQLPKG) command can be used. If a collection-name is specified on the DFTRDBCOL parameter. package-name: Specify the name of the package created on the remote database specified on the RDBNAME parameter. *NONE: The naming convention defined on the OPTION parameter is used. For *SQL naming. collection-name: Specify the name of the collection identifier. *NO: Do not use the value specified on the DFTRDBCOL parameter for unqualified names of tables. the current library list at runtime. indexes. SAAFLAG Specifies the IBM SQL flagging function. library-name: Specify the name of the library where the package is created. and user defined types in static SQL statements. | | | | | | | | | | DYNDFTCOL Specifies whether the default collection name specified for the DFTRDBCOL parameter is also used for dynamic statements. where ″userid″ is the value of the USER special register. A maximum of 43 individual collections may be specified.CRTSQLRPG DFTRDBCOL Specifies the collection name used for the unqualified names of tables. DB2 UDB for AS/400 CL Command Descriptions 741 . collection-name: Specify a list of one or more collection names. For *SYS naming. and SQL packages for dynamic SQL statements. | | | | | | | | | | | | SQLPATH Specifies the path to be used to find procedures. indexes. The possible library values are: *PGMLIB: The package is created in the library with the same name as the library containing the program. and SQL packages. *NAMING: The path used depends on the naming convention specified on the OPTION parameter. *PGM: The package name is the same as the program name. views. the path used is *LIBL. ″userid″. 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. ″QSYS2″. views. the path used is ″QSYS″. *YES: The collection name specified on the DFTRDBCOL parameter will be used for the unqualified names of the tables. functions. views. This parameter flags SQL statements Appendix D. and SQL packages in dynamic SQL statements. This parameter applies only to static SQL statements. The naming convention specified on the OPTION parameter is used. the collection-name takes the place of userid. *LIBL: The path used is the library list at runtime. indexes. ANSI X3. 742 DB2 UDB for AS/400 SQL Programming V4R4 .2 entry *NONE: The precompiler does not check to see whether SQL statements conform to ANSI standards. FLAGSTD Specifies the American National Standards Institute (ANSI) flagging function. The name of the printer file can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. SC26-3255-00. *ANS: The precompiler checks to see whether SQL statements conform to ANSI standards. library-name: Specify the name of the printer device file to which the compiler printout is directed. The file must have a minimum record length of 132 bytes or information is lost. the precompiler printout is directed to the IBM-supplied printer file QSYSPRT. *NOFLAG: The precompiler does not check to see whether SQL statements conform to IBM SQL syntax. the QGPL library is used. This parameter flags SQL statements to verify whether they conform to the following standards. QSYSPRT: If a file name is not specified. printer-file-name: Specify the name of the printer device file to which the compiler printout is directed. SRTSEQ(*JOBRUN) is valid only when LANGID(*JOBRUN) is also specified. PRTFILE Specifies the qualified name of the printer device file to which the listing is directed. *JOB: The SRTSEQ value for the job is retrieved during the precompile.CRTSQLRPG 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. *JOBRUN: The SRTSEQ value for the job is retrieved when the program is run. If no library is specified as the current library for the job. 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. *CURLIB: The current library for the job is searched.135-1992 entry ISO 9075-1992 entry FIPS 127. For distributed applications. *FLAG: The precompiler checks to see whether SQL statements conform to IBM SQL syntax. USRPRF(*OWNER) is used. The name of the sort sequence table can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. language-id: Specify a language identifier to be used by the program. Distributed dynamic SQL statements are run under the user profile of the application server job. *USER: Local dynamic SQL statements are run under the user profile of the job. LANGID(*JOBRUN) is valid only when SRTSEQ(*JOBRUN) is also specified. *LANGIDSHR: The shared-weight sort table for the language specified on the LANGID parameter is used. If the naming convention is *SYS. table-name: Specify the name of the sort sequence table to be used. *JOB: The LANGID value for hte job is retrieved during the precompile. USRPRF(*USER) is used. *OWNER: Local dynamic SQL statements are run under the user profile of the program’s owner. For distributed applications. the QGPL library is used. including the authority that the program object has for each object in static SQL statements. library-name: Specify the name of the library to be searched. *USER: The profile of the user running the program object is used. Distributed dynamic SQL statements are run under the user profile of the SQL package’s owner. Appendix D. *HEX: A sort sequence table is not used. *CURLIB: The current library for the job is searched. *NAMING: The user profile is determined by the naming convention. *OWNER: The user profiles of both the program owner and the program user are used when the program is run. If the naming convention is *SQL.CRTSQLRPG *LANGIDUNQ: The unique-weight sort table for the language specified on the LANGID parameter is used. DB2 UDB for AS/400 CL Command Descriptions 743 . The profile of either the program owner or the program user is used to control which objects can be used by the program object. USRPRF Specifies the user profile that is used when the compiled program object is run. If no library is specified as the current library for the job. DYNUSRPRF Specifies the user profile used for dynamic SQL statements. The hexadecimal values of the characters are used to determine the sort sequence. LANGID Specifies the language identifier to be used when SRTSEQ(*LANGIDUNQ) or SRTSEQ(*LANGIDSHR) is specified. *JOBRUN: The LANGID value for the job is retrieved when the program is run. If the specified source file is not found. ″Expanded Parameter Descriptions″ in the CL Reference book. *LIBL: The job’s library list is searched for the specified file. the file will be created in the current library. the text is blank. it will be created. *CURLIB: The current library for the job will be used. enclosed in apostrophes. library-name: Specify the name of the library that is to contain the output source file. CRTSQLRPGI (Create SQL ILE RPG Object) Command Job: B. The output member will have the same name as the name that is specified for the SRCMBR parameter. 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. or by using either the Add Physical File Member (ADDPFM) command or the Change Physical File Member (CHGPFM) command. The RPG compiler is called to create program ARBR5 in library JONES by using the source member created by the SQL precompiler. Text for a database source member can be added or changed by using the Start Source Entry Utility (STRSEU) command. If the source file is an inline file or a device file. QSQLTEMP: The source file QSQLTEMP will be used. ’description’: Specify no more than 50 characters of text. TEXT Specifies text that briefly describes the program and its function. The possible library values are: QTEMP: The library QTEMP will be used. If no library is specified as the current library for the job.I OBJ( library-name/ REXX: B. If the file is not found in any library in the library list.I Pgm: B. More information on this parameter is in Appendix A.I *CURLIB/ Exec object-name ) CRTSQLRPGI 744 DB2 UDB for AS/400 SQL Programming V4R4 .CRTSQLRPG | | | | | | | | | | | | | | | | | 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. *BLANK: Text is not specified. the QGPL library will be used. *SRCMBRTXT: The text is taken from the source file member being used to create the RPG program. source-file-name: Specify the name of the source file to contain the output source member. DB2 UDB for AS/400 CL Command Descriptions 745 .CRTSQLRPGI *LIBL/ SRCFILE( *CURLIB/ library-name/ QRPGLESRC source-file-name ) (1) *OBJ source-file-member-name SRCMBR( ) OPTION( OPTION Details ) TGTRLS( *CURRENT *PRV VxRxMx ) OBJTYPE( *PGM *MODULE *SRVPGM ) *LIBL/ INCFILE( *CURLIB/ library-name/ *SRCFILE source-file-name ) COMMIT( *UR *CHG *ALL *RS *CS *NONE *NC *RR CLOSQLCSR( ) *ENDACTGRP *ENDMOD ) ALWCPYDTA( *OPTIMIZE *YES *NO ) ALWBLK( *ALLREAD *NONE *READ ) DLYPRP( *NO *YES ) GENLVL( 10 severity-level ) Appendix D. ' '.' '.' '-' ' ' *BLANK DATFMT( ) DATSEP( ) TIMFMT( *HMS *USA *ISO *EUR *JIS ) TIMSEP( *JOB ':' '.CRTSQLRPGI *JOB *USA *ISO *EUR *JIS *MDY *DMY *YMD *JUL *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 ) DYNDFTCOL( *NO *YES ) *OBJLIB/ SQLPKG( library-name/ *OBJ package-name ) SQLPATH( *NAMING *LIBL ) collection-name 746 DB2 UDB for AS/400 SQL Programming V4R4 . DB2 UDB for AS/400 CL Command Descriptions 747 .CRTSQLRPGI *NOFLAG *FLAG *NONE *ANS SAAFLAG( ) FLAGSTD( ) DBGVIEW( *NONE *SOURCE ) USRPRF( *NAMING *OWNER *USER ) DYNUSRPRF( *USER *OWNER ) SRTSEQ( *JOB *JOBRUN *LANGIDUNQ *LANGIDSHR *HEX *LIBL/ table-name *CURLIB/ library-name/ ) LANGID( *JOB *JOBRUN language-identifier ) OUTPUT( *NONE *PRINT ) *LIBL/ PRTFILE( *CURLIB/ library-name/ QSYSPRT printer-file-name ) QTEMP/ TOSRCFILE( *LIBL/ *CURLIB/ library-name/ QSQLTEMP1 source-file-name ) TEXT( *SRCMBRTXT *BLANK 'description' ) OPTION Details: Appendix D. QRPGLESRC: If the source file name is not specified. *CURLIB: The current library for the job is searched. 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. If no library is specified as the current library for the job. or create a service program. *CURLIB: The new object is created in the current library for the job. and then optionally calls the ILE RPG compiler to create a module. The name of the source file can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. Parameters OBJ Specifies the qualified name of the object being created. object-name: Specify the name of the object being created. 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. All parameters preceding this point can be specified in positional form. the QGPL library is used. source-file-name: Specify the name of the source file that contains the RPG source. library-name: Specify the name of the library to be searched. SRCMBR Specifies the name of the source file member that contains the RPG source. produces a temporary source member.CRTSQLRPGI *XREF *NOXREF *GEN *NOGEN *JOB *SYSVAL *PERIOD *COMMA *SYS *SQL *NOSECLVL *SECLVL *NOSEQSRC *SEQSRC *NOEVENTF *EVENTF *OPTLOB *NOOPTLOB Notes: 1. create a program. SRCFILE Specifies the qualified name of the source file that contains the RPG source with SQL statements. the IBM-supplied source file QRPGLESRC contains the RPG source. This parameter is specified only if the source file name in the SRCFILE 748 DB2 UDB for AS/400 SQL Programming V4R4 . 4.) followed by a blank( ). any numeric constants in lists (such as in the SELECT clause or the VALUES clause) must be separated by a comma (.CRTSQLRPGI parameter is a database file.23. and a module. program. For example.4. 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.1) is equivalent to VALUES(1. 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.23. Note: Any numeric constants in lists (such as in the SELECT clause or the VALUES clause) must be separated by a comma (.23. *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.). 4. VALUES(1.1) where the decimal point is a period (. the PGM name specified on the OBJ parameter is used. service program. DB2 UDB for AS/400 CL Command Descriptions 749 . Element 2: Program Creation Options *GEN: The precompiler creates the object that is specified by the OBJTYPE parameter. For example. *SYSVAL: The value used as the decimal point for numeric constants in SQL statements is the QDECFMT system value. Element 4: Naming Convention Options Appendix D.23.2. 4. source-file-member-name: Specify the name of the member that contains the RPG source. 2.2. *PERIOD: The value used as the decimal point for numeric constants in SQL statements is a period (.1. *NOXREF: The precompiler does not cross-reference names. If this parameter is not specified.1) is equivalent to VALUES(1. or if two options conflict.). or SQL package is not created.). *COMMA: The value used as the decimal point for numeric constants in SQL statements is a comma (. Note: If QDECFMT specifies that the value used as the decimal point is a comma(. the last option specified is used. OPTION Specifies whether one or more of the following options are used when the RPG source is precompiled.1. VALUES(1.) followed by a blank ( ).1.1. 2.).). If an option is specified more than once. *NOGEN: The precompiler does not call the RPG compiler.1) in which the decimal point is a period (. no subsequent FETCH for that cursor can use a LOB locator for that column. This option is normally specified by CODE/400 on your behalf. *SQL must be specified as the naming convention.table-name). This option can cause performance to degrade. Element 7: Event File Creation *NOEVENTF: The compiler will not produce an Event File for use by CoOperative Development Environment/400 (CODE/400). 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. When creating a program on a remote database other than an AS/400 system.CRTSQLRPGI *SYS: The system naming convention (library-name/file-name) is used. *NOOPTLOB: There is no restriction on whether a column is retrieved into a LOB locator or into a LOB host variable. time and timestamp data types which are retrieved from externally-described files are to be processed as fixed-length character. time and timestamp data types which are retrieved from externally-described files are to be processed using the native RPG language. *SECLVL: Second-level text with replacement data is added for all messages on the listing. If the first FETCH places the LOB column into a LOB host variable. *SEQSRC: The source file member created into QSQLTEMP1 contains sequence numbers starting at 000001 and incremented by 000001. Element 8: Date Conversion *NOCVTDT: Date. 750 DB2 UDB for AS/400 SQL Programming V4R4 . *EVENTF: The compiler produces an event file for use by CoOperative Development Environment/400 (CODE/400). no subsequent FETCH for that cursor can fetch that LOB column into a LOB host variable. This option remains in effect until the cursor is closed. The event file will be created as a member in the file EVFEVENT in your source library. If the first FETCH uses a LOB locator to access a LOB column. | Element 9: Large Object Optimization for DRDA *OPTLOB: The first FETCH for a cursor determines how the cursor will be used for LOBs (Large Objects) on all subsequent FETCHes. *SQL: The SQL naming convention is used (collection-name. CODE/400 uses this file to offer error feedback integrated with the CODE/400 editor. Element 5: Second-Level Message Text Option *NOSECLVL: Second-level text descriptions are not added to the listing. *CVTDT: Date. *PRV: The object is to be used on the previous release with modification level 0 of the operating system. an SQL package is not created and you must issue the CRTSQLPKG command after the CRTPGM or CRTSRVPGM command has created the program. Note: If V2R3M5 is running on the system. 2. Valid values depend on the current version. modification level 0. service program. and they change with each new release. *PRV means the user intends to use the object on a system with V2R2M0 installed. When OBJTYPE(*PGM) or OBJTYPE(*SRVPGM) is specified and the RDB parameter is also specified. For example. and modification level. For example. *MODULE: The SQL precompiler issues the CRTRPGMOD command to create the module. In the examples given for the *CURRENT and *PRV values. Appendix D. *PGM: The SQL precompiler issues the CRTBNDRPG command to create the bound program. specify TGTRLS(V2R3M0) not TGTRLS(*CURRENT). *SRVPGM: The SQL precompiler issues the CRTRPGMOD and CRTSRVPGM commands to create the service program. *CURRENT means the user intends to use the object on a system with V2R3M5 installed. OBJTYPE Specifies the type of object being created. V2R3M0 is version 2. For example. only the SQL temporary source member is generated and a module. the format VxRxMx is used to specify the release. DB2 UDB for AS/400 CL Command Descriptions 751 . The user can also use the object on a system with any subsequent release of the operating system installed. if V2R3M5 is running on the user’s system. The object can be used on a system with the specified release or with any subsequent release of the operating system installed. Notes: 1. Rx is the release. *CURRENT: The object is to be used on the release of the operating system currently running on the user’s system. where Vx is the version. If you specify a release-level which is earlier than the earliest release level supported by this command. When OBJTYPE(*MODULE) is specified. if V2R3M5 is running on the system.CRTSQLRPGI TGTRLS Specifies the release of the operating system on which the user intends to use the object being created. release-level: Specify the release in the format VxRxMx. and Mx is the modification level. and SQL package are not created. If *NOGEN is specified. program. and when specifying the release-level value. The user can also use the object on a system with any subsequent release of the operating system installed. release. an error message is sent indicating the earliest supported release. release 3. the CRTSQLPKG command is issued by the SQL precompiler after the program has been created. and the object is to be used on a system with V2R3M0 installed. CALL. GRANT. *CS: Specifies the objects referred to in SQL ALTER. GRANT. Files referred to in the host language source are not affected by this option. DELETE. deleted. GRANT. deleted. DROP. *RR: Specifies the objects referred to in SQL ALTER. and REVOKE statements and the rows updated. the QGPL library is used. library-name: Specify the name of the library to be searched. CALL. Uncommitted changes in other jobs cannot be seen. *CHG or *UR: Specifies the objects referred to in SQL ALTER. and inserted are locked until the end of the unit of work (transaction). DROP. If no library is specified as the current library for the job. *NONE or *NC must be used. and inserted are locked until the end of the unit of work (transaction). COMMENT ON. SQL views. Uncommitted changes in other jobs cannot be seen. GRANT. and REVOKE statements and the rows updated. The name of the source file can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. All tables referred to in SELECT. deleted. and inserted are locked until the end of the unit of work (transaction). RENAME. LABEL ON. DROP. RENAME. RENAME. Uncommitted changes in other jobs can be seen. UPDATE. CALL. COMMENT ON. LABEL ON.CRTSQLRPGI INCFILE Specifies the qualified name of the source file that contains members included in the program with any SQL INCLUDE statement. but not updated. source-file-name: Specify the name of the source file that contains the source file members specified on any SQL INCLUDE statement. and INSERT statements are locked exclusively until the end of the unit of work (transaction). Uncommitted changes in other jobs can be seen. and REVOKE statements and the rows selected. *ALL or *RS: Specifies the objects referred to in SQL ALTER. *NONE or *NC cannot be specified. LABEL ON. CREATE. *CURLIB: The current library for the job is searched. DROP. and inserted are locked until the end of the unit of work (transaction). CALL. 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. If the SQL DROP COLLECTION statement is included in the program. Only SQL tables. CREATE. deleted. Uncommitted changes in other jobs cannot be seen. COMMENT ON. COMMIT Specifies whether SQL statements in the compiled unit are run under commitment control. COMMENT ON. and REVOKE statements and the rows selected. is locked until the next row is selected. 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. A row that is selected. LABEL ON. RENAME. CREATE. *SRCFILE: The qualified source file specified in the SRCFILE parameter contains the source file members specified on any SQL INCLUDE statement. CREATE. and SQL packages referred to in SQL statements are affected. updated. *NONE or *NC: Specifies that commitment control is not used. 752 DB2 UDB for AS/400 SQL Programming V4R4 . updated. SQL prepared statements are implicitly discarded. The decision is based on which method provides the best performance. *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. and LOCK TABLE locks are released when the activation group ends. 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. – Dynamic running of a positioned UPDATE or DELETE statement (for example. then a copy of the data is used only when it is necessary to run a query. Specifying *NONE: v Guarantees that the data retrieved is current. If a temporary copy of the data is required to perform the query. *ENDACTGRP: SQL cursors are closed. *NO: A copy of the data is not allowed. DB2 UDB for AS/400 CL Command Descriptions 753 . v Can improve the performance of almost all read-only cursors in programs. | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ALWCPYDTA Specifies whether a copy of the data can be used in a SELECT statement. and LOCK TABLE locks are released. and the extent to which blocking can be used for read-only cursors. COMMIT. ALWBLK Specifies whether the database manager can use record blocking. *ALLREAD: Rows are blocked for read-only cursors if *NONE or *CHG is specified on the COMMIT parameter. using EXECUTE IMMEDIATE). an error message is returned. *NONE: Rows are not blocked for retrieval of data for cursors. cannot be used to update a row in a cursor unless the DECLARE statement for the cursor includes the FOR UPDATE clause. or if COMMIT is *ALL or *RR. Appendix D. but limits queries in the following ways: – The Rollback (ROLLBACK) command. Specifying *ALLREAD: v Allows record blocking under commitment control level *CHG in addition to the blocking allowed for *READ. *ENDMOD: SQL cursors are closed and SQL prepared statements are implicitly discarded when the module is exited. SQL cursors are explicitly closed when you issue the CLOSE. or the ROLLBACK HOLD SQL statement does not reposition a read-only cursor when *ALLREAD is specified. SQL prepared statements are implicitly discarded. LOCK TABLE locks are released when the first SQL program on the call stack ends. a ROLLBACK statement in host languages. or ROLLBACK (without HOLD) SQL statements.CRTSQLRPGI CLOSQLCSR Specifies when SQL cursors are implicitly closed. If COMMIT is *CHG or *CS and ALWBLK is not *ALLREAD. CRTSQLRPGI | | | | | | | | | | | | | | | v May reduce the amount of time required to retrieve the first row of data for a query. GENLVL Specifies the severity level at which the create operation fails. EXECUTE. DATFMT Specifies the format used when accessing date result columns. EXECUTE. or DESCRIBE SQL statement. or DESCRIBE statement to ensure that the dynamic statement is valid. the specified value is used to determine whether the date is specified in a valid format. the access plan is revalidated. All output date fields are returned in the specified format. 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. EXECUTE. When the dynamic statement is prepared. For input date strings. When the dynamic statement is used in an OPEN or EXECUTE statement. Because the authority or the existence of objects referred to by the dynamic statement may change. If you specify *YES on this parameter. *NO: Dynamic statement validation is not delayed. If errors occur that have a severity level greater than this value. severity-level: Specify a value ranging from 0 through 40. the validation is completed and an access plan is built. *YES: Dynamic statement validation is delayed until the dynamic statement is used in an OPEN. DLYPRP Specifies whether the dynamic statement validation for a PREPARE statement is delayed until an OPEN. When the dynamic statement is used. v Can degrade the overall performance of a query that retrieves a large number of rows. which indicates that commitment control is not used. *READ: Records are blocked for read-only retrieval of data for cursors when: v *NONE is specified on the COMMIT parameter. or DESCRIBE statement is run. 10: The default severity level is 10. 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. Delaying validation improves performance by eliminating redundant validation. the access plan is validated. Note: If you specify *YES. 754 DB2 UDB for AS/400 SQL Programming V4R4 . you should check the SQLCODE and SQLSTATE after running an OPEN. the operation ends. Specifying *READ can improve the overall performance of queries that meet the above conditions and retrieve a large number of records. 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. you must still check the SQLCODE or SQLSTATE after issuing the OPEN or EXECUTE statement to ensure that the dynamic statement is still valid. ’: A comma (. Use the Display Job (DSPJOB) command to determine the current value for the job. ’-’: A dash (-) is used. or *JIS must be specified. *EUR.yyyy) is used. Use the Display Job (DSPJOB) command to determine the current date format for the job. *JOB: The format specified for the job is used. ’ ’: A blank ( ) is used. TIMFMT Specifies the format used when accessing time result columns. the specified value is used to determine whether the time is specified in a valid format. *YMD: The date format (yy/mm/dd) is used.mm. *ISO. or *JIS is always valid. DB2 UDB for AS/400 CL Command Descriptions 755 . *JUL: The Julian date format (yy/ddd) is used.) is used. *ISO: The International Organization for Standardization (ISO) date format (yyyy-mm-dd) is used. *JOB: The date separator specified for the job at precompile time is used. *EUR. *BLANK: A blank ( ) is used. *MDY: The date format (mm/dd/yy) is used. Appendix D. *EUR: The European date format (dd. *DMY. *DMY: The date format (dd/mm/yy) is used. or *JUL is specified on the DATFMT parameter. *YMD. *MDY. *ISO. ’. Note: This parameter applies only when *JOB. DATSEP Specifies the separator used when accessing date result columns. *JIS: The Japanese Industrial Standard date format (yyyy-mm-dd) is used. then *USA. *ISO. For input time strings.’: A period (.CRTSQLRPGI Note: An input date string that uses the format *USA.) is used. *EUR. ’/’: A slash (/) is used. *USA: The United States date format (mm/dd/yyyy) is used. ’. 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. Note: An input time string that uses the format *USA. An SQL package object is not 756 DB2 UDB for AS/400 SQL Programming V4R4 . or package is created.ss is used. *JIS: The Japanese Industrial Standard time format hh:mm:ss is used.) is used. service program. service program.CRTSQLRPGI If a relational database is specified on the RDB parameter and the database is on a system that is not another AS/400 system. REPLACE Specifies if a SQL module. CRTBNDRPG. *ISO: The International Organization for Standardization (ISO) time format hh. the time format must be *USA. *USA: The United States time format hh:mm xx is used. program. *EUR: The European time format hh. *NO: A new SQL module.mm. and CRTSQLPKG commands. Use the Display Job (DSPJOB) command to determine the current value for the job. program. Note: This parameter applies only when *HMS is specified on the TIMFMT parameter. *YES: A new SQL module. RDB Specifies the name of the relational database where the SQL package object is created. ’ ’: A blank ( ) is used.mm. *ISO. *BLANK: A blank ( ) is used. ’:’: A colon (:) is used. or package is not created if an SQL object of the same name and type already exists in the specified library. *HMS: The hh:mm:ss format is used. or package of the same name and type in the same library. ’. ’. *JIS. program. The SQL statements will access the local database. where xx is AM or PM. service program.ss is used. TIMSEP Specifies the separator used when accessing time result columns. program. *EUR. *LOCAL: The program is created as a distributed SQL program. The value of this parameter is passed to the CRTRPGMOD. any existing SQL object of the same name and type in the specified library is moved to QRPLOBJ. service program or package is created when there is an existing SQL module.’: A comma (.’: A period (. or *HMS with a time separator of a colon or period.) is used. *JOB: The time separator specified for the job at precompile time is used. CRTSRVPGM. *NONE: The naming convention defined on the OPTION parameter is used. RDBCNNMTH Specifies the semantics used for CONNECT statements. PASSWORD Specifies the password to be used on the remote system. password: Specify the password of the user name specified on the USER parameter. *NONE: No password is sent. When the name of the local relational database is specified. relational-database-name: Specify the name of the relational database where the new SQL package object is to be created. *DUW: CONNECT (Type 2) semantics are used to support distributed unit of work. This parameter is valid only if RDB is specified. Appendix D. USER(*CURRENT) must also be specified. Refer to the SQL Reference. Consecutive CONNECT statements result in the previous connection being disconnected before a new connection is established. Consecutive CONNECT statements to additional relational databases do not result in disconnection of previous connections.CRTSQLRPGI created as part of the precompile process. The SQL statements will access the local database. This parameter is valid only when RDB is specified. This parameter applies only to static SQL statements. *CURRENT: The user profile under which the current job is running is used. DB2 UDB for AS/400 CL Command Descriptions 757 . SC41-3612 book for more information. *RUW: CONNECT (Type 1) semantics are used to support remote unit of work. The program object is not a distributed program and the Create Structured Query Language Package (CRTSQLPKG) command cannot be used. This value is used instead of the naming convention specified on the OPTION parameter. the program created is still a distributed SQL program. views. indexes. collection-name: Specify the name of the collection identifier. and SQL packages. | | | DYNDFTCOL Specifies whether the default collection name specified for the DFTRDBCOL parameter is also used for dynamic statements. USER Specifies the user name sent to the remote system when starting the conversation. *NONE: An SQL package object is not created. If this value is specified. The Create Structured Query Language Package (CRTSQLPKG) command can be used. DFTRDBCOL Specifies the collection name used for the unqualified names of tables. user-name: Specify the user name being used for the application server job. CRTSQLRPGI | | | | | | | *NO: Do not use the value specified on the DFTRDBCOL parameter for unqualified names of tables. views. ″QSYS2″. the path used is *LIBL. collection-name: Specify a list of one or more collection names. *LIBL: The path used is the library list at runtime. indexes. This parameter flags SQL statements to verify whether they conform to IBM SQL syntax. and SQL packages for dynamic SQL statements. SAAFLAG Specifies the IBM SQL flagging function. the collection-name takes the place of userid. the current library list at runtime. library-name: Specify the name of the library where the package is created. views. For *SYS naming. and user defined types in static SQL statements. *FLAG: The precompiler checks to see whether SQL statements conform to IBM SQL syntax. the path used is ″QSYS″. If a collection-name is specified on the DFTRDBCOL parameter. SQLPKG Specifies the qualified name of the SQL package created on the relational database specified on the RDB parameter of this command. A maximum of 43 individual collections may be specified. The naming convention specified on the OPTION parameter is used. | | | | | | | | | | | | SQLPATH Specifies the path to be used to find procedures. *NAMING: The path used depends on the naming convention specified on the OPTION parameter. For *SQL naming. *NOFLAG: The precompiler does not check to see whether SQL statements conform to IBM SQL syntax. *OBJ: The name of the SQL package is the same as the object name specified on the OBJ parameter. indexes. and SQL packages in dynamic SQL statements. ″userid″. SC26–3255–00. no more than 8 characters can be specified. where ″userid″ is the value of the USER special register. If the remote system is not an AS/400 system. package-name: Specify the name of the SQL package. 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. *YES: The collection name specified on the DFTRDBCOL parameter will be used for the unqualified names of the tables. More information about IBM SQL syntax found in IBM database products can be found in the DRDA IBM SQL Reference. functions. 758 DB2 UDB for AS/400 SQL Programming V4R4 . USRPRF Specifies the user profile that is used when the compiled program object is run. If the naming convention is *SQL.CRTSQLRPGI FLAGSTD Specifies the American National Standards Institute (ANSI) flagging function. *NAMING: The user profile is determined by the naming convention. including the authority that the program object has for each object in static SQL statements. This parameter flags SQL statements to verify whether they conform to the following standards. *USER: The profile of the user running the program object is used. dynamic SQL statements run under the profile of the program’s owner. USRPRF(*USER) is used. USRPRF(*OWNER) is used. dynamic SQL statements run under the profile of the SQL package’s user. SRTSEQ Specifies the sort sequence table to be used for string comparisons in SQL statements. For distributed. *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. If the naming convention is *SYS. For distributed. *NONE: The source view will not be generated. Appendix D. dynamic SQL statements run under the profile of the SQL package’s owner. DYNUSRPRF Specifies the user profile to be used for dynamic SQL statements.135-1992 entry ISO 9075-1992 entry FIPS 127. *SOURCE: The SQL precompiler will provide the source views for the root and if necessary. The profile of either the program owner or the program user is used to control which objects can be used by the program object. SQL INCLUDE statements. dynamic SQL statements run under the user of the program’s user. *OWNER: The user profiles of both the program owner and the program user are used when the program is run. 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.2 entry *NONE: The precompiler does not check to see whether SQL statements conform to ANSI standards. ANSI X3. DB2 UDB for AS/400 CL Command Descriptions 759 . *OWNER: For local. *USER: For local. A view will be provided which contains the statements generated by the precompiler. *LANGIDUNQ: The unique-weight sort table for the language specified on the LANGID parameter is used. library-name: Specify the name of the library to be searched. the QGPL library is used. *CURLIB: The current library for the job is searched. library-name: Specify the name of the library to be searched. *NONE: The precompiler listing is not generated. The name of the printer file can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. *JOBRUN: The SRTSEQ value for the job is retrieved when the program is run.CRTSQLRPGI *JOB: The SRTSEQ value for the job is retrieved during the precompile. *CURLIB: The current library for the job is searched. SRTSEQ(*JOBRUN) is valid only when LANGID(*JOBRUN) is also specified. For distributed applications. LANGID Specifies the language identifier to be used when SRTSEQ(*LANGIDUNQ) or SRTSEQ(*LANGIDSHR) is specified. The hexadecimal values of the characters are used to determine the sort sequence. *JOBRUN: The LANGID value for the job is retrieved when the program is run. LANGID(*JOBRUN) is valid only when SRTSEQ(*JOBRUN) is also specified. *JOB: The LANGID value for the job is retrieved during the precompile. For distributed applications. 760 DB2 UDB for AS/400 SQL Programming V4R4 . If no library is specified as the current library for the job. The name of the sort sequence table can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. OUTPUT Specifies whether the precompiler listing is generated. The file must have a minimum length of 132 bytes. *LANGIDSHR: The sort sequence table uses the same weight for multiple characters. If a file with a record length of less than 132 bytes is specified. and is the shared-weight sort sequence table associated with the language specified on the LANGID parameter. If no library is specified as the current library for the job. the QGPL library is used. *HEX: A sort sequence table is not used. *PRINT: The precompiler listing is generated. table-name: Specify the name of the sort sequence table to be used. language-identifier: Specify a language identifier. information is lost. PRTFILE Specifies the qualified name of the printer device file to which the precompiler printout is directed. it will be created. Appendix D. ’description’: Specify no more than 50 characters of text. TEXT Specifies the text that briefly describes the function. The possible library values are: QTEMP: The library QTEMP will be used. The output member will have the same name as the name that is specified for the SRCMBR parameter. Text can be added or changed for a database source member by using the Start Source Entry Utility (STRSEU) command. If the source file is an inline file or a device file. source-file-name: Specify the name of the source file to contain the output source member. If the specified source file is not found. the text is blank. *CURLIB: The current library for the job will be used. ″Expanded Parameter Descriptions″ in the CL Reference book. the QGPL library will be used. or by using either the Add Physical File Member (ADDPFM) or Change Physical File Member (CHGPFM) command. *BLANK: Text is not specified. Example CRTSQLRPGI PAYROLL OBJTYPE(*PGM) TEXT('Payroll Program') This command runs the SQL precompiler which precompiles the source and stores the changed source in member PAYROLL in file QSQLTEMP1 in library QTEMP. QSQLTEMP1: The source file QSQLTEMP1 will be used. enclosed in apostrophes. *LIBL: The job’s library list is searched for the specified file. the file will be created in the current library. More information on this parameter is located in Appendix A. If the file is not found in any library in the library list. *SRCMBRTXT: The text is taken from the source file member being used to create the RPG program. If no library is specified as the current library for the job.CRTSQLRPGI QSYSPRT: If a file name is not specified. library-name: Specify the name of the library that is to contain the output source file. The ILE RPG compiler is called to create program PAYROLL in the current library by using the source member created by the SQL precompiler. | | | | | | | | | | | | | | | | | 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. DB2 UDB for AS/400 CL Command Descriptions 761 . printer-file-name: Specify the name of the printer device file to which the precompiler printout is directed. the precompiler printout is directed to the IBM-supplied printer file QSYSPRT. I PGM( *CURLIB/ library-name/ REXX: B.I Pgm: B.CRTSQLPKG CRTSQLPKG (Create Structured Query Language Package) Command Job: B.I *LIBL/ Exec program-name ) CRTSQLPKG (1) *PGM relational-database-name RDB( ) USER( *CURRENT user-name ) PASSWORD( *NONE password ) GENLVL( 10 severity-level ) REPLACE( *YES *NO ) DFTRDBCOL( *PGM *NONE collection-name ) *LIBL/ PRTFILE( *CURLIB/ library-name/ QSYSPRT printer-file-name ) OBJTYPE( *PGM *SRVPGM ) *ALL (2) MODULE( module-name ) TEXT( *PGMTXT *BLANK 'description' ) 762 DB2 UDB for AS/400 SQL Programming V4R4 . USER(*CURRENT) must also be specified. *CURLIB: The current library for the job is searched. user-name: Specify the user name being used for the application server job. PASSWORD Specifies the password to be used on the remote system. PLI. relational-database-name: Specify the name of the relational database where the SQL package is to be created. USER Specifies the user name sent to the remote system when starting the conversation. The program must be a distributed SQL program. RDB Specifies the name of the relational database where the SQL package is being created. *NONE: No password is sent. FTN. *CURRENT: The user name associated with the current job is used. Parameters PGM Specifies the qualified name of the program for which the SQL package is being created. the QGPL library is used. *PGM: The relational database name specified for the SQL program is used. CI. The name of the program can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. CBLI. Use the Work with Relational Database Directory Entry (WRKRDBDIRE) command to show the relational database names that are valid on this parameter.CRTSQLPKG Notes: 1. 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. or RPG or RPGI) command. A maximum of 256 modules may be specified. Appendix D. All parameters preceding this point can be specified in positional form. CBL. If this value is specified. The relational database name is specified on the RDB parameter of the distributed SQL program. program-name: Specify the name of the program for which the package is being created. A distributed SQL program is a program created by specifying the RDB parameter on a CRTSQLxxx (where xxx = C. 2. If no library is specified as the current library for the job. DB2 UDB for AS/400 CL Command Descriptions 763 . library-name: Specify the name of the library to be searched. a new SQL package is not created if the package already exists in the specified library. 764 DB2 UDB for AS/400 SQL Programming V4R4 . collection-name: Specify the collection name that is used for unqualified tables. GENLVL Specifies the maximum severity level allowed for errors detected during SQL package creation. QSYSPRT: If a file name is not specified. PRTFILE Specifies the qualified name of the printer device file to which the create SQL package error listing is directed. Valid values range from 0 through 40. If no library is specified as the current library for the job. *PGM: The collection name specified for the SQL program is used. library-name: Specify the name of the library to be searched. *CURLIB: The current library for the job is searched. More information on this parameter is in Appendix A. views. ″Expanded Parameter Descriptions″ in the CL Reference book. *NO: An existing SQL package of the same name is not replaced. REPLACE Specifies whether an existing package is being replaced with the new package. views. If no errors are detected during the creation of the SQL package. the QGPL library is used. views. *NONE: Unqualified names for tables.CRTSQLPKG password: Specify the password of the user name specified on the USER parameter. indexes. indexes. *YES: An existing SQL package of the same name is replaced by the new SQL package. and SQL packages. severity-level: Specify the maximum severity level. If errors occur at a level that exceeds the specified level. indexes. The default relational database collection name is specified on the DFTRDBCOL parameter of the distributed SQL program. This parameter applies only to static SQL statements in the package. the SQL package is not created. the create SQL package error listing is directed to the IBM-supplied printer file QSYSPRT. and SQL packages use the search conventions specified on the OPTION parameter of the CRTSQLxxx command used to create the program. and SQL packages. The name of the printer file can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. no listing is produced. 10: The default severity-level is 10. DFTRDBCOL Specifies the collection name to be used for unqualified names of tables. DB2 UDB for AS/400 CL Command Descriptions 765 . module-name: Specify the names of up to 256 modules in the program for which an SQL package is to be created. The SQL package is associated with the module of the bound program. *PGM: Create an SQL package from the program specified on the PGM parameter. Note: CRTSQLPKG can process programs that do not contain more than 1024 modules. If more than 256 modules exist that need to have an SQL package created. *PGMTXT: The text from the program for which the SQL package is being created is used.CRTSQLPKG printer-file-name: Specify the name of the printer device file to which the create SQL package error listing is directed. Appendix D. *BLANK: No text is specified. Duplicate module names in the same program are allowed. *ALL: An SQL package is created for each module in the program. MODULE Specifies a list of modules in a bound 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. multiple CRTSQLPKG commands must be used. Example CRTSQLPKG PAYROLL RDB(SYSTEMA) TEXT('Payroll Program') | This command creates an SQL package from the distributed SQL program PAYROLL on relational database SYSTEMA. *SRVPGM: Create an SQL package from the service program specified on the PGM parameter. an SQL package is created for the module. ’description’: Specify a maximum of 50 characters of text. OBJTYPE Specifies the type of program for which an SQL package is created. This command looks at each module in the program and if *ALL or the module name is specified on the MODULE parameter. If the module is created using SQL and the RDB parameter is specified on the precompile command. enclosed in apostrophes. processing continues to determine whether an SQL package should be created. TEXT Specifies text that briefly describes the SQL package and its function. I Pgm: B.CVTSQLCPP | | | | | | CVTSQLCPP (Convert Structured Query Language C++ Source) Command Job: B.I REXX: B.I *LIBL/ CVTSQLCPP SRCFILE( *CURLIB/ library-name/ source-file-name ) Exec | | | | SRCMBR( *OBJ source-file-member-name (1) ) *LIBL/ TOSRCFILE( *CURLIB/ library-name/ QSQLTEMP source-file-name ) | | OPTION( OPTION Details ) TGTRLS( *CURRENT VxRxMx ) | | INCFILE( *LIBL/ *CURLIB/ library-name/ *SRCFILE source-file-name ) | | COMMIT( *UR *CHG *ALL *RS *CS *NONE *NC *RR CLOSQLCSR( ) *ENDACTGRP *ENDMOD ) | | ALWCPYDTA( *OPTIMIZE *YES *NO ) ALWBLK( *ALLREAD *NONE *READ ) | | DLYPRP( *NO *YES ) GENLVL( 10 severity-level ) | 766 DB2 UDB for AS/400 SQL Programming V4R4 . DB2 UDB for AS/400 CL Command Descriptions 767 .' ' ' *BLANK ) | | | RDB( *LOCAL relational-database-name *NONE ) USER( *CURRENT user-name ) | | PASSWORD( *NONE password ) RDBCNNMTH( *DUW *RUW ) | | DFTRDBCOL( *NONE collection-name ) DYNDFTCOL( *NO *YES ) | | SQLPKG( *OBJLIB/ library-name/ *OBJ package-name ) | Appendix D.' '.' '.CVTSQLCPP | | MARGINS( *SRCFILE left-right *JOB *USA *ISO *EUR *JIS *MDY *DMY *YMD *JUL ) DATFMT( ) | | DATSEP( *JOB '/' '.' '-' ' ' *BLANK ) TIMFMT( *HMS *USA *ISO *EUR *JIS ) | | TIMSEP( *JOB ':' '. CVTSQLCPP | | SQLPATH( *NAMING *LIBL ) collection-name | | SAAFLAG( *NOFLAG *FLAG ) FLAGSTD( *NONE *ANS ) | | DBGVIEW( *NONE *SOURCE ) USRPRF( *NAMING *OWNER *USER ) | | DYNUSRPRF( *USER *OWNER ) | | SRTSEQ( *JOB *JOBRUN *LANGIDUNQ *LANGIDSHR *HEX *LIBL/ table-name *CURLIB/ library-name/ ) | | LANGID( *JOB *JOBRUN language-identifier ) OUTPUT( *NONE *PRINT ) | | PRTFILE( *LIBL/ *CURLIB/ library-name/ QSYSPRT printer-file-name ) | | TEXT( *SRCMBRTXT *BLANK 'description' ) | | OPTION Details: | 768 DB2 UDB for AS/400 SQL Programming V4R4 . CVTSQLCPP | | *XREF *NOXREF *JOB *SYSVAL *PERIOD *COMMA *SYS *SQL *NOSECLVL *SECLVL *NOCNULRQD *CNULRQD | | *NOEVENTF *EVENTF *OPTLOB *NOOPTLOB | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Notes: 1. All parameters preceding this point can be specified in positional form. 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 OS/400 compiler. 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 job’s 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 job’s 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. Appendix D. DB2 UDB for AS/400 CL Command Descriptions 769 CVTSQLCPP | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | 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. 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: 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. 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 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 3: 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 4: 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 5: NUL Required Options 770 DB2 UDB for AS/400 SQL Programming V4R4 CVTSQLCPP | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | *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 6: 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 7: Large Object Optimization for DRDA *OPTLOB: The first FETCH for a cursor determines how the cursor will be used for LOBs (Large Objects) on all subsequent FETCHes. This option remains in effect until the cursor is closed. If the first FETCH uses a LOB locator to access a LOB column, no subsequent FETCH for that cursor can fetch that LOB column into a LOB host variable. If the first FETCH places the LOB column into a LOB host variable, no subsequent FETCH for that cursor can use a LOB locator for that column. *NOOPTLOB: There is no restriction on whether a column is retrieved into a LOB locator or into a LOB host variable. This option can cause performance to degrade. 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 user’s 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). Appendix D. DB2 UDB for AS/400 CL Command Descriptions 771 CVTSQLCPP | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | 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 job’s 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 772 DB2 UDB for AS/400 SQL Programming V4R4 CVTSQLCPP | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | 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. 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. *YES: A copy of the data is used only when necessary. *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. *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. Appendix D. DB2 UDB for AS/400 CL Command Descriptions 773 CVTSQLCPP | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | – 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. *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. *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. 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. 774 DB2 UDB for AS/400 SQL Programming V4R4 CVTSQLCPP | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | 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. The margin default values are 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. Appendix D. DB2 UDB for AS/400 CL Command Descriptions 775 CVTSQLCPP | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | *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 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. 776 DB2 UDB for AS/400 SQL Programming V4R4 CVTSQLCPP | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | *BLANK: A blank ( ) is used. 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. *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. Appendix D. DB2 UDB for AS/400 CL Command Descriptions 777 CVTSQLCPP | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | collection-name: Specify the name of the collection identifier. This value is used instead of the naming convention specified on the OPTION parameter. DYNDFTCOL Specifies whether the default collection name specified for the DFTRDBCOL parameter is also used for dynamic statements. *NO: Do not use the value specified on the DFTRDBCOL parameter for unqualified names of tables, views, indexes, and SQL packages for dynamic SQL statements. The naming convention specified on the OPTION parameter is used. *YES: The collection name specified on the DFTRDBCOL parameter will be used for the unqualified names of the tables, views, indexes, and SQL packages in dynamic SQL statements. 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. SQLPATH Specifies the path to be used to find procedures, functions, and user defined types in static SQL statements. *NAMING: The path used depends on the naming convention specified on the OPTION parameter. For *SYS naming, the path used is *LIBL, the current library list at runtime. For *SQL naming, the path used is ″QSYS″, ″QSYS2″, ″userid″, where ″userid″ is the value of the USER special register. If a collection-name is specified on the DFTRDBCOL parameter, the collection-name takes the place of userid. *LIBL: The path used is the library list at runtime. collection-name: Specify a list of one or more collection names. A maximum of 43 individual collections may 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. 778 DB2 UDB for AS/400 SQL Programming V4R4 CVTSQLCPP | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | *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. *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 program’s user. Distributed dynamic SQL statements are run under the profile of the SQL package’s user. *OWNER: Local dynamic SQL statements are run under the profile of the program’s owner. Distributed dynamic SQL statements are run under the profile of the SQL package’s owner. SRTSEQ Specifies the sort sequence table to be used for string comparisons in SQL statements. Appendix D. DB2 UDB for AS/400 CL Command Descriptions 779 CVTSQLCPP | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | 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. The name of the table name can be qualified by one of the following library values: *LIBL: All libraries in the job’s 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: 780 DB2 UDB for AS/400 SQL Programming V4R4 CVTSQLCPP | | | | | | | | | | | | | | | | | | | | | | | | | | | | *LIBL: All libraries in the job’s 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. 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 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. *BLANK: Text is not specified. ’description’: Specify no more than 50 characters of text, enclosed in apostrophes. Example CVTSQLCPP SRCFILE(PAYROLL) SRCMBR(PAYROLL) TOSRCFILE(MYLIB/MYSRCFILE) TEXT('Payroll Program') 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. DLTSQLPKG (Delete Structured Query Language Package) Command Job: B,I Pgm: B,I REXX: B,I Exec DLTSQLPKG *LIBL/ SQLPKG( *CURLIB/ *USRLIBL/ *ALL/ *ALLUSR/ library-name/ SQL-package-name generic*-SQL-package name ) (1) Notes: 1. All parameters preceding this point can be specified in positional form. Appendix D. DB2 UDB for AS/400 CL Command Descriptions 781 DLTSQLPKG 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. 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 job’s 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 job’s 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 Note: A different library name, of the form QUSRVxRxMx, can be created by the user for each release that IBM supports. VxRxMx is the version, release, and modification level of the library. 782 DB2 UDB for AS/400 SQL Programming V4R4 DLTSQLPKG library-name: Specify the name of the library to be searched. SQL-package-name: Specify the name of the SQL package being deleted. generic*-SQL-package-name: Specify the generic name of the SQL package to be deleted. A generic name is a character string of one or more characters followed by an asterisk (*); for example, ABC*. If a generic name is specified, all SQL packages with names that begin with the generic name, and for which the user has authority, are deleted. If an asterisk is not included with the generic (prefix) name, the system assumes it to be the complete SQL package name. Example DLTSQLPKG SQLPKG(JONES) This command deletes the SQL package JONES. PRTSQLINF (Print Structured Query Language Information) Command Job: B,I Pgm: B,I OBJ( *CURLIB/ library-name/ REXX: B,I *LIBL/ Exec object-name ) PRTSQLINF (1) *PGM *SQLPKG *SRVPGM OBJTYPE( ) 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 job’s library list are searched until the first match is found. Appendix D. DB2 UDB for AS/400 CL Command Descriptions 783 PRTSQLINF *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. Example Example 1: PRTSQLINF Printing SQL Information PAYROLL This command will print information about the SQL statements contained in program PAYROLL. RUNSQLSTM (Run Structured Query Language Statement) Command Job: B,I Pgm: B,I REXX: B,I *LIBL/ RUNSQLSTM SRCFILE ( *CURLIB/ library-name/ source-file-name ) Exec (1) SRCMBR ( source-file-member-name ) *UR *CHG *ALL *RS *CS *NONE *NC *RR COMMIT ( ) NAMING ( *SYS *SQL ) PROCESS( *RUN *SYN ) ALWCPYDTA ( *OPTIMIZE *YES *NO ) ALWBLK ( *ALLREAD *NONE *READ ) 784 DB2 UDB for AS/400 SQL Programming V4R4 RUNSQLSTM 10 severity-level *JOB *USA *ISO *EUR *JIS *MDY *DMY *YMD *JUL ERRLVL ( ) DATFMT ( ) DATSEP ( *JOB '/' '.' ',' '-' ' ' *BLANK ) TIMFMT ( *HMS *USA *ISO *EUR *JIS ) 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 ) FLAGSTD ( *NONE *ANS ) SAAFLAG ( *NOFLAG *FLAG ) Appendix D. DB2 UDB for AS/400 CL Command Descriptions 785 RUNSQLSTM *LIBL/ PRTFILE ( *CURLIB/ library-name/ QSYSPRT printer-file-name ) SQL-procedure-parameters: *CURRENT VxRxMx *ENDACTGRP *ENDMOD TGTRLS ( ) CLOSQLCSR ( ) OUTPUT ( *NONE *PRINT ) DBGVIEW ( *NONE *STMT *LIST ) USRPRF ( *NAMING *OWNER *USER ) DYNUSRPRF ( *USER *OWNER ) 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 job’s 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. 786 DB2 UDB for AS/400 SQL Programming V4R4 DROP. LABEL ON.RUNSQLSTM SRCMBR Specifies the name of the source file member that contains the SQL statements to be run. NAMING Specifies the naming convention used for naming objects in SQL statements. ALWCPYDTA Specifies whether a copy of the data can be used in a SELECT statement. and INSERT statements are locked exclusively 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. LABEL ON. is locked until the next row is selected. and REVOKE statements and the rows updated. DROP. deleted. COMMENT ON. DROP. GRANT. Uncommitted changes in other jobs can be seen. CREATE. *RUN: Statement are syntax-checked and run. CALL. Uncommitted changes in other jobs cannot be seen. COMMENT ON. CALL. but not updated. COMMIT Specifies whether SQL statements in the source file are run under commitment control. COMMENT ON. DELETE. CALL. and REVOKE statements and the rows selected. and REVOKE statements and the rows selected. deleted. and inserted are locked until the end of the unit of work (transaction). GRANT. A row that is selected. RENAME. *ALL or *RS: Specifies the objects referred to in SQL ALTER. Uncommitted changes in other jobs cannot be seen. deleted. *CHG or *UR: Specifies the objects referred to in SQL ALTER. and inserted are locked until the end of the unit of work (transaction). LABEL ON.table-name) is used. and inserted are locked until the end of the unit of work (transaction). Uncommitted changes in other jobs cannot be seen. *NONE or *NC: Specifies that commitment control is not used. deleted. RENAME. COMMENT ON. and inserted are locked until the end of the unit of work (transaction). RENAME. *NONE or *NC cannot be specified. *RR: Specifies the objects referred to in SQL ALTER. UPDATE. LABEL ON. CALL. GRANT. updated. and REVOKE statements and the rows updated. CREATE. updated. *SQL: The SQL naming convention (collection-name. *SYN: Statements are syntax-checked only. Appendix D. RENAME. All tables referred to in SELECT. *SYS: The system naming convention (library-name/file-name) is used. If the SQL DROP COLLECTION statement is included in the program. PROCESS Specifies whether SQL statements in the source file member are executed or syntax-checked only. DB2 UDB for AS/400 CL Command Descriptions 787 . *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. CREATE. DROP. CREATE. GRANT. 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. but limits queries in the following ways: – The Rollback (ROLLBACK) command. Specifying *NONE: v Guarantees that the data retrieved is current. ALWBLK Specifies whether the database manager can use record blocking. *ALLREAD: Rows are blocked for read-only cursors if *NONE or *CHG is specified on the COMMIT parameter. or if COMMIT is *ALL or *RR. If temporary copy of the data is required to perform the query. then a copy of the data is used only when it is necessary to run a query. – Dynamic running of a positioned UPDATE or DELETE statement (for example. v Can improve the performance of almost all read-only cursors in programs. If COMMIT is *CHG or *CS and ALWBLK is not *ALLREAD. v Can degrade the overall performance of a query that retrieves a large number of rows. an error message is returned. 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. or the ROLLBACK HOLD SQL statement does not reposition a read-only cursor when *ALLREAD is specified. 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. cannot be used to update a row in a cursor unless the DECLARE statement for the cursor includes the FOR UPDATE clause. *YES: A copy of the data is used only when necessary. a ROLLBACK statement in host languages. and the extent to which blocking can be used for read-only cursors. The decision is based on which method provides the best performance. 788 DB2 UDB for AS/400 SQL Programming V4R4 . *NONE: Rows are not blocked for retrieval of data for cursors.RUNSQLSTM *OPTIMIZE: The system determines whether to use the data retrieved directly from the database or to use a copy of the data. v May reduce the amount of time required to retrieve the first row of data for a query. *NO: A copy of the data is not used. using EXECUTE IMMEDIATE). Specifying *READ can improve the overall performance of queries that meet the above conditions and retrieve a large number of records. Specifying *ALLREAD: v Allows record blocking under commitment control level *CHG in addition to the blocking allowed for *READ. which indicates that commitment control is not used. *READ: Records are blocked for read-only retrieval of data for cursors when: v *NONE is specified on the COMMIT parameter. ’-’: A dash (-) is used. *DMY. DB2 UDB for AS/400 CL Command Descriptions 789 .’: A comma (. For input date strings.mm. *ISO. *MDY. *YMD. *JIS: The Japanese Industrial Standard date format (yyyy-mm-dd) is used. DATFMT Specifies the format used when accessing date result columns. *DMY: The date format (dd/mm/yy) is used. Appendix D. *JUL: The Julian date format (yy/ddd) is used. severity-level: Specify the severity level to be used.) is used. Use the Display Job (DSPJOB) command to determine the current value for the job. the specified value is used to determine whether the date is specified in a valid format. ’. Note: This parameter applies only when *JOB. *EUR: The European date format (dd. ’/’: A slash (/) is used. *USA: The United States date format (mm/dd/yyyy) is used. Note: An input date string that uses the format *USA. based on the severity of the messages generated by the processing of the SQL statements. or *JIS is always valid. ’. DATSEP Specifies the separator used when accessing date result columns. If errors that are greater than the value specified on this parameter occur during processing. Use the Display Job (DSPJOB) command to determine the current date format for the job. no more statements are processed and the statements are rolled back if they are running under commitment control. *EUR. 10: Statement processing is stopped when error messages with a severity level greater than 10 are received.) is used. *JOB: The date separator specified for the job is used. *MDY: The date format (mm/dd/yy) is used.RUNSQLSTM ERRLVL Specifies whether the processing is successful. *ISO: The International Organization for Standardization (ISO) date format (yyyy-mm-dd) is used. *YMD: The date format (yy/mm/dd) is used. *JOB: The format specified for the job is used.’: A period (. or *JUL is specified on the DATFMT parameter.yyyy) is used. ’: A period (.) is used.) is used. *ISO: The International Organization for Standardization (ISO) time format hh. *EUR. *PERIOD: A period represents the decimal point. where xx is AM or PM. For input time strings.mm. Use the Display Job (DSPJOB) command to determine the current value for the job. ’ ’: A blank ( ) is used. *BLANK: A blank ( ) is used. *BLANK: A blank ( ) is used. ’. ’.mm. *USA: The United States time format hh:mm xx is used. ’:’: A colon (:) is used. Note: This parameter applies only when *HMS is specified on the TIMFMT parameter. *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.ss is used.RUNSQLSTM ’ ’: A blank ( ) is used. *HMS: The hh:mm:ss format is used. *JOB: The time separator specified for the job is used.ss is used. *ISO. *EUR: The European time format hh. *SYSVAL: The QDECFMT system value is used as the decimal point. the specified value is used to determine whether the time is specified in a valid format. DECMPT Specifies the decimal point value used for numeric constants in SQL statements. 790 DB2 UDB for AS/400 SQL Programming V4R4 . or *JIS is always valid. SRTSEQ Specifies the sort sequence table to be used for string comparisons in SQL statements.’: A comma (. *COMMA: A comma represents the decimal point. *JIS: The Japanese Industrial Standard time format hh:mm:ss is used. Note: An input date string that uses the format *USA. TIMSEP Specifies the separator used when accessing time result columns. TIMFMT Specifies the format used when accessing time result columns. *ANS: The SQL statements are checked to determine whether they conform to ANSI standards. *JOB: The LANGID value for the job is retrieved during the precompile. *HEX: A sort sequence table is not used. collection-name: Specify the name of the collection identifier. views. *LANGIDUNQ: The unique-weight sort table for the language specified on the LANGID parameter is used. and is the shared-weight sort sequence table associated with the language specified on the LANGID parameter. DB2 UDB for AS/400 CL Command Descriptions 791 . *CURLIB: The current library for the job is searched. language-identifier: Specify a language identifier. *NONE: The naming convention defined on the OPTION parameter is used. This parameter flags SQL statements to verify whether they conform to the following standards.RUNSQLSTM *JOB: The LANGID value for the job is retrieved. This parameter flags SQL statements Appendix D. and SQL packages. DFTRDBCOL Specifies the collection name used for the unqualified names of tables. LANGID Specifies the language identifier to be used when SRTSEQ(*LANGIDUNQ) or SRTSEQ(*LANGIDSHR) is specified. *LANGIDSHR: The sort sequence table uses the same weight for multiple characters. the QGPL library is used.135-1992 entry ISO 9075-1992 entry FIPS 127. indexes. This value is used instead of the naming convention specified on the OPTION parameter.2 entry *NONE: The SQL statements are not checked to determine whether they conform to ANSI standards. The hexadecimal values of the characters are used to determine the sort sequence. library-name: Specify the name of the library to be searched. This parameter applies only to static SQL statements. FLAGSTD Specifies the American National Standards Institute (ANSI) flagging function. table-name: Specify the name of the sort sequence table to be used. The name of the table name can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. ANSI X3. SAAFLAG Specifies the IBM SQL flagging function. If no library is specified as the current library for the job. 792 DB2 UDB for AS/400 SQL Programming V4R4 . if V2R3M5 is running on the system. *CURRENT The object is to be used on the release of the operating system currently running on the user’s system. The user can also use the object on a system with any subsequent release of the operating system installed. If no library is specified as the current library for the job. where Vx is the version. The name of the printer file can be qualified by one of hte following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. The parameters are used during the creation of the program object associated with the SQL procedure. *CURLIB: The current library for the job is searched. and the object is to be used on a system with V2R3M0 installed. modification level 0. Note: If V2R3M5 is running on the system. specify TGTRLS(V2R3M0) not TGRRLS(*CURRENT). printer-file-name: Specify the name of the printer device file to which the RUNSQLSTM printout is directed. the QGPL library is used. SC26-3255-00. *FLAG: The SQL statements are checked to determine whether they conform to IBM SQL syntax. TGTRLS Specifies the release of the operating system on which the user intends to use the object being created.RUNSQLSTM 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. *NOFLAG: The SQL statements are not checked to determine whether they conform to IBM SQL syntax. In the examples given for the *CURRENT value. If a file with a record length of less than 132 bytes is specified. information is lost. release 3. QSYSPRT: If a file name is not specified. The file must have a minimum length of 132 bytes. *CURRENT means the user intends to use the object on a system with V2R3M5 installed. Parameters for SQL procedures The parameters listed below only apply to statements within the source file that create SQL procedures. and when specifying the release-level value. the format VxRxMx is used to specify the release. PRTFILE Specifies the qualified name of the printer device file to which the RUNSQLSTM printout is directed. For example. and Mx is the modification level. library-name: Specify the name of the library to be searched. the RUNSQLSTM printout is directed to the IBM-supplied printer file QSYSPRT. V2R3M0 is version 2. Rx is the release. For example. CLOSQLCSR Specifies when SQL cursors are implicitly closed. ENDMOD: SQL cursors are closed and SQL prepared statements are implicitly discarded when the module is exited. If you specify a release-level which is earlier than the earliest release level supported by this command. *STMT: Allows the compiled module to be debugged using program statement numbers and symbolic identifiers. release. SQL prepared statements are implicitly discarded. Appendix D. and they change with each new release. including the authority that the program object has for each object in static SQL statements. an error message is sent indicating the earliest supported release. *LIST: Generates the listing view for debugging the compiled module object. OUTPUT Specifies whether the precompiler listing is generated. The profile of either the program owner or the program user is used to control which objects can be used by the program object. DB2 UDB for AS/400 CL Command Descriptions 793 . USRPRF(*OWNER) is used. *OWNER: The user profiles of both the program owner and the program user are used when the program is run. USRPRF(*USER) is used. *ENDACTGRP: SQL cursors are closed and SQL prepared statements are implicitly discarded. *NAMING: The user profile is determined by the naming convention. The object can be used on a system with the specified release or with any subsequent release of the operating system installed. and modification level. *PRINT: The precompiler listing is generated. DBGVIEW Specifies the type of source debug information to be provided by the SQL precompiler. If the naming convention is *SYS. If the naming convention is *SQL. *USER: The profile of the user running the program object is used. or ROLLBACK (without HOLD) SQL statements. DYNUSRPRF Specifies the user profile to be used for dynamic SQL statements. LOCK TABLE locks are released when the first SQL program on the call stack ends. SQL cursors are explicitly closed when you issue the CLOSE.RUNSQLSTM release-level: Specify the release in the format VxRxMx. and LOCK TABLE locks are released. Valid values depend on the current version. *NONE: The source view will not be generated. USRPRF Specifies the user profile that is used when the compiled program object is run. *NONE: The precompiler listing is not generated. COMMIT. 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. you should check the SQLCODE and SQLSTATE after running an OPEN. *NO: Dynamic statement validation is not delayed. dynamic SQL statements run under the profile of the SQL package’s user. EXECUTE. dynamic SQL statements run under the profile of the SQL package’s owner. EXECUTE. the validation is completed and an access plan is built. or DESCRIBE SQL statement. Delaying validation improves performance by eliminating redundant validation. Because the authority or the existence of objects referred to by the dynamic statement may change. If you specify *YES on this parameter. EXECUTE. When the dynamic statement is used in an OPEN or EXECUTE statement. Example RUNSQLSTM SRCFILE(MYLIB/MYFILE) SRCMBR(MYMBR) This command processes the SQL statements in member MYMBR found in file MYFILE in library MYLIB. When the dynamic statement is used. dynamic SQL statements run under the user of the program’s user. For distributed. For distributed. you must still check the SQLCODE or SQLSTATE after issuing the OPEN or EXECUTE statement to ensure that the dynamic statement is still valid. STRSQL (Start Structured Query Language) Command Job: I Pgm: I REXX: I Exec *SYS *SQL STRSQL *NC *NONE *CHG *UR *CS *RS *ALL *RR NAMING( ) ) COMMIT( 794 DB2 UDB for AS/400 SQL Programming V4R4 .RUNSQLSTM *USER: For local. dynamic SQL statements run under the profile of the program’s owner. When the dynamic statement is prepared. the access plan is revalidated. Note: If you specify *YES. DLYPRP Specifies whether the dynamic statement validation for a PREPARE statement is delayed until an OPEN. *YES: Dynamic statement validation is delayed until the dynamic statement is used in an OPEN. the access plan is validated. or DESCRIBE statement to ensure that the dynamic statement is valid. *OWNER: For local. or DESCRIBE statement is run. ’ ’-’ ’ ’ ) TIMFMT( *HMS *USA *ISO *EUR *JIS ) (3) TIMSEP( *JOB *BLANK ’:’ ’.STRSQL *RUN *VLD *SYN *LIBL *CURLIB *USRLIBL *ALL *ALLUSR library-name PROCESS( ) LIBOPT( ) (1) *ALL *SQL *ALWAYS *FORWARD LISTTYPE( ) REFRESH( ) ALWCPYDTA( *YES *OPTIMIZE *NO ) DATFMT( *JOB *USA *ISO *EUR *JIS *MDY *DMY *YMD *JUL ) (2) DATSEP( *JOB *BLANK ’/’ ’.’ ’. DB2 UDB for AS/400 CL Command Descriptions 795 .’ ’ ’ ) DECPNT( *SYSVAL *PERIOD *COMMA *JOB ) (4) PGMLNG( *NONE *C *CBL *PLI *RPG *FTN ) (5) SQLSTRDLM( (6) *QUOTESQL *APOSTSQL ) Appendix D.’ ’. *NONE or *NC cannot be specified. 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. CREATE. and REVOKE statements and the rows updated. 3. and REVOKE statements and 796 DB2 UDB for AS/400 SQL Programming V4R4 . edit. LABEL ON. Parameters COMMIT Specifies whether the SQL statements are run under commitment control. DATSEP is only valid when *MDY. CALL. 4. PGMLNG and SQLSTRDLM are valid only when PROCESS(*SYN) is specified. COMMENT ON. PGMLNG and SQLSTRDLM are valid only when PROCESS(*SYN) is specified. *CS: Specifies the objects referred to in SQL ALTER.STRSQL *JOB *JOBRUN *LANGIDUNQ *LANGIDSHR *HEX *LIBL/ table-name *CURLIB/ library-name/ SRTSEQ( ) LANGID( *JOB *JOBRUN language-ID ) Notes: 1. and inserted are locked until the end of the unit of work (transaction). COMMENT ON. Messages received during the running of the program are shown on this display. deleted. 2. The program starts the statement entry of the interactive SQL program which immediately shows the Enter SQL Statements display. GRANT. If the SQL DROP COLLECTION statement is included in the program. Uncommitted changes in other jobs can be seen. LABEL ON. *CHG or *UR: Specifies the objects referred to in SQL ALTER. TIMSEP is only valid when TIMFMT(*HMS) is specified. This display allows the user to build. and run an SQL statement in an interactive environment. RENAME. CALL. All parameters preceding this point can be specified in positional form. *NONE or *NC: Specifies that commitment control is not used. Purpose The Start Structured Query Language (STRSQL) command starts the interactive Structured Query Language (SQL) program. DROP. RENAME. SQLSTRDLM is valid only when PGMLNG(*CBL) is specified. *NONE or *NC must be used. DROP. *YMD. *DMY. CREATE. or *JUL is specified on the DATFMT parameter. 6. GRANT. enter. 5. Uncommitted changes in other jobs can be seen. updated. DROP.table-name) is used. and inserted are locked until the end of the unit of work (transaction). *RUN: The statements are syntax checked. data checked. LABEL ON. *SYN: The statements are syntax checked only. GRANT. but not updated. PLI. *ALLUSR: All user libraries are searched. CBL.STRSQL the rows updated. COMMENT ON. CBLI. deleted. F17. DROP. the QGPL library is used. RENAME. All tables referred to in SELECT. PROCESS Specifies the values used to process the SQL statements. *USRLIBL: Only the libraries in the user portion of the job’s library list are searched. *ALL: All libraries in the system. RENAME. CALL. DELETE. including QSYS. *CURLIB: The current library for the job is searched. are searched. deleted. *SYS: The system naming convention (library-name/file-name) is used. and REVOKE statements and the rows selected. LABEL ON. *VLD: The statements are syntax checked and data checked. F16. Uncommitted changes in other jobs cannot be seen. FTN. and inserted are locked until the end of the unit of work (transaction). but not run. *SQL: The SQL naming convention (collection-name. and inserted are locked until the end of the unit of work (transaction). Uncommitted changes in other jobs cannot be seen. RPG or RPGI) is *CHG. updated. and then run. *RR: Specifies the objects referred to in SQL ALTER. or F18 function key is pressed. CALL. 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 Appendix D. CPPI. Uncommitted changes in other jobs cannot be seen. DB2 UDB for AS/400 CL Command Descriptions 797 . GRANT. Note: The default for this parameter for the CRTSQLXXX commands (when XXX=CI. and REVOKE statements and the rows selected. is locked until the next row is selected. CREATE. deleted. UPDATE. and INSERT statements are locked exclusively until the end of the unit of work (transaction). LIBOPT Specifies which collections and libraries are used as a basis for building a collection list when the F4. If no library is specified as the current library for the job. CREATE. COMMENT ON. The name of the collection list can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. NAMING Specifies the naming convention used for naming objects in SQL statements. *ALL or *RS: Specifies the objects referred to in SQL ALTER. A row that is selected. When scrolling backward. of the form QUSRVxRxMx. If COMMIT(*ALL) is specified. a copy of the data already viewed is shown. *USA: The United States date format (mm/dd/yyyy) is used. *NO: A copy of the data is not allowed. these libraries are considered user libraries and are also searched: QDSNX QGPL QGPL38 QPFRDATA QRCL QS36F QUSER38 QUSRADSM QUSRBRM QUSRIJS QUSRINFSKR QUSRRDARS QUSRSYS QUSRVxRxMx Note: A different library name. F17. REFRESH Specifies when the display select output data is refreshed. If a temporary copy of the data is required to perform the query. 798 DB2 UDB for AS/400 SQL Programming V4R4 . *EUR: The European date format (dd. The determination is based on which will provide the best performance. *ALL: All objects are displayed. or F18 function key. library-name: Specify the name of the library to be searched. *JOB: The format specified on the job attribute DATFMT is used. release. SQL run time ignores the ALWCPYDTA value and uses current data. Therefore. *FORWARD: Data is refreshed only during forward scrolling to the end of the data for the first time. and modification level of the library. *ISO: The International Standards Organization date format (yyyy-mm-dd) is used. an error message is returned. *SQL: Only SQL-created objects are displayed. LISTTYPE Specifies the types of objects that are displayed with list support by pressing the F4.STRSQL Although the following Qxxx libraries are provided by IBM. VxRxMx is the version. can be created by the user for each release that IBM supports. DATFMT Specifies the date format used in SQL statements. *YES: A copy of the data is used when necessary.mm. F16. they typically contain user data that changes frequently. ALWCPYDTA Specifies whether a copy of the data can be used in a SELECT statement. *ALWAYS: Data is normally refreshed during forward and backward scrolling. *OPTIMIZE: The system determines whether to use the data retrieved from the database or to use a copy of the data.yyyy) is used. day. *BLANK: A blank ( ) is used. ’. *HMS: The Hour-Minute-Second time format (hh:mm:ss) is used. DATSEP Specifies the date separator used in SQL statements. *ISO: The International Standards Organization time format (hh.) is used. the current value is stored and used. *MDY: The month. ’ ’: A blank ( ) is used.ss) is used. and year date format (dd/mm/yy) is used. *USA: The United States time format (hh:mm xx. ’/’: A slash (/) is used. *JOB: The time separator specified on the job attribute is used. where xx is AM or PM) is used. *BLANK: A blank ( ) is used. *JUL: The Julian date format (yy/ddd) is used. Later changes to the job’s date separator are not detected by interactive SQL. ’-’: A dash (-) is used. month.’: A comma (. the current value is stored and used.ss) is used. and day date format (yy/mm/dd) is used. DB2 UDB for AS/400 CL Command Descriptions 799 . TIMSEP Specifies the time separator used in SQL statements. *JIS: The Japanese Industry Standard Christian Era time format (hh:mm:ss) is used. *YMD: The year. If the user specifies *JOB on a new interactive SQL session. Appendix D.STRSQL *JIS: The Japanese Industry Standard Christian Era date format (yyyy-mm-dd) is used. ’:’: A colon (:) is used. Later changes to the job’s time separator are not detected by interactive SQL. month. *JOB: The date separator specified on the job attribute is used. TIMFMT Specifies the time format used in SQL statements. ’.mm. If the user specifies *JOB on a new interactive SQL session. *EUR: The European time format (hh. and year date format (mm/dd/yy) is used. *DMY: The day.mm.) is used.’: A period (. DECPNT Specifies the kind of decimal point to use. If the user specifies *SYSVAL on a new interactive SQL session. *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. *CBL: Syntax checking is done according to the COBOL language syntax rules. SRTSEQ Specifies the sort sequence table to be used for string comparisons in SQL statements on the Enter SQL Statements display. ’ ’: A blank ( ) is used. *NONE: No specific language’s syntax check rules are used. ’. *SYSVAL: The decimal point is extracted from the system value. *QUOTESQL: A quotation mark represents the SQL string delimiter.STRSQL ’. To use this parameter.) is used. *PERIOD: A period represents the decimal point. PGMLNG Specifies which program language syntax rules to use. SQLSTRDLM Specifies the SQL string delimiter. *PLI: Syntax checking is done according to the PL/I language syntax rules. *COMMA: A comma represents the decimal point.’: A comma (. *FTN: Syntax checking is done according to the FORTRAN language syntax rules. *RPG: Syntax checking is done according to the RPG language syntax rules. Use of this parameter requires using the COBOL (*CBL) character set. *JOB: The SRTSEQ value for the job is retrieved. The supported languages are: *C: Syntax checking is done according to the C language syntax rules. Later changes to the system’s time separator are not detected by interactive SQL.’: A period (. 800 DB2 UDB for AS/400 SQL Programming V4R4 . the current value is stored and used. *SYN must be selected at the PROCESS parameter. *JOBRUN: The SRTSEQ value for the job is retrieved each time the user starts interactive SQL.) is used. *APOSTSQL: An apostrophe represents the SQL string delimiter. *JOB: The LANGID value for the job is retrieved. The decimal point is represented by a comma. The character set used by the syntax checker uses the COBOL language syntax rules. The SQL naming convention is used for this session. Appendix D. and the SQL string delimiter is represented by an apostrophe. *HEX: A sort sequence table is not used. LANGID Specifies the language identifier to be used when SRTSEQ(*LANGIDUNQ) or SRTSEQ(*LANGIDSHR) is specified. *JOBRUN: The LANGID value for the job is retrieved each time interactive SQL is started. *CURLIB: The current library for the job is searched. table-name: Specify the name of the sort sequence table to be used with the interactive SQL session. the QGPL library is used. DB2 UDB for AS/400 CL Command Descriptions 801 .STRSQL *LANGIDUNQ: The unique-weight sort table for the language specified on the LANGID parameter is used. If no library is specified as the current library for the job. The name of the table name can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. language-ID: Specify the language identifier to be used. library-name: Specify the name of the library to be searched. The hexadecimal values of the characters are used to determine the sort sequence. *LANGIDSHR: The shared-weight sort table for the language specified on the LANGID parameter is 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. STRSQL 802 DB2 UDB for AS/400 SQL Programming V4R4 . This appendix is intended to help those customers who are using the SQL C for AS/400 precompiler with other non-IBM C compilers. and prefix name are optional. Using the C for AS/400 and FORTRAN for AS/400 Precompilers This appendix contains the syntax diagrams for the C for AS/400 and FORTRAN for AS/400 precompilers. Coding SQL Statements in FORTRAN Applications” on page 837. Using external file descriptions You can use the C #pragma mapinc directive with the #include directive to include external file descriptions in your program. the precompiler ignores the directive and does not generate host variable structures. although these are no longer supported on the AS/400. The SQL C for AS/400 precompiler support is the same as the ILE C for AS/400 precompiler support with the exception of the information included in this appendix. If all of the required elements are not specified. DB2 UDB for AS/400 Sample Tables. When used with SQL. those created by the #pragma mapinc and #include directives are recognized. 1999 803 . Using the C for AS/400 Precompiler C for AS/400 is no longer a supported compiler for the AS/400 system. the structure declared using the typedef can be used. Another appendix. describes the unique application and coding requirements for embedding SQL statements in a FORTRAN/400 program. Unions declared using the typedef union created by the #pragma mapinc and #include directive cannot be used as host variables in SQL statements. you can code the following: © Copyright IBM Corp. Structures that contain the typedef structure cannot be used in SQL statements. The required elements are: v Include name v Externally described file name v Format name or a list of format names v Options v ″p z″ parameter The library name. Host variable data types The SQL C for AS/400 precompiler does not support the decimal data type. only a particular format of the #pragma mapinc directive is recognized by the SQL precompiler. union name.Appendix E. 1997. the members of the unions can be used. Access plans The SQL C for AS/400 precompiler generates access plan structures that are for use with non-ILE programs. “Appendix F. Although typedef statements coded by the user are not recognized by the precompiler. To retrieve the definition of the sample table DEPARTMENT described in Appendix A. CRTSQLC (Create Structured Query Language C) Command Job: B. By using the extended program model (EPM) routines. Note: DATE."CORPDATA/DEPARTMENT(*ALL)". see the ILE C for AS/400 Language Reference book. and ADMRDEPT. and TIMESTAMP columns generate character host variable definitions."p z") #include "dept" CORPDATA_DEPARTMENT_DEPARTMENT_both_t Dept_Structure. and TIMESTAMP column. MGRNO.I Pgm: B. and binary (with non-zero scale fields) are mapped to character fields in C. TIME. a date host variable can only compared against a DATE column or a character string which is a valid representation of a date. DEPTNAME.I *CURLIB/ Exec program-name ) CRTSQLC *LIBL/ SRCFILE( *CURLIB/ library-name/ QCSRC source-file-name ) (1) *PGM source-file-member-name SRCMBR( ) OPTION( OPTION Details ) TGTRLS( *CURRENT *PRV VxRxMx ) *LIBL/ INCFILE( *CURLIB/ library-name/ *SRCFILE source-file-name ) 804 DB2 UDB for AS/400 SQL Programming V4R4 .#pragma mapinc ("dept". For more information. For example. SQL will treat these fields as numeric. TIME. They are treated by SQL with the same comparison and assignment rules as a DATE. Although packed. These field names can be used as host variables in SQL statements."both".I PGM( library-name/ REXX: B. zoned. you can manipulate these fields to convert zoned and packed decimal data. A host structure named Dept_Structure is defined with the following elements: DEPTNO. Using the C for AS/400 and FORTRAN for AS/400 Precompilers 805 .' '.' ' ' *BLANK ) REPLACE( *YES *NO ) RDB( *NONE relational-database-name ) USER( *CURRENT user-name ) PASSWORD( *NONE password ) Appendix E.' '.COMMIT( *CHG *ALL *CS *NONE ) CLOSQLCSR( *ENDPGM *ENDSQL *ENDJOB ) ALWCPYDTA( *YES *OPTIMIZE *NO ) 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( *JOB '/' '.' '-' ' ' *BLANK ) TIMFMT( *HMS *USA *ISO *EUR *JIS ) TIMSEP( *JOB ':' '. RDBCNNMTH( *DUW *RUW ) DFTRDBCOL( *NONE collection-name ) *PGMLIB/ SQLPKG( library-name/ *PGM package-name ) SAAFLAG( *NOFLAG *FLAG ) FLAGSTD( *NONE *ANS ) *LIBL/ PRTFILE( *CURLIB/ library-name/ QSYSPRT printer-file-name ) SRTSEQ( *JOB *JOBRUN *LANGIDUNQ *LANGIDSHR *HEX *LIBL/ table-name *CURLIB/ library-name/ ) LANGID( *JOB *JOBRUN language-ID ) DYNUSRPRF( *USER *OWNER ) QTEMP/ TOSRCFILE *LIBL/ *CURLIB/ library-name/ QSQLTEMP source-file-name ) TEXT( *SRCMBRTXT *BLANK 'description' ) OPTION Details: 806 DB2 UDB for AS/400 SQL Programming V4R4 . Using the C for AS/400 and FORTRAN for AS/400 Precompilers 807 . The name of the source file can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found.*NOSRC *NOSOURCE *SOURCE *SRC *NOXREF *XREF *NOGEN *JOB *PERIOD *SYSVAL *COMMA *SYS *SQL *NOSECLVL *SECLVL *NODEBUG *DEBUG *NOCNULRQD *CNULRQD *NOLSTDBG *LSTDBG Notes: 1. library-name: Specify the name of the library to be searched. the IBM-supplied source file QCSRC contains the C source. produces a temporary source member. QCSRC: If the source file name is not specified. 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. All parameters preceding this point can be specified in positional form. the QGPL library is used. Parameters PGM Specifies the qualified name of the compiled program. If no library is specified as the current library for the job. library-name: Specify the name of the library where the compiled C program is created. Purpose The Create Structured Query Language C (CRTSQLC) command calls the Structured Query Language (SQL) precompiler which precompiles C source containing SQL statements. Appendix E. *CURLIB: The current library for the job is searched. If no library is specified as the current library for the job. 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. This CRTSQLC command is provided for use by other non-IBM C compilers. Note: The C for AS/400 Compiler is no longer supported. The supported IBM compiler is ILE C for AS/400 and the SQL precompiler command is CRTSQLCI. the QGPL library is used. Element 3: Program Creation Option *NOGEN: The precompiler does not call the C compiler. source-file-member-name: Specify the name of the member that contains the C source. *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.23. This parameter is specified only if the source file name in the SRCFILE parameter is a database file. SRCMBR Specifies the name of the source file member that contains the C source.1) in which the decimal point is a period. *XREF: The precompiler cross-references items in the program to the statement numbers in the program that refer to those items. the last option specified is used.23. Note: If QDECFMT specifies that the value used as the decimal point is a comma.4.1) is equivalent to VALUES(1. For example. *PERIOD: The value used as the decimal point for numeric constants in SQL statements is a period.source-file-name: Specify the name of the source file that contains the C source.1. *SYSVAL: The value used as the decimal point for numeric constants in SQL statements is the QDECFMT system value. Element 2: Cross-Reference Options *NOXREF: The precompiler does not cross-reference names. 808 DB2 UDB for AS/400 SQL Programming V4R4 . If this parameter is not specified. 4.2. If an option is specified more than once. VALUES(1. and a program and SQL package are not created.1. or if two options conflict. 2. 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. *SOURCE or *SRC: The precompiler produces a source listing consisting of C source input. 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. OPTION Specifies whether one or more of the following options are used when the C source is precompiled. the PGM name specified on the PGM parameter is used. Element 1: Source Listing Options *NOSOURCE or *NOSRC: A source printout is not produced by the precompiler unless errors are detected by the precompile or create package. This option is passed to the compiler and does not affect the SQL precompiler. *SECLVL: Second-level text with replacement data is added for all messages on the listing. Element 7: Debug Options *NODEBUG: Symbolic extended program model (EPM) debug information is not stored with the program. *CNULRQD: Output character and graphic host variables always contain the NUL-terminator. The event file will be created as a member in the file EVFEVENT in your source library.23. If there is not enough space for the NUL-terminator. When creating a program on a remote database other than an AS/400 system.1) where the decimal point is a period. 2. *SQL: The SQL naming convention is used (collection-name. Element 8: NUL Required Options *NOCNULRQD: For output character and graphic host variables. For example.23. Using the C for AS/400 and FORTRAN for AS/400 Precompilers 809 .1) is equivalent to VALUES(1. Element 9: Event File Creation *NOEVENTF: The compiler will not produce an event file for use by CoOperative Development Environment/400 (CODE/400). the data is truncated and the NUL-terminator is added. 4. CODE/400 uses this file to offer error feedback integrated with the CODE/400 editor. Input character and graphic host variables do not require a NUL-terminator. the NUL-terminator is not returned when the host variable is exactly the same length as the data. Appendix E. This option is passed to the compiler and does not affect the SQL precompiler. *SQL must be specified as the naming convention.table-name).2. *DEBUG: Symbolic EPM debug information is stored with the program. VALUES(1. Element 5: Naming Convention Options *SYS: The system naming convention (library-name/file-name) is used. Input character and graphic host variables require a NUL-terminator.4. *EVENTF: The compiler produces an event file for use by CoOperative Development Environment/400 (CODE/400). This option is normally specified by CODE/400 on your behalf.*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. Element 6: Second-Level Message Text Option *NOSECLVL: Second-level text descriptions are not added to the listing.1.1. and Mx is the modification level. and they change with each new release. For example. and when specifying the release-level value. and modification level. *SRCFILE: The qualified source file specified in the SRCFILE parameter contains the source file members specified on any SQL INCLUDE statement. If you specify a release-level which is earlier than the earliest release level supported by this command. The object can be used on a system with the specified release or with any subsequent release of the operating system installed. the QGPL library is used. Note: If V2R3M5 is running on the system. *CURRENT means the user intends to use the object on a system with V2R3M5 installed. an error message is sent indicating the earliest supported release. The user can also use the object on a system with any subsequent release of the operating system installed. *PRV means the user intends to use the object on a system with V2R2M0 installed. For example. and the object is to be used on a system with V2R3M0 installed. *CURRENT: The object is to be used on the release of the operating system currently running on the user’s system. release-level: Specify the release in the format VxRxMx. where Vx is the version. if V2R3M5 is running on the system. If no library is specified as the current library for the job. For example. Rx is the release. *PRV: The object is to be used on the previous release with modification level 0 of the operating system. release. release 3. library-name: Specify the name of the library to be searched. The user can also use the object on a system with any subsequent release of the operating system installed. *CURLIB: The current library for the job is searched. INCFILE Specifies the qualified name of the source file that contains members included in the program with any SQL INCLUDE statement. modification level 0. COMMIT Specifies whether SQL statements in the compiled program are run under 810 DB2 UDB for AS/400 SQL Programming V4R4 .TGTRLS Specifies the release of the operating system on which the user intends to use the object being created. Valid values depend on the current version. 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. specify TGTRLS(V2R3M0) not TGTRLS(*CURRENT). In the examples given for the *CURRENT and *PRV values. source-file-name: Specify the name of the source file that contains the source file members specified on any SQL INCLUDE statement. V2R3M0 is version 2. The name of the source file can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. the format VxRxMx is used to specify the release. if V2R3M5 is running on the user’s system. COMMENT ON. *ENDPGM: SQL cursors are closed and SQL prepared statements are discarded when the program ends. GRANT. *CHG: Specifies the objects referred to in SQL ALTER. GRANT. deleted. SQL cursors are closed. DROP. Uncommitted changes in other jobs cannot be seen. SQL cursors are left open. ALWCPYDTA Specifies whether a copy of the data can be used in a SELECT statement. LOCK TABLE locks are released when the first SQL program on the call stack ends. *ALL: Specifies the objects referred to in SQL ALTER. SQL views. DROP. and LOCK TABLE locks are released when the first SQL program on the call stack ends. CLOSQLCSR Specifies when SQL cursors are implicitly closed. *ENDSQL: SQL cursors remain open between calls and can be fetched without running another SQL OPEN. SQL cursors are explicitly closed when you issue the CLOSE. If the SQL DROP COLLECTION statement is included in the program. LABEL ON. COMMIT. CREATE. *OPTIMIZE: The system determines whether to use the data retrieved directly from the database or to use a copy of the data. COMMENT ON. and LOCK TABLE locks are held when the first SQL program on the call stack ends. the program is treated as if *ENDPGM was specified. One of the programs higher on the call stack must have run at least one SQL statement. SQL prepared statements are discarded. and inserted are locked until the end of the unit of work (transaction). The programs higher on the call stack do not need to have run SQL statements. Only SQL tables. Uncommitted changes in other jobs cannot be seen. but not updated. CREATE. and REVOKE statements and the rows updated.commitment control. SQL prepared statements are implicitly discarded. and LOCK TABLE locks are released. The decision is based on which Appendix E. is locked until the next row is selected. *ENDJOB: SQL cursors remain open between calls and can be fetched without running another SQL OPEN. Using the C for AS/400 and FORTRAN for AS/400 Precompilers 811 . and inserted are locked until the end of the unit of work (transaction). If *ENDSQL is specified for a program that is the first SQL program called (the first SQL program on the call stack). Uncommitted changes in other jobs can be seen. updated. GRANT. CREATE. *NONE: Specifies that commitment control is not used. and REVOKE statements and the rows updated. deleted. and LOCK TABLE locks are released when the job ends. or ROLLBACK (without HOLD) SQL statements. LABEL ON. DROP. *NONE cannot be specified. SQL prepared statements are discarded. 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. SQL prepared statements are preserved. COMMENT ON. and REVOKE statements and the rows selected. and inserted are locked until the end of the unit of work (transaction). Files referred to in the host language source are not affected by this option. Uncommitted changes in other jobs can be seen. deleted. *NONE must be used. *CS: Specifies the objects referred to in SQL ALTER. SQL cursors are closed. LABEL ON. and SQL packages referred to in SQL statements are affected. A row that is selected. the access plan is validated. *NO: A copy of the data is not used. *ALLREAD: Rows are not blocked for retrieval of data for cursors. or if COMMIT is *ALL or *RR. *NO: Dynamic statement validation is not delayed. Delaying validation improves performance by eliminating redundant validation.method provides the best performance. When the dynamic 812 DB2 UDB for AS/400 SQL Programming V4R4 . v Can degrade the overall performance of a query that retrieves a large number of rows. *NONE: Rows are not blocked for retrieval of data for cursors. v May reduce the amount of time required to retrieve the first row of data for a query. then a copy of the data is used only when it is necessary to run a query. ALWBLK Specifies whether the database manager can use record blocking. v May reduce the amount of time required to retrieve the first row of data for a query. *READ: Records are blocked for read-only retrieval of data for cursors when: v *NONE is specified on the COMMIT parameter. If a temporary copy of the data is required to perform the query. DLYPRP Specifies whether the dynamic statement validation for a PREPARE statement is delayed until an OPEN. Specifying *NONE: v Guarantees that the data retrieved is current. 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. EXECUTE. Specifying *READ can improve the overall performance of queries that meet the above conditions and retrieve a large number of records. v Can degrade the overall performance of a query that retrieves a large number of rows. or DESCRIBE statement is run. an error message is returned. which indicates that commitment control is not used. 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. *YES: A copy of the data is used only when necessary. If COMMIT is *CHG or *CS and ALWBLK is not *ALLREAD. When the dynamic statement is prepared. Specifying *NONE: v Guarantees that the data retrieved is current. and the extent to which blocking can be used for read-only cursors. 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. *SRCFILE:The file member margin values that you specified on the SRCMBR parameter are used.statement is used in an OPEN or EXECUTE statement. EXECUTE. Using the C for AS/400 and FORTRAN for AS/400 Precompilers 813 . the operation ends. or DESCRIBE SQL statement. If you specify *YES on this parameter. MARGINS Specifies the part of the precompiler input record that contains source text. severity-level: Specify a value ranging from 0 through 40. *YES: Dynamic statement validation is delayed until the dynamic statement is used in an OPEN. All output date fields are returned in the specified format. the access plan is revalidated. Appendix E. GENLVL Specifies the severity level at which the create operation fails. Note: If you specify *YES. If a relational database is specified on the RDB parameter and the database is on a system that is not an AS/400 system. For input date strings. 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. Element 2: Right Margin right: Specify the ending position for the statements. or CLE source type. 10: The default severity level is 10. *EUR. Valid values range from 1 through 80. Because the authority or the existence of objects referred to by the dynamic statement may change. If the member is an SQLC. or *JIS must be specified. the validation is completed and an access plan is built. you should check the SQLCODE and SQLSTATE after running an OPEN. *EUR. or *JIS is always valid. If errors occur that have a severity level greater than or equal to this value. DATFMT Specifies the format used when accessing date result columns. SQLCLE. you must still check the SQLCODE or SQLSTATE after issuing the OPEN or EXECUTE statement to ensure that the dynamic statement is still valid. If the member is a different source type. When the dynamic statement is used. Element 1: Left Margin left: Specify the beginning position for the statements. the margin values are the default values of 1 and 80. C. the margin values are the values specified on the source entry utility (SEU) services display. Note: An input date string that uses the format *USA. or DESCRIBE statement to ensure that the dynamic statement is valid. *ISO. then *USA. EXECUTE. *ISO. Valid values range from 1 through 80. the specified value is used to determine whether the date is specified in a valid format. Use the Display Job (DSPJOB) command to determine the current date format for the job.) is used. *YMD: The date format (yy/mm/dd) is used. 814 DB2 UDB for AS/400 SQL Programming V4R4 . *HMS: The hh:mm:ss format is used. ’. *JOB: The date separator specified for the job at precompile time is used. For input time strings. *YMD. *DMY: The date format (dd/mm/yy) is used. *BLANK: A blank ( ) is used. the time format must be *USA.yyyy) is used. *EUR: The European date format (dd. Note: This parameter applies only when *JOB. *USA: The United States date format (mm/dd/yyyy) is used. Note: An input date string that uses the format *USA. or *JIS is always valid. DATSEP Specifies the separator used when accessing date result columns. *EUR.) is used. Use the Display Job (DSPJOB) command to determine the current value for the job. *ISO.’: A comma (. or *JUL is specified on the DATFMT parameter. ’/’: A slash (/) is used. or *HMS with a time separator of a colon or period.mm. *MDY: The date format (mm/dd/yy) is used. *JIS.*JOB: The format specified for the job is used. If a relational database is specified on the RDB parameter and the database is on a system that is not another AS/400 system. *ISO: The International Organization for Standardization (ISO) date format (yyyy-mm-dd) is used. the specified value is used to determine whether the time is specified in a valid format. *JIS: The Japanese Industrial Standard date format (yyyy-mm-dd) is used. *ISO. *DMY. ’ ’: A blank ( ) is used. *JUL: The Julian date format (yy/ddd) is used. ’. TIMFMT Specifies the format used when accessing time result columns. *EUR.’: A period (. ’-’: A dash (-) is used. *MDY. *NONE: An SQL package object is not created.ss is used. *ISO: The International Organization for Standardization (ISO) time format hh. ’. The SQL statements will access the local database.More information on this parameter is in Appendix A.*USA: The United States time format hh:mm xx is used. and any existing program or SQL package of the same name and type in the specified library is moved to QRPLOBJ. Using the C for AS/400 and FORTRAN for AS/400 Precompilers 815 . ″Expanded Parameter Descriptions″ in the CL Reference (Abridged) book. Use the Display Job (DSPJOB) command to determine the current value for the job. the program created is still a distributed SQL program. When the name of the local relational database is specified. Appendix E.) is used.ss is used. where xx is AM or PM. *YES: A new program or SQL package is created. ’ ’: A blank ( ) is used. *JOB: The time separator specified for the job at precompile time 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. relational-database-name: Specify the name of the relational database where the new SQL package object is to be created. ’:’: A colon (:) is used. RDB Specifies the name of the relational database where the SQL package object is created.’: A period (. ’. TIMSEP Specifies the separator used when accessing time result columns.mm. *JIS: The Japanese Industrial Standard time format hh:mm:ss is used. The value of this parameter is passed to the C command. Note: This parameter applies only when *HMS is specified on the TIMFMT parameter.mm. *EUR: The European time format hh.’: A comma (. *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. The program object is not a distributed program and the Create Structured Query Language Package (CRTSQLPKG) command cannot be used.) is used. Refer to the SQL Reference. *NONE: The naming convention defined on the OPTION parameter is used. This parameter is valid only when RDB is specified. This parameter applies only to static SQL statements. indexes. *DUW: CONNECT (Type 2) semantics are used to support distributed unit of work. *NONE: No password is sent. package-name: Specify the name of the SQL package. If the remote system is not an AS/400 system. This value is used instead of the naming convention specified on the OPTION parameter. collection-name: Specify the name of the collection identifier. user-name: Specify the user name to be used for the application server job. *CURRENT: The user profile under which the current job is running is used. This parameter is valid only if RDB is specified. SQLPKG Specifies the qualified name of the SQL package created on the relational database specified on the RDB parameter of this command. no more than 8 characters can be specified. views. library-name: Specify the name of the library where the package is created. and SQL packages. *PGM: The name of the SQL package is the same as the program name. password: Specify the password of the user name specified on the USER parameter.USER Specifies the user name sent to the remote system when starting the conversation. Consecutive CONNECT statements result in the previous connection being disconnected before a new connection is established. This parameter flags SQL statements 816 DB2 UDB for AS/400 SQL Programming V4R4 . USER(*CURRENT) must also be specified. If this value is specified. SAAFLAG Specifies the IBM SQL flagging function. DFTRDBCOL Specifies the collection name used for the unqualified names of tables. PASSWORD Specifies the password to be used on the remote system. 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. The possible library values are: *PGMLIB: The package is created in the library with the same name as the library containing the program. SC41-3612 book for more information. RDBCNNMTH Specifies the semantics used for CONNECT statements. The file must have a minimum record length of 132 bytes or information is lost. SRTSEQ(*JOBRUN) is valid only when LANGID(*JOBRUN) is also specified. *FLAG: The precompiler checks to see whether SQL statements conform to IBM SQL standards. 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. printer-file-name: Specify the name of the printer device file to which the precompiler printout is directed. the precompiler printout is directed to the IBM-supplied printer file QSYSPRT. *CURLIB: The current library for the job is searched. This parameter flags SQL statements to verify whether they conform to the following standards.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. PRTFILE Specifies the qualified name of the printer device file to which the listing is directed. SC26-3255-00. library-name: Specify the name of the library to be searched. Appendix E. ANSI X3. The name of the printer file can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found.2 entry *NONE: The precompiler does not check to see whether SQL statements conform to ANSI standards. *JOBRUN: The SRTSEQ value for the job is retrieved when the program is run. the QGPL library is used. *ANS: The precompiler checks to see whether SQL statements conform to ANSI standards.135-1992 entry ISO 9075-1992 entry FIPS 127. FLAGSTD Specifies the American National Standards Institute (ANSI) flagging function. *NOFLAG: The precompiler does not check to see whether SQL statements conform to IBM SQL standards. SRTSEQ Specifies the sort sequence table to be used for string comparisons in SQL statements. Using the C for AS/400 and FORTRAN for AS/400 Precompilers 817 . For distributed applications. QSYSPRT: If a file name is not specified. *JOB: The SRTSEQ value for hte job is retrieved during the precompile. If no library is specified as the current library for the job. 818 DB2 UDB for AS/400 SQL Programming V4R4 . *USER: Local dynamic SQL statements are run under the user profile of the job. table-name: Specify the name of the sort sequence table to be used. For distributed applications. *HEX: A sort sequence table is not used. DYNUSRPRF Specifies the user profile used for dynamic SQL statements. library-name: Specify the name of the library to be searched. LANGID Specifies the language identifier to be used when SRTSEQ(*LANGIDUNQ) or SRTSEQ(*LANGIDSHR) is specified. The possible library values are: QTEMP: The library QTEMP will be used. *LIBL: The job’s library list is searched for the specified file. the QGPL library will be used. *OWNER: Local dynamic SQL statements are run under the user profile of the program’s owner. the QGPL library is used.*LANGIDUNQ: The unique-weight sort table for the language specified on the LANGID parameter is used. The output member will have the same name as the name that is specified for the SRCMBR parameter. The hexadecimal values of the characters are used to determine the sort sequence. *JOB: The LANGID value for the job is received during the precompile. | | | | | | | | | | | | 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. *JOBRUN: The LANGID value for the job is retrieved when the program is run. If no library is specified as the current library for the job. the file will be created in the current library. If the file is not found in any library in the library list. *LANGIDSHR: The shared-weight sort table for the language specified on the LANGID parameter is used. language-id: Specify a language identifier to be used by the program. LANGID(*JOBRUN) is valid only when SRTSEQ(*JOBRUN) is also specified. it will be created. If the specified source file is not found. Distributed dynamic SQL statements are run under the user profile of the application server job. *CURLIB: The current library for the job will be used. If no library is specified as the current library for the job. Distributed dynamic SQL statements are run under the user profile of the SQL package’s owner. *CURLIB: The current library for the job is searched. The name of the sort sequence table can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. 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. Using the C for AS/400 and FORTRAN for AS/400 Precompilers 819 . This appendix is intended to help those customers who are using the SQL FORTRAN precompiler with other non-IBM FORTRAN compilers. CRTSQLFTN (Create Structured Query Language FORTRAN) Command Job: B. Coding SQL Statements in FORTRAN Applications. More information on this parameter is in Appendix A. ″Expanded Parameter Descriptions″ in the CL Reference book.I Pgm: B. If the source file is an inline file or a device file. or by using either the Add Physical File Member (ADDPFM) or Change Physical File Member (CHGPFM) command. QSQLTEMP: The source file QSQLTEMP will be used.I *CURLIB/ Exec program-name ) CRTSQLFTN *LIBL/ SRCFILE( *CURLIB/ library-name/ QFTNSRC source-file-name ) Appendix E. enclosed in apostrophes. see Appendix F.I PGM( library-name/ REXX: B. *BLANK: Text is not specified. For a description of using the FORTRAN precompiler. 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. the text is blank. ’description’: Specify no more than 50 characters of text.| | | | | library-name: Specify the name of the library that is to contain the output source file. *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. Using the FORTRAN/400 Precompiler FORTRAN/400 is no longer a supported compiler for the AS/400 system. ' '.' '-' ' ' *BLANK ) 820 DB2 UDB for AS/400 SQL Programming V4R4 .(1) *PGM source-file-member-name SRCMBR( ) OPTION( OPTION Details ) TGTRLS( *CURRENT *PRV VxRxMx ) *LIBL/ INCFILE( *CURLIB/ library-name/ *SRCFILE source-file-name ) COMMIT( *UR *CHG *ALL *RS *CS *NONE *NC *RR CLOSQLCSR( ) *ENDPGM *ENDSQL *ENDJOB ) ALWCPYDTA( *YES *OPTIMIZE *NO ) ALWBLK( *READ *NONE *ALLREAD ) DLYPRP( *NO *YES ) GENLVL( 10 severity-level ) DATFMT( *JOB *USA *ISO *EUR *JIS *MDY *DMY *YMD *JUL ) DATSEP( *JOB '/' '. TIMFMT( *HMS *USA *ISO *EUR *JIS ) TIMSEP( *JOB ':' '. Using the C for AS/400 and FORTRAN for AS/400 Precompilers 821 .' '.' ' ' *BLANK ) REPLACE( *YES *NO ) RDB( *LOCAL relational-database-name *NONE ) USER( *CURRENT user-name ) PASSWORD( *NONE password ) RDBCNNMTH( *DUW *RUW ) DFTRDBCOL( *NONE collection-name ) *PGMLIB/ SQLPKG( library-name/ *PGM package-name ) SAAFLAG( *NOFLAG *FLAG ) FLAGSTD( *NONE *ANS ) *LIBL/ PRTFILE( *CURLIB/ library-name/ QSYSPRT printer-file-name ) Appendix E. Purpose The Create Structured Query Language FORTRAN (CRTSQLFTN) command calls the Structured Query Language (SQL) precompiler which precompiles FORTRAN 822 DB2 UDB for AS/400 SQL Programming V4R4 .SRTSEQ( *JOB *JOBRUN *LANGIDUNQ *LANGIDSHR *HEX *LIBL/ table-name *CURLIB/ library-name/ ) LANGID( *JOB *JOBRUN language-ID ) USRPRF( *NAMING *OWNER *USER ) DYNUSRPRF( *USER *OWNER ) QTEMP/ TOSRCFILE( *LIBL/ *CURLIB/ library-name/ QSQLTEMP source-file-name ) TEXT( *SRCMBRTXT *BLANK 'description' ) OPTION Details: *NOSRC *NOSOURCE *SOURCE *SRC *NOXREF *XREF *GEN *NOGEN *PERIOD *JOB *SYSVAL *COMMA *SYS *SQL *NOSECLVL *SECLVL *NODEBUG *DEBUG Notes: 1. All parameters preceding this point can be specified in positional form. or if two options conflict. If no library is specified as the current library for the job. The name of the source file can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found.source containing SQL statements. 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. the QGPL library is used. library-name: Specify the name of hte library where the compiled FORTRAN program is created. OPTION Specifies whether one or more of the following options are used when the FORTRAN source is precompiled. Parameters PGM Specifies the qualified name of the compiled program. If no library is specified as the current library for the job. If an option is specified more than once. the IBM-supplied source file QFTNSRC contains the FORTRAN source. Using the C for AS/400 and FORTRAN for AS/400 Precompilers 823 . *CURLIB: The current library for the job is searched. the last option specified is used. SRCFILE Specifies the qualified name of the source file that contains the FORTRAN source with SQL statements. QFTNSRC: If the source file name is not specified. This parameter is specified only if the source file name in the SRCFILE parameter is a database file. the PGM name specified on the PGM parameter is used. the QGPL library is used. program-name: Specify the name of the compiled FORTRAN program. Element 1: Source Listing Options Appendix E. and then optionally calls the FORTRAN compiler to compile the program. source-file-name: Specify the name of the source file that contains the FORTRAN source. source-file-member-name: Specify the name of the member that contains the FORTRAN source. *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. If this parameter is not specified. library-name: Specify the name of the library to be searched. produces a temporary source member. SRCMBR Specifies the name of the source file member that contains the C source. Element 5: Naming Convention Options *SYS:The system naming convention (library-name/file-name) is used. 2. Element 3: Program Creation Options *GEN: *NOGEN: The precompiler does not call the FORTRAN compiler.1. 824 DB2 UDB for AS/400 SQL Programming V4R4 . For example. Element 2: Cross-Reference Options *NOXREF: The precompiler does not cross-reference names. *SQL must be specified as the naming convention. *SYSVAL: The value used as the decimal point for numeric constants in SQL statements is the QDECFMT system value.4.23. *XREF:The precompiler cross-references items in the program to the statement numbers in the program that refer to those items.1. 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. and a program and SQL package are not created. 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. *SOURCE or *SRC: The precompiler produces a source printout consisting of FORTRAN source input. *COMMA: The value used as the decimal point for numeric constants in SQL statements is a comma. *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. When creating a program on a remote database other than an AS/400 system.*NOSOURCE: or *NOSRC: A source printout is not produced by the precompiler unless errors are detected during precompile or create package.table-name).23. *SQL: The SQL naming convention is used (collection-name.1) is equivalent to VALUES(1. Note: If QDECFMT specifies that the value used as the decimal point is a comma.1) where the decimal point is a period.2.1) is equivalent to VALUES(1. For example.1) in which the decimal point is a period.1.4.23.23. 4.2. VALUES(1. VALUES(1. Element 4: Decimal Point Options *PERIOD: The value used as the decimal point for numeric constants used in SQL statements is a period. Element 6: Second-Level Message Text Option *NOSECLVL: Second-level text descriptions are not added to the listing. 2. 4.1. and they change with each new release. *DEBUG: Symbolic EPM debug information is stored with the program. For example. release 3. For example. Element 7: Debug Options *NODEBUG: Symbolic extended program model (EPM) debug information is not stored with the program. The name of the source file can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. This option is passed to the compiler and does not affect the SQL precompiler. For example. *CURLIB: The current library for the job is searched. an error message is sent indicating the earliest supported release. The user can also use the object on a system with any subsequent release of the operating system installed. *PRV: The object is to be used on the previous release with modification level 0 of the operating system. modification level 0. Appendix E. and when specifying the release-level value. the QGPL library is used. if V2R3M5 is running on the user’s system. In the examples given for the *CURRENT and *PRV values. *CURRENT: The object is to be used on the release of the operating system currently running on the user’s system. *CURRENT means the user intends to use the object on a system with V2R3M5 installed. and modification level. If no library is specified as the current library for the job. where Vx is the version.*SECLVL: Second-level text with replacement data is added for all messages on the listing. and Mx is the modification level. release. The user can also use the object on a system with any subsequent release of the operating system installed. if V2R3M5 is running on the system. If you specify a release-level which is earlier than the earliest release level supported by this command. V2R3M0 is version 2. The object can be used on a system with the specified release or with any subsequent release of the operating system installed. INCFILE Specifies the qualified name of the source file that contains members included in the program with any SQL INCLUDE statement. Note: If V2R3M5 is running on the system. TGTRLS Specifies the release of the operating system on which the user intends to use the object being created. release-level: Specify the release in the format VxRxMx. *PRV means the user intends to use the object on a system with V2R2M0 installed. the format VxRxMx is used to specify the release. Rx is the release. specify TGTRLS(V2R3M0) not TGTRLS(*CURRENT). Using the C for AS/400 and FORTRAN for AS/400 Precompilers 825 . Valid values depend on the current version. This option is passed to the compiler and does not affect the SQL precompiler. and the object is to be used on a system with V2R3M0 installed. and REVOKE statements and the rows selected. deleted. deleted. RENAME. DROP. deleted. LABEL ON. and inserted are locked until the end of the unit of work (transaction). and REVOKE statements and the rows updated. COMMENT ON. is locked until the next row is selected. and inserted are locked until the end of the unit of work (transaction). COMMENT ON. Uncommitted changes in other jobs cannot be seen. Only SQL tables. updated. *CHG or *UR: Specifies the objects referred to in SQL ALTER. but not updated. *NONE or *NC cannot be specified. 826 DB2 UDB for AS/400 SQL Programming V4R4 . *NONE or *NC: Specifies that commitment control is not used. GRANT. or ROLLBACK (without HOLD) SQL statements. SQL prepared statements are implicitly discarded. LABEL ON. CALL. and REVOKE statements and the rows selected. *ALL or *RS: Specifies the objects referred to in SQL ALTER. and REVOKE statements and the rows updated. RENAME. Uncommitted changes in other jobs cannot be seen. GRANT. LABEL ON. CREATE. COMMIT Specifies whether SQL statements in the compiled program are run under commitment control. DROP. 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 must be used. and INSERT statements are locked exclusively until the end of the unit of work (transaction). If the SQL DROP COLLECTION statement is included in the program. LOCK TABLE locks are released when the first SQL program on the call stack ends. SQL cursors are explicitly closed when you issue the CLOSE. GRANT. GRANT.library-name: Specify the name of the library to be searched. CALL. and inserted are locked until the end of the unit of work (transaction). All tables referred to in SELECT. DROP. CREATE. and inserted are locked until the end of the unit of work (transaction). source-file-name: Specify the name of the source file that contains the source file members specified on any SQL INCLUDE statement. *RR: Specifies the objects referred to in SQL ALTER. *CS: Specifies the objects referred to in SQL ALTER. CALL. deleted. *SRCFILE: The qualified source file specified in the SRCFILE parameter contains the source file members specified on any SQL INCLUDE statement. Files referred to in the host language source are not affected by this option. SQL views. COMMIT. DELETE. CALL. CLOSQLCSR Specifies when SQL cursors are implicitly closed. UPDATE. RENAME. updated. RENAME. CREATE. COMMENT ON. Uncommitted changes in other jobs can be seen. COMMENT ON. 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. A row that is selected. LABEL ON. and SQL packages referred to in SQL statements are affected. DROP. Uncommitted changes in other jobs can be seen. Uncommitted changes in other jobs cannot be seen. *ENDPGM: SQL cursors are closed and SQL prepared statements are discarded when the program ends. and LOCK TABLE locks are released. CREATE. ALWBLK Specifies whether the database manager can use record blocking. *NONE: Rows are not blocked for retrieval of data for cursors. If *ENDSQL is specified for a program that is the first SQL program called (the first SQL program on the call stack). SQL cursors are closed. SQL prepared statements are discarded. Appendix E. 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. One of the programs higher on the call stack must have run at least one SQL statement. *YES: A copy of the data is used only when necessary. and LOCK TABLE locks are released when the first SQL program on the call stack ends. SQL cursors are left open.*ENDSQL: SQL cursors remain open between calls and can be fetched without running another SQL OPEN. Specifying *ALLREAD: v Allows record blocking under commitment control level *CHG in addition to the blocking allowed for *READ. SQL prepared statements are preserved. and the extent to which blocking can be used for read-only cursors. then a copy of the data is used only when it is necessary to run a query. *ENDJOB: SQL cursors remain open between calls and can be fetched without running another SQL OPEN. cannot be used to update a row in a cursor unless the DECLARE statement for the cursor includes the FOR UPDATE clause. The decision is based on which method provides the best performance. – Dynamic running of a positioned UPDATE or DELETE statement (for example. If COMMIT is *CHG or *CS and ALWBLK is not *ALLREAD. SQL prepared statements are discarded. *ALLREAD: Rows are blocked for read-only cursors if *NONE or *CHG is specified on the COMMIT parameter. Specifying *NONE: v Guarantees that the data retrieved is current. a ROLLBACK statement in host languages. Using the C for AS/400 and FORTRAN for AS/400 Precompilers 827 . v Can improve the performance of almost all read-only cursors in programs. *OPTIMIZE: The system determines whether to use the data retrieved directly from the database or to use a copy of the data. The programs higher on the call stack do not need to have run SQL statements. and LOCK TABLE locks are released when the job ends. the program is treated as if *ENDPGM was specified. or the ROLLBACK HOLD SQL statement does not reposition a read-only cursor when *ALLREAD is specified. SQL cursors are closed. *NO: A copy of the data is not allowed. or if COMMIT is *ALL or *RR. an error message is returned. If a temporary copy of the data is required to perform the query. but limits queries in the following ways: – The Rollback (ROLLBACK) command. and LOCK TABLE locks are held when the first SQL program on the call stack ends. using EXECUTE IMMEDIATE). ALWCPYDTA Specifies whether a copy of the data can be used in a SELECT statement. the validation is completed and an access plan is built. severity-level: Specify a value ranging from 0 through 40. the access plan is validated. 828 DB2 UDB for AS/400 SQL Programming V4R4 . If you specify *YES on this parameter. For input date strings. 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. Because the authority or the existence of objects referred to by the dynamic statement may change. Note: If you specify *YES.v May reduce the amount of time required to retrieve the first row of data for a query. DATFMT Specifies the format used when accessing date result columns. If errors occur that have a severity level greater than or equal to this value. When the dynamic statement is used. 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. the specified value is used to determine whether the date is specified in a valid format. 10: The default severity level is 10. *NO: Dynamic statement validation is not delayed. All output date fields are returned in the specified format. Delaying validation improves performance by eliminating redundant validation. *READ: Records are blocked for read-only retrieval of data for cursors when: v *NONE is specified on the COMMIT parameter. you must still check the SQLCODE or SQLSTATE after issuing the OPEN or EXECUTE statement to ensure that the dynamic statement is still valid. GENLVL Specifies the severity level at which the create operation fails. Specifying *READ can improve the overall performance of queries that meet the above conditions and retrieve a large number of records. the operation ends. v Can degrade the overall performance of a query that retrieves a large number of rows. DLYPRP Specifies whether the dynamic statement validation for a PREPARE statement is delayed until an OPEN. When the dynamic statement is used in an OPEN or EXECUTE statement. you should check the SQLCODE and SQLSTATE after running an OPEN. *YES: Dynamic statement validation is delayed until the dynamic statement is used in an OPEN. the access plan is revalidated. EXECUTE. EXECUTE. When the dynamic statement is prepared. which indicates that commitment control is not used. or DESCRIBE statement to ensure that the dynamic statement is valid. or DESCRIBE SQL statement. 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. EXECUTE. or DESCRIBE statement is run. ’. *ISO. or *JIS must be specified. *USA: The United States date format (mm/dd/yyyy) is used. If a relational database is specified on the RDB parameter and the database is on a system that is not an AS/400 system.yyyy) is used.’: A comma (. TIMFMT Specifies the format used when accessing time result columns. Using the C for AS/400 and FORTRAN for AS/400 Precompilers 829 . ’-’: A dash (-) is used. *JOB: The date separator specified for the job at precompile time is used. the specified value is used to determine whether the time is specified in a valid format. or *JIS is always valid. For input time strings. *ISO: The International Organization for Standardization (ISO) date format (yyyy-mm-dd) is used. *EUR. *YMD. *BLANK: A blank ( ) is used. *DMY. *EUR. *MDY: The date format (mm/dd/yy) is used. ’.) is used. *ISO. *DMY: The date format (dd/mm/yy) is used. then *USA. Note: An input date string that uses the format *USA. Note: This parameter applies only when *JOB. *JIS: The Japanese Industrial Standard date format (yyyy-mm-dd) is used. *EUR: The European date format (dd.’: A period (. Appendix E. *YMD: The date format (yy/mm/dd) is used. *EUR.Note: An input date string that uses the format *USA. Use the Display Job (DSPJOB) command to determine the current date format for the job. or *JUL is specified on the DATFMT parameter.) is used. *JOB: The format specified for the job is used. *ISO. ’/’: A slash (/) is used. *JUL: The Julian date format (yy/ddd) is used. Use the Display Job (DSPJOB) command to determine the current value for the job. or *JIS is always valid. DATSEP Specifies the separator used when accessing date result columns.mm. *MDY. ’ ’: A blank ( ) is used. *BLANK: A blank ( ) is used. More information on this parameter is in Appendix A.) is used. *JOB: The time separator specified for the job at precompile time is used.’: A comma (. and any existing program or SQL package of the same name and type in the specified library is moved to QRPLOBJ. TIMSEP Specifies the separator used when accessing time result columns.mm.mm. The SQL statements will access the local database. *ISO: The International Organization for Standardization (ISO) time format (hh. *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. or *HMS with a time separator of colon or period.’: A period (.ss) is used. ’ ’: A blank ( ) is used.) is used. Use the Display Job (DSPJOB) command to determine the current value for the job. the time format must be *USA. *ISO. *USA: The United States time format (hh:mm xx) is used. *JIS. An SQL package object is not 830 DB2 UDB for AS/400 SQL Programming V4R4 . *LOCAL: The program is created as a distributed SQL program. *HMS: The (hh:mm:ss) format is used. *EUR. 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. ’:’: A colon (:) is used. ’. RDB Specifies the name of the relational database where the SQL package object is created. ’. where xx is AM or PM. *EUR: The European time format (hh. The value of this parameter is passed to the CRTFTNPGM command. *YES: A new program or SQL package is created. ″Expanded Parameter Descriptions″ in the CL Reference (Abridged) book.If a relational database is specified on the RDB parameter and the database is on a system that is not another AS/400 system. *JIS: The Japanese Industrial Standard time format (hh:mm:ss) is used. Note: This parameter applies only when *HMS is specified on the TIMFMT parameter.ss) is used. *NONE: An SQL package object is not created. user-name: Specify the user name being used for the application server job. This value is used instead of the naming convention specified on the OPTION parameter. Consecutive CONNECT statements result in the previous connection being disconnected before a new connection is established. The possible library values are: Appendix E. RDBCNNMTH Specifies the semantics used for CONNECT statements. This parameter is valid only when RDB is specified. SQLPKG Specifies the qualified name of the SQL package created on the relational database specified on the RDB parameter of this command. DFTRDBCOL Specifies the collection name used for the unqualified names of tables. This parameter applies only to static SQL statements. Consecutive CONNECT statements to additional relational databases do not result in disconnection of previous connections. Refer to the SQL Reference book for more information. *CURRENT: The user profile under which the current job is running is used. When the name of the local relational database is specified. views. *RUW: CONNECT (Type 1) semantics are used to support remote unit of work. *NONE: The naming convention defined on the OPTION parameter is used. collection-name: Specify the name of the collection identifier. *DUW: CONNECT (Type 2) semantics are used to support distributed unit of work. relational-database-name: Specify the name of the relational database where the new SQL package object is to be created. *NONE: No password is sent. and SQL packages. The program object is not a distributed program and the Create Structured Query Language Package (CRTSQLPKG) command cannot be used. PASSWORD Specifies the password to be used on the remote system. USER(*CURRENT) must also be specified. indexes. Using the C for AS/400 and FORTRAN for AS/400 Precompilers 831 . The SQL statements will access the local database. password: Specify the password of the user name specified on the USER parameter. USER Specifies the user name sent to the remote system when starting the conversation. The Create Structured Query Language Package (CRTSQLPKG) command can be used. This parameter is valid only if RDB is specified. the program created is still a distributed SQL program. If this value is specified.created as part of the precompile process. If no library is specified as the current library for the job. The name of the printer file can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. *NOFLAG: The precompiler does not check to see whether SQL statements conform to IBM SQL syntax. PRTFILE Specifies the qualified name of the printer device file to which the listing is directed. package-name: Specify the name of the package created on the remote database specified on the RDB parameter. SRTSEQ Specifies the sort sequence table to be used for string comparisons in SQL statements.135-1992 entry ISO 9075-1992 entry FIPS 127. FLAGSTD Specifies the American National Standards Institute (ANSI) flagging function. *FLAG: The precompiler checks to see whether SQL statements conform to IBM SQL syntax. 832 DB2 UDB for AS/400 SQL Programming V4R4 . SC26-3255-00. SAAFLAG Specifies the IBM SQL flagging function.2 entry *NONE: The precompiler does not check to see whether SQL statements conform to ANSI standards. *CURLIB: The current library for the job is searched. 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. *PGM: The package name is the same as the program name.*PGMLIB: The package is created in the library with the same name as the library containing the program. the precompiler printout is directed to the IBM-supplied printer file QSYSPRT. library-name: Specify the name of the library where the package is created. printer-file-name: Specify the name of the printer device file to which the precompiler printout is directed. The file must have a minimum record length of 132 bytes or information is lost. *ANS: The precompiler checks to see whether SQL statements conform to ANSI standards. QSYSPRT: If a file name is not specified. This parameter flags SQL statements to verify whether they conform to the following standards. library-name: Specify the name of the library to be searched. the QGPL library is used. ANSI X3. If no library is specified as the current library for the job. *JOB: The SRTSEQ value for the job is retrieved during the precompile. Using the C for AS/400 and FORTRAN for AS/400 Precompilers 833 . The name of the sort sequence table can be qualified by one of the following library values: *LIBL: All libraries in the job’s library list are searched until the first match is found. table-name: Specify the name of the sort sequence table to be used. *JOB: The LANGID value for the job is retrieved during the precompile.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. Appendix E. 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. *LANGIDSHR: The shared-weight sort table for the language specified on the LANGID parameter is used. The hexadecimal values of the characters are used to determine the sort sequence. SRTSEQ(*JOBRUN) is valid only when LANGID(*JOBRUN) is also specified. For distributed applications. For distributed applications. *JOBRUN: The LANGID value for the job is retrieved when the program is run. *CURLIB: The current library for the job is searched. LANGID(*JOBRUN) is valid only when SRTSEQ(*JOBRUN) is also specified. *LANGIDUNQ: The unique-weight sort table for the language specified on the LANGID parameter is used. *HEX: A sort sequence table is not used. *JOBRUN: The SRTSEQ value for the job is retrieved when the program is run. LANGID Specifies the language identifier to be used when SRTSEQ(*LANGIDUNQ) or SRTSEQ(*LANGIDSHR) is specified. language-id: Specify a language identifier to be used by the program. the QGPL library is used. The profile of either the program owner or the program user is used to control which objects can be used by the program object. library-name: Specify the name of the library to be searched. including the authority that the program object has for each object in static SQL statements. USRPRF Specifies the user profile that is used when the compiled program object is run. Specifies the sort sequence table to be used for string comparisons in SQL statements. USRPRF(*USER) is used. *SRCMBRTXT: The text is taken from the source file member being used to create the FORTRAN program. The output member will have the same name as the name that is specified for the SRCMBR parameter. *OWNER: The user profiles of both the program owner and the program user are used when the program is run. Text can be added or changed for a database source member by using the Start Source Entry Utility (STRSEU) command. *USER: Local dynamic SQL statements are run under the user profile of the job. *BLANK: Text is not specified. The possible library values are: QTEMP: The library QTEMP will be used. it will be created.*NAMING: The user profile is determined by the naming convention. If the file is not found in any library in the library list. USRPRF(*OWNER) is used. If no library is specified as the current library for the job. library-name: Specify the name of the library that is to contain the output source file. If the naming convention is *SYS. If the specified source file is not found. If the source file is an inline file or a device file. the text is blank. Distributed dynamic SQL statements are run under the user profile of the application server job. TEXT Specifies the text that briefly describes the LANGID. DYNUSRPRF Specifies the user profile used for dynamic SQL statements. *OWNER: Local dynamic SQL statements are run under the user profile of the program’s owner. *USER: The profile of the user running the program object is used. *LIBL: The job’s library list is searched for the specified file. source-file-name: Specify the name of the source file to contain the output source member. ″Expanded Parameter Descriptions″ in the CL Reference (Abridged) book. | | | | | | | | | | | | | | | | | 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. or by using either the Add Physical File Member (ADDPFM) or Change Physical File Member (CHGPFM) command. Distributed dynamic SQL statements are run under the user profile of the SQL package’s owner. the file will be created in the current library. If the naming convention is *SQL. QSQLTEMP: The source file QSQLTEMP will be used. More information on this parameter is in Appendix A. 834 DB2 UDB for AS/400 SQL Programming V4R4 . *CURLIB: The current library for the job will be used. the QGPL library will be used. Appendix E. enclosed in apostrophes. which precompiles the source and stores the changed source in member PAYROLL in file QSQLTEMP in library QTEMP. Using the C for AS/400 and FORTRAN for AS/400 Precompilers 835 . The FORTRAN compiler is called to create program PAYROLL in the current library by using the source member created by the SQL precompiler. Example CRTSQLFTN PAYROLL TEXT('Payroll Program') This command runs the SQL precompiler.’description’: Specify no more than 50 characters of text. 836 DB2 UDB for AS/400 SQL Programming V4R4 . INTEGER*4 SQLCOD SQLERR(6) INTEGER*2 SQLTXL CHARACTER SQLERP*8. Defining the SQL Communications Area A FORTRAN program that contains SQL statements must include one or both of the following: v An SQLCOD variable declared as INTEGER v An SQLSTA (or SQLSTATE) variable declared as CHARACTER*5 Or. v An SQLCA (which contains an SQLCOD and SQLSTA variable). EQUIVALENCE (SQLCA( 89). EQUIVALENCE (SQLCA( 17). Requirements for host variables are defined. EQUIVALENCE (SQLCA( 19). C SQLCAID) SQLCABC) SQLCODE) SQLERRML) SQLERRMC) SQLERRP) SQLERRD) SQLWARN) SQLSTATE) * © Copyright IBM Corp. 1999 837 . EQUIVALENCE (SQLCA( 97). EQUIVALENCE (SQLCA( 13). C SQLWRX(1:3)*1. Coding SQL Statements in FORTRAN Applications This appendix describes the unique application and coding requirements for embedding SQL statements in a FORTRAN/400 program. EQUIVALENCE (SQLCA( 9). EQUIVALENCE (SQLCA(121). An application can check the SQLCOD or SQLSTA (or SQLSTATE) value to determine whether the last SQL statement was successful. 1997. EQUIVALENCE (SQLCA(132). Using the SQL INCLUDE statement requests the inclusion of a standard declaration: EXEC SQL INCLUDE SQLCA The included FORTRAN source statements for the SQLCA are: * * * The SQL communications area CHARACTER SQLCA(136) CHARACTER SQLCAID*8 INTEGER*4 SQLCABC INTEGER*4 SQLCODE INTEGER*2 SQLERRML CHARACTER SQLERRMC*70 CHARACTER SQLERRP*8 INTEGER*4 SQLERRD(6) CHARACTER SQLWARN*11 CHARACTER SQLSTATE*5 EQUIVALENCE (SQLCA( 1). The SQLCA can be coded in a FORTRAN program either directly or by using the SQL INCLUDE statement.Appendix F. The SQLCOD and SQLSTA (or SQLSTATE) values are set by the database manager after each SQL statement is executed. C SQLWRN(0:7)*1. there can be more than one SQLDA in a program. This improves performance. SQLERRWK*24. SQLWRNWK) EQUIVALENCE (SQLWRX(1).USING DESCRIPTOR descriptor-name OPEN. SQLWRNWK*8. SQLSTA. SQLERRWK) COMMON /SQLCA1/SQLCOD. If compatibility with other IBM SQL implementations is not a primary consideration. Dynamic SQL is an advanced programming technique described in Chapter 10. Defining SQL Descriptor Areas The following statements require an SQLDA: EXECUTE.SQLERR. SQLWRXWK*3... and SQLCA variables must be placed before the first executable SQL statement. see Appendix B.USING DESCRIPTOR descriptor-name FETCH. “SQL Communication Area” in the DB2 UDB for AS/400 SQL Reference book. SQLERRDWK*24 EQUIVALENCE (SQLWRN(1). and an SQLDA can have any valid name..SQLWRX. SQLSTT*5. or SQLSTATE in the program. SQLWRXWK) EQUIVALENCE (SQLCA(97). For more information on SQLCA. an INCLUDE SQLDA statement 838 DB2 UDB for AS/400 SQL Programming V4R4 . The SQLCOD. SQLSTA. a list of the data to be returned as part of the query) that runs dynamically requires an SQL descriptor area (SQLDA). your program can develop and then run SQL statements while the program is running. SQLERRDWK) EQUIVALENCE (SQLERR(1).SQLSTT SQLSTATE is replaced with SQLSTOTE when a declare for SQLSTATE is found in the program and the SQLCA is provided by the compiler..USING DESCRIPTOR descriptor-name DESCRIBE statement-name INTO descriptor-name DESCRIBE TABLE host-variable INTO descriptor-name PREPARE statement-name INTO descriptor-name Unlike the SQLCA. SQLSTATE. and SQLCA variables.SQLTXT. Dynamic SQL Applications. Because the SQLDA uses pointer variables.. 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.SQLWRN. it is recommended that the SQLCA be included by coding the FORTRAN variable SQLCOD. which are not supported by FORTRAN. SQLSTA.USING DESCRIPTOR descriptor-name CALL.C C C C C C SQLTXT*70. but does not generate a compatible SQLCA. All SQL statements that can be run in a program must be within the scope of the declaration of the SQLCOD variable or SQLCA variables. SQLSTATE. All executable SQL statements in a program must be within the scope of the declaration of the SQLCOD. With dynamic SQL.... A SELECT statement with a variable SELECT list (that is.SQLTXTL COMMON /SQLCA2/SQLERP. Coding an SQLDA on the multiple-row FETCH statement using a row storage area provides a technique to retrieve multiple rows on each FETCH statement. except between the keywords EXEC and SQL. The comment extends to the end of the line. Each SQL statement in a FORTRAN program must begin with EXEC SQL. you cannot use the SQLDA. but the SQL language does. Example: An UPDATE statement coded in a FORTRAN program might be coded as follows: C C C EXEC SQL UPDATE DEPARTMENT SET MGRNO = :MGRNUM WHERE DEPTNO = :INTDEPT An SQL statement cannot be followed on the same line by another SQL statement or by a FORTRAN statement. Comment lines can appear between the lines of a continued SQL statement. The EXEC SQL keywords must appear all on one line. any necessary THEN and END IF statements will be generated. FORTRAN does not require the use of blanks to delimit words within a statement. The character (!) indicates a comment. or ILE RPG program and passed to the FORTRAN program. Embedding SQL Statements SQL statements can be coded in a FORTRAN program wherever a statement that can be run appears. Coding SQL Statements in FORTRAN Applications 839 . If the SQL statement is within an IF statement. Comments In addition to SQL comments (--). except when it appears in a character context or in column 6. This technique can improve an application’s performance if a large number of rows are read by the application. Continuation for SQL statements The line continuation rules for SQL statements are the same as those for other FORTRAN statements. see the DB2 UDB for AS/400 SQL Reference book. but the remainder of the statement can appear on the same line and on subsequent lines. Appendix F. which requires the use of one or more blanks as delimiters. PL/I. For more information on using the FETCH statement. FORTRAN comments can be included within the embedded SQL statements wherever a blank is allowed. The rules for embedded SQL follow the rules for SQL syntax.cannot be specified in a FORTRAN program. except that EXEC SQL must be specified within one line. Unless an SQLDA is set up by a C. Debug Lines Lines contain debug statements (’D’ or ’d’ in column 1) are treated as comments lines by the precompiler. COBOL. *.. A labelled SQL statement should not be the last statement in a DO loop... Because CONTINUE statements can be run..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.. Margins Code the SQL statements (starting with EXEC SQL) in coding columns 7 to 72.3.... These names are reserved for the database manager.+... 840 DB2 UDB for AS/400 SQL Programming V4R4 .+.. INCLUDE and BEGIN DECLARE SECTION) should not be labelled.+.+.. 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'.+..2. specified in columns 1 to 5.6. However.... a labelled SQL statement causes a CONTINUE statement with that label to be generated before the code runs the statement..+.+... This SQL statement has a valid graphic constant of G’<AABBCCDDEEFFGGHHIIJJKK>’..7..5. during program preparation. or 'DSN'. SQL statements that occur before the first statement that can be run in a FORTRAN program (for example....+.1.. 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.4............ 'RDI'.......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 The FORTRAN INCLUDE compiler directive cannot be used to include SQL statements or FORTRAN host variable declarations that are to be used in an SQL statement...... 'SQL'. all host variable declarations used in SQL statements must be between the BEGIN DECLARE SECTION and the END DECLARE SECTION statements. The names of host variables should be unique within the program. All host variables within an SQL statement must be preceded with a colon (:).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. Implicit declarations of host variables via default typing or by the IMPLICIT statement are not supported. FORTRAN Compile-Time Options The FORTRAN PROCESS statement can be used to specify the compile-time options for the FORTRAN compiler. The declaration for a character host variable must not use an expression to define the length of the character variable. A WHENEVER statement only applies to SQL statements in the same subprogram. Declaring Host Variables The FORTRAN precompiler only recognizes a subset of valid FORTRAN declarations as valid host variable declarations. they cannot be elements of arrays (subscripted variables). Numeric Host Variables The following figure shows the syntax for valid numeric host variable declarations. Note: LOB host variables are not supported in FORTRAN. Appendix F. the SQL precompiler itself does not recognize the PROCESS statement. even if the host variables are in different blocks or procedures. Although the PROCESS statement will be recognized by the FORTRAN compiler when it is called by the precompiler to create the program. CHARACTER(*)). The declaration for a character host variable must not have an undefined length (for example. The FORTRAN 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. Coding SQL Statements in FORTRAN Applications 841 . A host variable used in an SQL statement must be declared prior to the first use of the host variable in an SQL statement. Host variables must be scalar variables. An SQL statement that uses a host variable must be within the scope of the statement in which the variable was declared. If a BEGIN DECLARE SECTION and END DECLARE SECTION are specified. Using Host Variables All host variables used in SQL statements must be explicitly declared. variable-name / numeric-constant / Character Host Variables The following figure shows the syntax for valid character host variable declarations. If a host variable appears with an indicator variable. Character CHARACTER *n . Table 78. variable-name *n / character-constant / Note: n must be a constant no greater than 32766.Numeric INTEGER*2 INTEGER *4 REAL *4 REAL*8 DOUBLE PRECISION . FORTRAN Declarations Mapped to Typical SQL Data Types FORTRAN Data Type INTEGER*2 INTEGER*4 REAL*4 SQLTYPE of Host Variable 500 496 480 SQLLEN of Host SQL Data Type Variable 2 4 4 SMALLINT INTEGER FLOAT (single precision) 842 DB2 UDB for AS/400 SQL Programming V4R4 . the SQLTYPE is the base SQLTYPE plus one. Determining Equivalent SQL and FORTRAN Data Types The precompiler determines the base SQLTYPE and SQLLEN of host variables based on the following table. If the format is *YMD. n must be at least 19. To include microseconds at full precision. truncation occurs on the microseconds part. Table 79. If n is less than 26. to include seconds. or *ISO. *JIS. use exponent notation when specifying a real (floating-point) constant in an SQL statement. *EUR. FORTRAN Declarations Mapped to Typical SQL Data Types (continued) FORTRAN Data Type REAL*8 CHARACTER*n SQLTYPE of Host Variable 480 452 SQLLEN of Host SQL Data Type Variable 8 n FLOAT (double precision) CHAR(n) The following table can be used to determine the FORTRAN data type that is equivalent to a given SQL data type. or *MDY. Use a character host variable large enough to contain the largest expected VARCHAR value. SQL Data Types Mapped to Typical FORTRAN Declarations SQL Data Type SMALLINT INTEGER DECIMAL(p. a string of digits with a decimal point is interpreted as a real constant. n must be at least 8. such a string is interpreted as a decimal constant. In an SQL statement. Not supported Not supported If the format is *USA.s) FLOAT (single precision) FLOAT (double precision) CHAR(n) VARCHAR(n) FORTRAN Equivalent INTEGER*2 INTEGER*4 No exact equivalent REAL*4 REAL*8 CHARACTER*n No exact equivalent Use REAL*8 Explanatory Notes n is a positive integer from 1 to 32766. *DMY.Table 78. Coding SQL Statements in FORTRAN Applications 843 . If the format is *JUL. TIMESTAMP CHARACTER*n Notes on FORTRAN Variable Declaration and Usage In FORTRAN. n must be at least 8 characters.s) or NUMERIC(p. n must be at least 10 characters. n must be 26. Therefore. GRAPHIC(n) VARGRAPHIC(n) DATE Not supported Not supported CHARACTER*n TIME CHARACTER*n n must be at least 6. Appendix F. n must be at least 6 characters. C :BGN :BGN_IND. 3. Using Indicator Variables An indicator variable is a two-byte integer (INTEGER*2). C :DAY :DAY_IND. BGN_IND.14159E+04). 3. On assignment to a column. an indicator variable is used to show if its associated host variable has been assigned a null value. See DB2 UDB for AS/400 SQL Reference book for more information on the use of indicator variables.14159D+04). ENDCLS_IND EXEC SQL END DECLARE SECTION 844 DB2 UDB for AS/400 SQL Programming V4R4 . An 8-byte floating-point constant in an SQL statement must use an E (for example. Indicator variables are declared in the same way as host variables. The declarations of the two can be mixed in any way that seems appropriate to the programmer. a negative indicator variable is used to indicate that a null value should be assigned. a real (floating-point) constant having a length of eight bytes uses a D as the exponent indicator (for example. C :ENDCLS :ENDCLS_IND The variables can be declared as follows: EXEC SQL BEGIN DECLARE SECTION CHARACTER*7 CLS_CD INTEGER*2 DAY CHARACTER*8 BGN.In FORTRAN. On retrieval. Example: Given the statement: EXEC SQL FETCH CLS_CURSOR INTO :CLS_CD. ENDCLS INTEGER*2 DAY_IND. The manuals in this section are listed with their full title and order number. using native and SQL data access interface. The book reports examples developed in several programming languages (RPG. and creating CL programs. SC41-5304-03 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. SC41-5721-02 This guide provides a wide-ranging discussion of the AS/400 programming topics. breakpoints.) It also provides an overview of all the CL commands for the AS/400 system. and maintain ILE C for AS/400 programs on the AS/400 system. including a general discussion of objects and libraries. and practical examples of when and how functions offered by DB2 UDB for AS/400 such as triggers. DRDA-2. v CL Reference (Abridged). including debug mode. v Backup and Recovery. and display functions. and setting up security on the system. guidelines. can be effectively used. and maintain ILE RPG for AS/400 programs on the AS/400 system. v Data Management This guide provides information about using files in application programs. SC09-2540-01 This guide provides information you need to design. (Non-OS/400 commands are described in the respective licensed program publications. GG24-4249 This guide provides suggestions. C). both in the Integrated Language Environment and with the Original Program Model. keeping security up-to-date. 1999 information about protecting the system and data from being used by people who do not have the proper authorization. v ILE COBOL for AS/400 Programmer’s Guide. v DB2 UDB for AS/400 Database Programming This guide provides a detailed description of the DB2 UDB for AS/400 database organization. SC41-5722-03 This guide provides a description of the AS/400 control language (CL) and its OS/400 commands. files. and it describes the syntax rules needed to code them. COBOL. controlling flow and communicating between programs. 1997. Other topics include predefined and impromptu messages and handling. a shortened version of the title is used. CL programming. and stored procedures. v Security . 2-phase commit. v ILE C for AS/400 Programmer’s Guide. test.Bibliography This guide lists publications that provide additional information about topics described or referred to in this guide. v ILE C for AS/400 Language Reference. protecting the data from intentional or unintentional damage or destruction. v DB2 UDB for AS/400 SQL Reference This guide provides information about DB2 UDB for AS/400 statements and their parameters. working with objects in CL programs. SC09-2711-01 This guide provides information you need to design. application testing. It also describes how to install the system again from backup. SC41-5302-03 This guide provides information about system security concepts. but when referred to in text. and setting up security on the system. test. It also gives © Copyright IBM Corp. write. and records to the system. planning for security. including information on how to create. write. defining and creating user-defined commands and menus. write. v IDDU Use. SC41-5704-00 This guide describes how to use DB2 UDB for AS/400 interactive data definition utility (IDDU) to describe data dictionaries. v CL Programming. describe. and disk recovery procedures. It also includes an appendix describing the SQL communications area (SQLCA) and SQL description area (SQLDA). and maintain COBOL for AS/400 programs on the AS/400 system. SC09-2712-01 845 . v DATABASE 2/400 Advanced Database Functions. test. v ILE RPG for AS/400 Programmer’s Guide. the different types of media available to save and restore procedures. referential integrity. SC09-2507-02 This guide provides information you need to design. and update database files on the system.Reference. traces. write. v ILE COBOL for AS/400 Reference. test. SC41-5728-00 This guide provides information you need to design. write. v PL/I User’s Guide and Reference. Information is provided on how to configure the systems. SC09-2539-01 This guide provides information you need to design. how to create the files. nodegroups. This book also has tips for printing and analyzing performance data to identify and correct inefficiencies that might exist. test. and maintain COBOL for AS/400 programs on the AS/400 system. test. and partitioning. or program performance. Information about the manager and agent feature is included. v DB2 UDB for AS/400 SQL Call Level Interface This guide provides the information necessary for application programmers to write applications using the DB2 call level interface. write. v Performance Tools for AS/400. SC41-5340-00 This guide provides the programmer with the information needed to collect data about the system. 846 DB2 UDB for AS/400 SQL Programming V4R4 . and how the files can be used in applications. v DB2 Multisystem for AS/400 This guide describes the fundamental concepts of distributed relational database files. v REXX/400 Programmer’s Guide. SC09-1825 This guide provides information about using AS/400 PL/I in the System/38 environment. Differences between the System/38 environment and the AS/400 environment are identified as well as the enhancements available in the AS/400 environment. The book provides the information you need to create and use database files that are partitioned across multiple AS/400 systems. and maintain ILE C for AS/400 programs on the AS/400 system. and maintain REXX/400 programs on the AS/400 system. job.This guide provides information you need to design. in dynamic SQL 197 advanced coding technique complex search condition 72 inserting multiple rows into a table 69 joining data from multiple tables 75 advisor query optimizer index 482 aggregating functions 159 ALIAS statement 48 ALL 86 ALLOCATE clause performance implications 457 allocating storage for SQLDA 208 allow copy data (ALWCPYDTA) parameter 464 ALTER TABLE 93 ALWCPYDTA (allow copy data) parameter 464 ALWCPYDTA parameter effect on query optimimizer 423 AND keyword description 74 multiple search condition 74 ANY 86 API QSQCHKS 2 QSQPRCED 2 apostrophe C 249 C++ 249 application binding 344 dynamic SQL designing and running 199 overview 197 application design user-defined function (UDF) 185 application domain and object-orientation 145 application forms using CREATE TABLE example application plans 344 A access method dataspace scan 399 hashing access 415 index-from-index 414 index only access 412 key positioning 406 key selection 404 parallel data space scan 403 parallel key positioning 411 parallel key selection access method parallel pre-fetch 401 parallel pre-load 413 row selection method 397 summary table 420 access path definition 396 © Copyright IBM Corp.(minus) COBOL 255 %INCLUDE directive 291 PL/I 281 *APOST 254 *CNULRQD 232 /COPY ILE RPG for AS/400 312. 302 #include directive C 228 C++ 228 *NOCNULRQD 232 *NOCVTDT 317 *NOSEQSRC ILE RPG for AS/400 312 RPG for AS/400 299 #pragma mapinc directive C 245 C++ 245 *QUOTE 254 *SEQSRC ILE RPG for AS/400 312 RPG for AS/400 299 access path (continued) keyed sequence 396 sequential 396 temporary keyed from keyed access path 436 from the table 435 access plan 344 definition 11 in a package 12 in a program 11 validation 425 access plan rebuilt summary record 513 accessing remote databases interactive SQL 359 activation groups connection management example 561 add row to table 32 adding data to end of table 552 address variable.(dash) in COBOL host variable 255 . 1997. 1999 405 171 847 . 316 RPG for AS/400 299.Index Special Characters % (percent sign) use with LIKE 73 : (colon) C++ host variable 230 C host variable 230 COBOL 255 FORTRAN 841 ILE RPG for AS/400 313 PL/I 282 REXX 330 RPG for AS/400 300 . 380 auxiliary storage pools 368. 279 FORTRAN 837. 38 arranging rows 41 arrays of host structures using arrays C 241 C++ 241 COBOL 268 ILE RPG for AS/400 314 PL/I 289 RPG for AS/400 301 arrival sequence summary record 498 assignment rule date 218 host variable using 216 numeric assignment 218 string 217 time 218 timestamp 218 assignments in dynamic SQL example 175 assignments involving different UDTs example assignments involving UDTs example 175 asterisk (select all columns) 38 atomic operation data definition statements (DDL) 373 data integrity 373 definition 373 Auditing C2 security 366 authority. declaring 241 declaring 239 343 848 DB2 UDB for AS/400 SQL Programming V4R4 . affect on performance 461 72 C C++ program #include directive 228 #pragma mapinc directive 245 apostrophes 249 BEGIN/END DECLARE SECTION 230 coding SQL statements 225 comment 228 compiler parameters 341 continuation 228 dynamic SQL coding 226 error and warning message during a compile external file description 245 host structure array indicator structure. ILE 341 compiling. 192 arithmetic expression error 37. 845 ILE RPG for AS/400 309. 325 PL/I 279.application procedure coding SQL statements REXX 325 application program coding SQL statements C 225. 307 compiling. public 365 authorization Create SQL Package (CRTSQLPKG) command 558 for creating package 557 for running using a package 557 ID 366 testing 379. multiple search condition BETWEEN keyword 72 bibliography 845 Binary Large OBjects 146 binding 344 BLOBs (Binary Large OBjects) uses and definition 146 blocked insert statement 70 blocking. SQL improving performance 462 blocking consideration using. non-ILE 340 creating 9 SQLCA (SQL communication area) C 225 C++ 225 COBOL 251 FORTRAN 837 ILE RPG for AS/400 309 PL/I 279 RPG for AS/400 297 SQLDA C 226 C++ 226 COBOL 252 FORTRAN 838 ILE RPG for AS/400 310 PL/I 280 RPG for AS/400 298 testing SQL statements in 379 application requester 555 application requester driver (ARD) programs package creation 577 running statements 577 application server 555 ARD (application requester driver) programs 577 arithmetic error in UDFs 188. declaring 244 arrays. 295 RPG for AS/400 297. 251 C++ 225 COBOL 251. 378 AVG over a UDT example 164 176 B basic SQL statements and clauses 31 BEGIN DECLARE SECTION statement C 230 C++ 230 COBOL 255 FORTRAN 841 ILE RPG for AS/400 312 PL/I 282 RPG for AS/400 300 BETWEEN clause. declaring 228 SQLDA.C++ program (continued) indicator array 228 host variable 230 character 231 declaring 230 externally described 245 graphic 233 numeric 230 using pointers 244 INCLUDE statement 228 including code 228 margin 229 naming convention 229 null 229 preprocessor sequence 229 quotation marks 249 SQL data types determining equivalent C++ SQLCA. declaring 225 343 C program (continued) SQLCODE. 554 character host variable C 231 C++ 231 COBOL 258 Index 849 . 190. number using FETCH statement 462 cancelling a query 392 CAST FROM clause 188. declaring 225 SQLDA. declaring 244 arrays. 192 castability 157 casting. use in 97 definition 6 getting information about 97 column 98 integrity 377 LABEL ON information 48 QSYS2 views 6 table 97 CCSID connection to non-DB2 UDB for AS/400 561 delimited identifier effect 561 dynamic SQL statement 200 include file 334 package considerations 561 printer file 335 rule for using 217 source file 334 temporary source file 335 Change Class (CHGCLS) command 367 change information in table host variables 33. 236 externally described 245 graphic 233 numeric 230 using pointers 244 INCLUDE statement 228 including code 228 indicator structure 249 indicator variable 249 margin 229 naming convention 229 null 229 preprocessor sequence 229 quotation marks 249 SQL data types determining equivalent C 246 SQLCA. declaring 241 declaring 239 indicator array 241 host variable 230 character 231 declaring 230. passing to UDF 190 calls. declaring 226 SQLSTATE. declaring 225 SQLCODE. declaring 225 statement label 229 trigraph 229 union elements 230 WHENEVER statement 230 C2 security auditing 366 call level interface 2 call-type contents with table functions 190 call-type. declaring 226 SQLSTATE. declaring 225 statement label 229 trigraph 229 WHENEVER statement 230 C program 246 #include directive 228 #pragma mapinc directive 245 apostrophes 249 BEGIN/END DECLARE SECTION 230 coding SQL statements 225. UDFs 169 catalog database design. 251 comment 228 compiler parameters 341 continuation 228 dynamic SQL coding 226 error and warning message during a compile external file description 245 host structure array indicator structure. 34 Change Job (CHGJOB) command 367 Change Logical File (CHGLF) command 367 Change Physical File (CHGPF) command 367 Change Query Attribute (CHGQRYA) command 402 Change query attributes 543 Change Query Attributes (CHGQRYA) command 381 change session attributes interactive SQL 357 changing data 33 information in a table 25 query options file 546 table definition 93. character host variable (continued) FORTRAN 231 ILE RPG for AS/400 314. declaring 252 SQLSTATE. 315 numeric 255 including code 254 indicator structure 276 indicator variable 276 locator LOB 262. declaring 251 SQLDA. declaring 272 arrays. 303 Character Large OBjects 146 check constraints 99 check pending 107. 213 expression 39 joining tables 76 multiple search condition within 74 NOT keyword 40 WHERE CURRENT OF 61 CLI 2 CLOBs (Character Large OBjects) uses and definition 146 CLOSQLCSR parameter effect on implicit disconnect 565 using 469 COBOL program 272 BEGIN/END DECLARE SECTION 255 COBOL COPY statement 254. 375 checking syntax in interactive SQL 353 CHGPF command 33 CHGQRYA (Change Query Attributes) command 381 CL_SCHED table 585 class schedule table 585 clause 47 AND 74 DISTINCT 72 FROM 36 GROUP BY example 40 HAVING 42 INTO example 32 PREPARE statement. declaring 251 SQLCODE. 316 margin 254 multiple source programs 255 naming convention 254 REDEFINES 276 sample program with SQL statements 613 sequence numbers 254 SQL 613 SQL data types determining equivalent COBOL 274 SQLCA. declaring 268 declaring 264 indicator array 268 host variable 255 character 258 declaring 255. 318 PL/I 283 RPG for AS/400 300. 261 externally described 272 floating point 257 graphic 259 LOB 261. 279 comment 253 compile-time option 254 compiler parameters 340 continuation 253 Datetime host variable 263 debug lines 253 dynamic SQL coding 252 error and warning message during a compile 344 external file description 272 COBOL program 262 (continued) file reference variable LOB 262. SQL statements in COBOL 613 ILE C 606 ILE COBOL 613 ILE RPG for AS/400 program PL/I 621 REXX 640 REXX applications 327 RPG for AS/400 628 coding requirement C++ program comment 228 continuation 228 host variable 230 including code 228 margin 229 naming convention 229 null 229 preprocessor sequence 229 statement label 229 trigraph 229 WHENEVER statement 230 634 850 DB2 UDB for AS/400 SQL Programming V4R4 . 272 COBOL PROCESS statement 254 coding SQL statements 251. use with 202 restriction 208 NOT 74 null value 45 OR 74 ORDER BY 43 SELECT 38 SET 33 USING DESCRIPTOR 213 VALUES 31 WHENEVER NOT FOUND 60 WHERE character string 31 example 38. 316 host structure array indicator structure. declaring 251 statement label 255 WHENEVER statement 255 coded character set conversion error 38 coded character set identifier (CCSID) 217 coding examples. 6 solving problem paging through retrieved data 551 retrieving data a second time 553 colon in C++ host variable 230 in C host variable 230 in COBOL host variable 255 in FORTRAN host variable 841 in ILE RPG for AS/400 host variable 313 in PL/I host variable 282 in RPG for AS/400 host variable 300 column defining heading 16. 55.coding requirement (continued) C program comment 228 continuation 228 host variable 230 including code 228 indicator variable 249 margin 229 naming convention 229 null 229 preprocessor sequence 229 statement label 229 trigraph 229 WHENEVER statement 230 COBOL program COBOL PROCESS statement 254 comment 253 compile-time option 254 continuation 253 debug lines 253 host variable 255 indicator variable 276 margin 254 multiple source programs 255 naming convention 254 statement label 255 WHENEVER statement 255 FORTRAN program comment 839 continuation 839 debug lines 839 host variable 841 including code 840 indicator variable 844 margin 840 naming convention 840 statement label 840 WHENEVER statement 841 ILE RPG for AS/400 program comment 311 continuation 311 host variable 312 including code 312 indicator variable 322 naming convention 312 statement label 312 WHENEVER statement 312 PL/I program comment 281 continuation 281 host variable 282 including code 281 indicator variable 294 margin 281 naming convention 282 WHENEVER statement 282 RPG for AS/400 program comment 299 continuation 299 host variable 300 including code 299 coding requirement (continued) RPG for AS/400 program (continued) indicator variable 299 naming convention 299 statement label 300 WHENEVER statement 300 coding SQL statements in REXX applications 325 coding techniques 31. value 33 updating view 29 column functions 159 combining information from multiple tables 23 SELECT statement 80 subselect with UNION example 80 command CHGQRYA 543 CHGQRYA command 543 QAQQINI 543 QAQQINI command 543 RUNSQLSTM errors 362 command. 69 collating rows 41 collection changing table definition 554 creating 13 definition 3. 48 definition 3. CL Create Structured Query Language Package (CRTSQLPKG) 763 CRTSQLPKG (Create Structured Query Language Package) 763 Delete Structured Query Language Package (DLTSQLPKG) 782 DLTSQLPKG (Delete Structured Query Language Package) 782 command (CL) 819. 835 Change Class (CHGCLS) 367 Change Job (CHGJOB) 367 Change Logical File (CHGLF) 367 Index 851 . 6 FOR UPDATE OF clause 58 getting catalog information about 98 name definition 39 SET clause. 459. 302. 459. example 49 COMMIT keyword 370 prepared statements 201 statement 559 statement description 6 commitment control activation group example 561 committable updates 567 description 369 displaying 381 distributed connection restrictions 570 DRDA resource 567 INSERT statement 32 job-level commitment definition 565. 174 compile step warning 343 compile-time option COBOL 254 852 DB2 UDB for AS/400 SQL Programming V4R4 . 367. 461 TRCJOB (Trace Job) 382. 302. 784 QAQQINI 546 Reclaim DDM connections (RCLDDMCNV) 573 Retrieve Message (RTVMSG) 587 Revoke Object Authority (RVKOBJAUT) 365 RTVMSG (Retrieve Message) 587 Run SQL Statements (RUNSQLSTM) 1 command (CL) 1. 765 Create SQL PL/I (CRTSQLPLI) 728 Create SQL RPG (CRTSQLRPG) 744 Create User Profile (CRTUSRPRF) 366 CRTDUPOBJ (Create Duplicate Object) command 380 CRTUSRPRF (Create User Profile) 366 Delete Library (DLTLIB) 374 Delete Override (DLTOVR) 459 Delete SQL Package (DLTSQLPKG) 557. 367. 346. 461. 367 Override Database File (OVRDBF) 62. 462 Print SQL Information (PRTSQLINF) 345. 461. 570 protected resource 567 rollback required 572 RUNSQLSTM command 362 SQL statement processor 362 sync point manager 567 two-phase commit 567 unprotected resource 567 common database problem solving 551 comparison operators 40 comparisons involving UDTs example 173. 835 (continued) RUNSQLSTM (Run SQL statements) 367 RUNSQLSTM (Run SQL Statements) 361. 835 (continued) Change Physical File (CHGPF) 367 Change Query Attribute (CHGQRYA) command 402 Change Query Attributes (CHGQRYA) 381 CHGCLS (Change Class) 367 CHGJOB (Change Job) 367 CHGLF (Change Logical File) 367 CHGPF (Change Physical File) 367 CHGQRYA (Change Query Attribute) command 402 CHGQRYA (Change Query Attributes) 381 Convert SQL C++ (CVTSQLCPP) 781 Create Duplicate Object (CRTDUPOBJ) 380 Create Source Physical File (CRTSRCPF) command 335 Create SQL C++ (CRTSQLCPPI) 712 Create SQL COBOL (CRTSQLCBL) 661 Create SQL ILE C for AS/400 (CRTSQLCI) 695 Create SQL ILE COBOL (CRTSQLCBLI) 678 Create SQL ILE/RPG (CRTSQLRPGI) 761 Create SQL Package (CRTSQLPKG) 557. 783 Display Job (DSPJOB) 381 Display Journal (DSPJRN) 461 Display Message Description (DSPMSGD) 587 Display Module (DSPMOD) 345 Display Program (DSPPGM) 345 Display Program References (DSPPGMREF) 345 Display Service Program (DSPSRVPGM) 345 DLTLIB (Delete Library) 374 DLTOVR (Delete Override) 459 DSPJOB (Display Job) 381 DSPJRN (Display Journal) 461 DSPMSGD (Display Message Description) 587 Edit Check Pending Constraints (EDTCPCST) 375 Edit Rebuild of Access Paths (EDTRBDAP) 375 Edit Recovery for Access Paths (EDTRCYAP) 376 EDTCPCST (Edit Check Pending Constraints) 375 EDTRBDAP (Edit Rebuild of Access Paths) 375 EDTRCYAP (Edit Recovery for Access Paths) 376 Grant Object Authority (GRTOBJAUT) 365 GRTOBJAUT (Grant Object Authority) 365. 346.command (CL) 367. 393. 461 commands End Database Monitor (ENDDBMON) 480 Start Database Monitor (STRDBMON) 479 comment C 228 C++ 228 COBOL 253 for RUNSQLSTM 361 FORTRAN 839 getting 50 ILE RPG for AS/400 311 PL/I 281 REXX 328 RPG for AS/400 299 COMMENT ON statement using. 794 RVKOBJAUT (Revoke Object Authority) 365 Send Program Message (SNDPGMMSG) 587 Send User Message (SNDUSRMSG) 587 SNDPGMMSG (Send Program Message) 587 SNDUSRMSG (Send User Message) 587 Start Commitment Control (STRCMTCTL) 370 Start Journal Access Path (STRJRNAP) 376 STRCMTCTL (Start Commitment Control) 370 STRJRNAP (Start Journal Access Path) 376 STRSQL (Start SQL) 801 Trace Job (TRCJOB) 382. 462 OVRDBF (Override Database File) 62. 382. 559 interactive SQL 360 connection DDM 573 determining type 567 ending DDM 573 protected 567 unprotected 567 connection management ARD programs 577 commitment control restrictions 570 distributed unit of work considerations 572 ending connections DDMCNV effect on 573 DISCONNECT statement 573 RELEASE statement 573 example 561 implicit connection default activation group 565 nondefault activation group 566 implicit disconnection default activation group 565 nondefault activation group 566 216 connection management (continued) multiple connections to same relational database 577 connection status determining 570 example 576 consistency token 560 consistent behavior and UDTs 169 constant definition 39 SET clause.PROJECT (project) 584 CORPDATA.PROJECT table 584 correlated names 91 references 91 correlated subquery definition 88 Index 853 .DEPARTMENT (department) 579 CORPDATA. using SQL with host language host language.EMP_ACT (employee to project activity) 581 CORPDATA.EMP_ACT table 581 CORPDATA. value 33 constraint 375 definition 8 referential 8 unique 8 constraint mechanisms on large objects 145 constraints check 99 referential check pending 107 creating tables 100 delete rules 105 deleting from tables 105 inserting into tables 102 removing 102 update rules 103 updating tables 103 continuation C 228 C++ 228 COBOL 253 FORTRAN 839 ILE RPG for AS/400 311 PL/I 281 RPG for AS/400 299 control.compiled application program object managing object 9 output source file member 11 program 9 user source file member 11 compiling application program ILE 341 non-ILE 340 application program object output source file member 11 program 11 user source file member 11 error message 343 warning message 343 compiling a UDF 160 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.EMPLOYEE table 580 CORPDATA. using SQL with handling return code 221 host structure 220 host variable 215 SQLCODEs 221 SQLSTATEs 221 SQLSTATEs 221 concurrency data 367 definition 367 condition keyword for use in search 72 multiple search within a WHERE clause 74 performing complex search 72 CONNECT statement 555. commitment 369 control information to access large object data 147 control structures 12 controlling parallel processing 473 convention SQL naming 4 system naming 3 conversion error 37 Convert SQL C++ (CVTSQLCPP) command 781 copy of the data using to improve performance 465 COPY statement COBOL 254 externally described 272 CORPDATA. correlated subquery (continued) DELETE statement. use in 88 examples HAVING clause 90 UPDATE statement 91 WHERE clause 89 note on using 92 correlation definition 85 name 23. 468 rules for retaining 467 using to improve performance 467. 557. effect of recovery on 68 positions retaining across program call 467. 62 open 59 open. 468 retrieving SELECT statement result 212 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 781 D damage tolerance 376 dash in COBOL host variable 255 data adding to the end of table 552 854 DB2 UDB for AS/400 SQL Programming V4R4 . 79 using subquery 85 cost estimation query optimizer 423 cost of a UDT example 163 counter for UDFs example 194 counting and defining UDFs example 164 CREATE COLLECTION statement 13 CREATE DISTINCT TYPE statement and castability 157 examples of using 171 to define a UDT 170 Create Duplicate Object (CRTDUPOBJ) command 380 CREATE FUNCTION statement 190 to register a UDF 161 CREATE INDEX sort sequence 53 CREATE SCHEMA statement 362 Create Source Physical File (CRTSRCPF) command precompile use 335 Create SQL C++ (CRTSQLCPPI) command 712 Create SQL C (CRTSQLC) command 819 Create SQL COBOL (CRTSQLCBL) command 661 Create SQL FORTRAN (CRTSQLFTN) command 835 Create SQL ILE C for AS/400 (CRTSQLCI) command 695 Create SQL ILE COBOL (CRTSQLCBLI) command 678 Create SQL ILE/RPG (CRTSQLRPGI) command 761 Create SQL Package (CRTSQLPKG) command 340. 765 authority required 558 Create SQL PL/I (CRTSQLPLI) command 728 Create SQL RPG (CRTSQLRPG) command 744 Create Structured Query Language Package (CRTSQLPKG) command 763 CREATE TABLE prompting 353 CREATE TABLE statement 14 examples of using 171 Create User Profile (CRTUSRPRF) command 366 CREATE VIEW statement 29 creating collection example 13 index example 96 structured query language package 763 table description 14 example 14 creating (continued) view 13 description 28 on a table 29 over multiple tables 30 cross join 78 CRTDUPOBJ (Create Duplicate Object) command 380 CRTSQLC (Create SQL C) command 819 CRTSQLCBL (Create SQL COBOL) command 661 CRTSQLCBLI (Create SQL ILE/COBOL) command 678 CRTSQLCI (Create SQL ILE C for AS/400) command 695 CRTSQLCPPI (Create SQL C++) command 712 CRTSQLFTN (Create SQL FORTRAN) command 835 CRTSQLPKG (Create SQL Package) command 765 CRTSQLPKG (Create Structured Query Language Package) command 763 CRTSQLPLI (Create SQL PL/I) command 728 CRTSQLRPG (Create SQL RPG) command 744 CRTSQLRPGI (Create SQL ILE/RPG) command 761 CRTSQLxxx commands 3 CRTUSRPRF command create user profile 366 ctr() UDF C program listing 194 CURDATE scalar function 46 CURRENT DATE special register 45 current row 60 CURRENT SERVER special register 45 current session printing 357 removing all entries from 357 CURRENT TIME special register 45 CURRENT TIMESTAMP special register 45 CURRENT TIMEZONE special register 45 cursor distributed unit of work 576 example overview 56 example steps 58. passing to UDF 190 DBINFO keyword 190 dbminfo argument. 485 logical file DDS 493 physical file DDS 489 start 479 database monitor performance records 481 database query performance monitoring 478 dataspace definition 397 dataspace scan access method 399 date assignment rule host variable. 317 DATSEP ILE RPG for AS/400 313. using the catalog in 97 relational 3 database monitor end 480 examples 482. using 218 date format 47 specifying current value 47 date/time arithmetic 47 date/time host variable ILE RPG for AS/400 313 Datetime host variable COBOL 263 DATFMT ILE RPG for AS/400 313. processing 36 data definition statement (DDL) 4 data dictionary WITH DATA DICTIONARY clause CREATE COLLECTION statement 6 CREATE SCHEMA statement 6 data independence 32.data (continued) paging interactively displayed to improve performance 463 retrieved 551 retrieving in reverse order 551 selecting from multiple tables affect on performance 442 updating as it is retrieved 552 previously retrieved 553 view. open 388 data protection 365 data type determining equivalent C 246 C++ 246 COBOL 274 FORTRAN 842 ILE RPG for AS/400 318 PL/I 292 REXX 330 RPG for AS/400 303 data types BLOBs 146 CLOBs 146 DBCLOBs 146 object-oriented 145 database design. 317 DB2 Multisystem 2 DB2 Query Manager for AS/400 2 DB2 UDB for AS/400 1 C program 605 distributed relational database support 555 DB2 UDB for AS/400 sample table 579 DB2 UDB Query Manager and SQL Development Kit distributed relational database support 555 DB2 UDB Symmetric Multiprocessing 2 DB2 Universal Database considerations for packages 558 DBCLOBs (Double-Byte Character Large OBjects) uses and definition 146 DBCS (double-byte character set) considerations in interactive SQL 353 DBCS constants continuation C 228 C++ 228 COBOL 254 FORTRAN 839 ILE RPG for AS/400 311 PL/I 281 RPG for AS/400 299 in SQL source 334 DBGVIEW(*SOURCE) parameter 380 dbinfo. elements of 190 DDM (distributed data management) considerations 346 running a program with embedded SQL 346 DDS database monitor logical file 493 database monitor physical file 489 deadlock detection 367 debug lines COBOL 253 FORTRAN 839 debugging 379 common database problem 551 Index 1 855 . 38 data integrity 99 atomic operation 373 commitment control 369 concurrency 367 constraint 375 damage tolerance 376 data definition statements (DDL) 373 function 366 index recovery 376 journaling 368 save/restore 375 data items ILE RPG for AS/400 314 RPG for AS/400 300 data manipulation statement (DML) 4 data mapping error 37 data path. 9. use in 92 description 28. 34 Delete Structured Query Language Package (DLTSQLPKG) command 782 deleted rows getting rid of using REUSEDLT(*YES) 399 getting rid of using RGZPFM 399 deleting structured query language package 782 deleting information in a table 28 department table CORPDATA. 783 DELETE statement correlated subquery. 6 search condition 38 secondary tables 426 sequential access path 396 special register 40 SQL package 3 SQLCODE 587 SQLSTATE 587 stored procedure 8 subquery 84 symmetrical multiprocessing 397 table 3. 6 trigger 8 user profile 3 user source file member 11 USER special register 45 view 3. 6 column 3. 557 parallel data space scan method 403 parallel key positioning access method 411 parallel key selection access method 405 parallel pre-fetch access method 401 physical file 3 predicate 38 primary table 426 program 11 record 3 referential integrity 8 remote unit of work 555 row 3.DEPARTMENT 579 DESCRIBE statement use with dynamic SQL 201 856 DB2 UDB for AS/400 SQL Programming V4R4 . value 34 default value 14. 48 table name 48 defining the UDT and UDFs example 178 definitions 555 access path 396 access plan 11.debugging 551 (continued) program 551 DECLARE CURSOR statement using 36 DECLARE statement 198 default collection name (DFTRDBCOL) parameter default filter factors 424 DEFAULT keyword SET clause. 344 authorization ID 3 authorization name 3 binding 344 catalog 6 collection 3. 215 implementation cost 423 index 8 index-from-index access method 414 index only access method 412 indicator structure 220 indicator variable 219 isolatable 437 join 30 join operation 23 journal 6 journal receiver 6 3 definitions 406 (continued) key positioning access method 396 key selection access method 404 keyed sequence 396 library 3 logical file 3 miniplan 425 NULL value 40 null value 45 open data path 388 outer-level SELECT 84 output source file member 11 package 3. 6 column name 39 concurrency 367 constant 39 constraint 8 correlated subquery 88 correlation 85 CURRENT DATE special register 45 current row 60 CURRENT SERVER special register 45 CURRENT TIME special register 45 CURRENT TIMESTAMP special register 45 CURRENT TIMEZONE special register 45 data definition statement (DDL) 4 data dictionary 6 data manipulation statement (DML) 4 dataspace 397 default filter factors 424 dial 426 distributed unit of work 555 expression 39 field 3 hashing access method 415 host structure 215 host variable 39. 32 inserting in a view 96 define cursor 58 defining column heading 16. 12. 7 delete current row 61 Delete Library (DLTLIB) command 374 Delete Override (DLTOVR) command 459 Delete SQL Package (DLTSQLPKG) command 557. 18. use in 202 DESCRIBE statement 201 EXECUTE statement 199 FETCH. C for AS/400 external file 803 descriptor-name in REXX 325 designing dynamic SQL application 199 detail record records retrieved 523 DFT_SQLMATHWARN configuration parameter 188. 566. 570 connection management 561 multiple connections 565 connection restrictions 570 connection type determining 567 protected 567 unprotected 567 consideration for creating packages 558 creating packages 558 DB2 UDB for AS/400 support 555 determining connection status 570 distributed RUW example program 556 distributed unit of work 555. 573 ending connections DDMCNV effect on 573 DISCONNECT statement 573 RELEASE statement 573 first failure data capture (FFDC) 578 implicit connection default activation group 565 nondefault activation group 566 implicit disconnection default activation group 565 nondefault activation group 566 interactive SQL 359 distributed relational database (continued) packages 359 statement in 558 precompiler diagnostic messages 558 problem handling 578 protected connection 567 protected resource 567 remote unit of work 555.DESCRIBE TABLE statement 559 description SQLCODEs and SQLSTATEs 589 descriptions. 566 rollback required state 572 session attributes 360 SQL packages 557 sync point manager 567 two-phase commit 567 unprotected connection 567 unprotected resource 567 valid SQL statements 558 Distributed Relational Database Architecture (DRDA) 1 distributed unit of work 555. multiple-row ILE RPG for AS/400 323 fixed-list SELECT statement. using 202 parameter marker 213 PREPARE statement 199 processing non-SELECT statements 199 Index 857 . 573 connection considerations 572 connection status 570 connection type 567 cursors 576 prepared statements 576 sample program 574 DLTSQLPKG (Delete SQL Package) command 783 DLTSQLPKG (Delete Structured Query Language Package) command 782 Double-Byte Character Large OBjects 146 DRDA (Distributed Relational Database Architecture) 555 DRDA level 1 566 DRDA level 2 566 DRDA resource 567 DROP PACKAGE statement 555 DSPJOB (Display Job) command 381 duplicate rows eliminating 81 preventing 71 DUW (distributed unit of work) 555 dynamic SQL address variable 197 allocating storage 203 application 197. 566. 192 DFTRDBCOL (default collection name) parameter 3 diagnostic-message. 559 ending connection 573 Display Job (DSPJOB) command 381 Display Journal (DSPJRN) command 461 Display Message Description (DSPMSGD) command 587 Display Module (DSPMOD) 345 Display Program (DSPPGM) command 345 Display Program References (DSPPGMREF) command 345 Display Service Program (DSPSRVPGM) 345 displaying SQLCODE and SQLSTATE description 587 DISTINCT 71 clause 72 keyword 553 distinct type 157 distributed data management (DDM) 346 distributed relational database accessing remote databases 359 application requester 555 application server 555 committable updates 567. passing to UDF 189 DISCONNECT statement 555. 199 building and running statements 197 CCSID 200 coding in C 226 coding in C++ 226 coding in COBOL 252 coding in FORTRAN 838 coding in ILE RPG for AS/400 310 coding in PL/I 280 coding in RPG for AS/400 298 cursor. 125 EXISTS 87 exploiting LOB function to populate the database 179 exploiting LOB locators to manipulate UDT instances 180 exploiting UDFs to query instances of UDTs 179 exponentiation and defining UDFs 161 extracting a document to a file (CLOB elements in a table) 152 function invocations 165 getting catalog information about column 98 table 97 getting comment 50 getting information about column using catalog 97 858 DB2 UDB for AS/400 SQL Programming V4R4 . UPDATE statement 253 COMMENT ON 49 comparisons involving UDTs 173. 174 correlated subquery HAVING clause 90 WHERE clause 89 correlation name 23 cost of a UDT 163 counter for UDFs 194 counting and defining UDFs 164 creating collection 13 index 96 table 14 view on a table 29 views over multiple tables 30 ctr() UDF C program listing 194 CURRENT DATE 47 CURRENT TIMEZONE 47 cursor 56 cursor in DUW program 576 database monitor 482. handling general 221 establishing position at end of table 551 examples 49. 220 (continued) AND 74. 34 COBOL. 50. 344 PL/I program 343 RPG program 343. 75 application forms using CREATE TABLE 171 assignments in dynamic SQL 175 assignments involving different UDTs 176 assignments involving UDTs 175 AVG over a UDT 164 BETWEEN 72 catalog getting column information 97 getting table information 97 changing information in a table 25 changing rows in table host variables 33.dynamic SQL (continued) replacing parameter markers with host variables 197 run-time overhead 197 statements 4 varying-list SELECT statement 201 E Edit Check Pending Constraints (EDTCPCST) command 375 Edit Rebuild of Access Paths (EDTRBDAP) command 375 Edit Recovery for Access Paths (EDTRCYAP) command 376 eliminating duplicate rows 81 embedded SQL C 227 C++ 227 COBOL 253 FORTRAN 839 ILE RPG for AS/400 311 PL/I 280 precompiling 333 RPG for AS/400 298 running a program with 346 employee-to-project activity table 581 encapsulation and UDTs 169 End Database Monitor (ENDDBMON) command 480 END DECLARE SECTION statement C 230 C++ 230 COBOL 255 FORTRAN 841 ILE RPG for AS/400 312 PL/I 282 RPG for AS/400 300 end-of-data reached 59 ENDDBMON (end database monitor) command 480 entering DBCS data 353 ERRLVL 362 error data mapping ORDER BY 37 error determination in distributed relational database first failure data capture (FFDC) 578 error message during a compile 343 C++ program 343 C program 343 COBOL program 343. 50. 485 defining stored procedures with CREATE PROCEDURE 117 defining the UDT and UDFs 178 deleting information in a table 28 determining connection status 576 distributed RUW program 556 distributed unit of work program 574 dynamic CALL 127 embedded CALL 124. 344 error message during precompile displayed on listing 335 error return code. 220 examples 74. SQB COBOL program listing 150 LOBLOC. 48 LIKE 73 list function in interactive SQL 354 LOBFILE. value 33 using in the WHERE clause 39 extended dynamic QSQPRCED 2 extensibility and UDTs 169 external file description C 245 C++ 245 C for AS/400 803 COBOL 272 host structure arrays COBOL 273 ILE RPG for AS/400 317 RPG for AS/400 303 ILE RPG for AS/400 316 PL/I 291 RPG for AS/400 302 extracting a document to a file (CLOB elements in a table) example 152 F failed session. recovering 358 Index 859 . 327 EXECUTE IMMEDIATE statement 199 EXECUTE privileges for packages 557 EXECUTE statement 199.SQB COBOL program listing 153 LOBFILE. 50.examples 97. 220 (continued) Union simple 83 UNION using host variables 81 UNION ALL using host variables 83 unqualified function reference 167 UPDATE statement 25 use of UDTs in UNION 177 user-defined sourced functions on UDTs 175 using a locator to work with a CLOB value 148 using index 96 using qualified function reference 166 variable declaration 276 view sort sequence 53 WITH CASCADED CHECK OPTION 110 WITH LOCAL CHECK OPTION 110 working with index 96 exception condition 222 exception join 77 EXECSQL REXX command 325. COBOL 336 parameter markers in functions 166 performance analysis 483. 220 (continued) table using catalog 74 getting information from multiple tables 23 single table 20 governor 394 host variable in SQL statement 215 IN 73 index 446 inserting add row to table 32 multiple rows into a table 69 inserting data into a CLOB column 154 invoking stored procedures 127 where a CREATE PROCEDURE exists 124 where no CREATE PROCEDURE exists 125 join 76 LABEL ON statement 16. 50.SQC C program listing 149 money using CREATE DISTINCT TYPE 171 multiple search condition (WHERE clause) 74 OR 75 ORDER BY sort sequence 51 output from precompiler. use in subquery 87 exiting interactive SQL 357 exploiting LOB function to populate the database example 179 LOB locators to manipulate UDT instances example 180 UDFs to query instances of UDTs example 179 exponentiation and defining UDFs example 161 expression definition 39 SET clause. 484 preventing duplicate rows 71 QSYSPRT listing SQL statement processor 363 reducing the number of open database operation 459 removing information from table 28. 34 resume using CREATE DISTINCT TYPE 171 returning completion status to calling program 135 RPG for AS/400 declare variable 306 sales using CREATE TABLE 171 sample table 579 search 72 search string and BLOBs 162 SELECT records sort sequence 52 SELECT statement allocating storage for SQLDA 208 selecting data from multiple tables 442 selecting into table host variables 36 special register 47 stored procedures returning completion status 135 string search and defining UDFs 162 string search over UDT 163 subquery 84 examples 83.SQC C program listing 153 LOBLOC. 200 EXISTS keyword. declaring 837 statement label 840 WHENEVER statement 841 FROM clause 36 function interactive SQL 349 function invocations example 165 function-name. declaring 837 SQLCOD. SQLDA 204 FORTRAN program BEGIN/END DECLARE SECTION 841 coding SQL statements 837. 316 file reference variables examples of using 152 for manipulating LOBs 146 input values 151 LOB PL/I 286 output values 152 filter factors. declaring 837 SQLSTA. summary for UDFs 167 function selection algorithm and UDFs 158 functions aggregating functions 159 column functions 159 scalar functions 159 syntax for referring to 165 table functions 159 G generic query information summary record 520 getting catalog information about column 98 table 97 comment 50 information from multiple table 23 from single table 20 governor 391 *DFT 393 *RQD 393 *SYSRPYL 393 CHGQRYA 391 JOB 392 QRYTIMLMT 391 time limit 392 Grant Object Authority (GRTOBJAUT) command GRANT PACKAGE statement 555 graphic host variable C 233 C++ 233 COBOL 259 ILE RPG for AS/400 318 GROUP BY clause 40 keyword 553 using null value with 41 grouping optimization 442 grouping the row you select 41 365 860 DB2 UDB for AS/400 SQL Programming V4R4 . declaring 837 SQLSTATE. 845 comment 839 compile-time options 841 continuation 839 debug lines 839 dynamic SQL coding 838 host variable 841 character 842 declaring 841.FETCH using host structure array multiple-row 63 FETCH statement 212 multiple-row ILE RPG for AS/400 314. declaring 837 SQLCODE. 323 RPG for AS/400 301 FFDC (first failure data capture) 578 field 3 file query options 546 file description external C 245 C++ 245 C for AS/400 803 COBOL 272 ILE RPG for AS/400 316 PL/I 291 RPG for AS/400 302 host structure arrays COBOL 273 ILE RPG for AS/400 317 RPG for AS/400 303 file reference variable LOB COBOL 262. default in query optimization 424 first failure data capture (FFDC) 578 fixed-list SELECT statement definition 201 using 201 flexibility and UDTs 169 floating point host variable COBOL 257 FOR UPDATE OF clause restrictions 58 format. passing to UDF 189 function path and UDFs 158 function references. 842 numeric 841 IMPLICIT statement 841 including code 840 indicator variable 844 FORTRAN program (continued) margin 841 naming convention 840 PROCESS statement 841 SQL data types determining equivalent FORTRAN 842 SQLCA. 318 Datetime COBOL 263 definition 39.H halfword binary integer (SMALLINT) 218 handling error return code SQLCODEs and SQLSTATEs 221 exception condition (WHENEVER statement) hash join 427 hashing access method 415 HAVING clause 42 host language concepts and rules 215 host structure C 239 C++ 239 COBOL 264 definition 215 ILE RPG for AS/400 314 indicator array C 241. 303 COBOL 255 date/time ILE RPG for AS/400 313. rule 217 host variable and ODP implementation summary record 518 I ID. sample 606 ILE COBOL program sample program with SQL statements 613 SQL 613 ILE programs package 559 Index 861 . 244 COBOL 268. time. 315 PL/I 284 numeric C 230 C++ 230 COBOL 255 FORTRAN 841 ILE RPG for AS/400 318 PL/I 283 RPG for AS/400 303 PL/I 282 declaring 282 requirement for COBOL program 255 requirement for ILE RPG for AS/400 312 requirement for PL/I program 282 REXX 330 RPG for AS/400 300 declaring 300 SET clause. and timestamp assignment 218 rule for numeric assignment 218 string assignment. 215 222 host variable 245 (continued) external file description C 245 C++ 245 COBOL 272 ILE RPG for AS/400 316 PL/I 291 RPG for AS/400 302 floating point COBOL 257 FORTRAN 841 declaring 841 general use in SQL statement 215 graphic C 233 C++ 233 COBOL 259 ILE RPG for AS/400 318 ILE RPG for AS/400 312 declaring 313 LOB COBOL 261. 272 PL/I 288. 318 PL/I 283 RPG for AS/400 300. use in rule for date. 290 PL/I 286 RPG for AS/400 300 used to set null value 220 using arrays C 241 C++ 241 COBOL 268. 244 C++ 241. value 33 SQL statement. example 220 host structure array multiple-row FETCH 63 host structure indicator array C 241 C++ 241 COBOL 268 PL/I 288 host variable 230 assignment rule 216 C 230 using pointers 244 C++ 230 using pointers 244 character C 231 C++ 231 COBOL 258 FORTRAN 842 ILE RPG for AS/400 314. authorization 366 IDDU (interactive data definition utility) 6 ILE (Integrated Language Environment) compiling application 341 ILE C program SQL statements in. 273 ILE RPG for AS/400 314 PL/I 289 RPG for AS/400 301 using indicator variable with. 316 character host variables 314 coding SQL statements 309. 325 comment 311 compiler parameters 341 continuation 311 dynamic SQL coding 310 error and warning message during a compile 344 external file description 316 host structure declaring 314 host structure array declaring 314 host variable 312 character 318 date/time 313. 465 blocking. 290 862 DB2 UDB for AS/400 SQL Programming V4R4 . 244 COBOL 268. 272 PL/I 288. 318 declaring 313 externally described 316 graphic 318 numeric 318 including code 312 indicator structure 322 indicator variable 322 naming convention 312 notes and usage 322 occurrence data structure 314 sequence numbers 312 SQL data types determining equivalent RPG 318 SQL statements in sample 634 SQLCA 309 SQLCA placement 309 SQLDA example 323 SQLDA. declaring 310 statement label 312 variable declaration 322 WHENEVER statement 312 ILE RPG program SQLCA placement 605 ILE service programs package 559 immediate sensitivity 63. use in 87 in tray table 585 IN_TRAY table 585 include file C 228 C++ 228 CCSID 334 COBOL 254 ILE RPG for AS/400 312 input to precompiler 334 PL/I 281 RPG for AS/400 299 INCLUDE statement 334 C 228 C++ 228 COBOL 254 ILE RPG for AS/400 312 PL/I 281 RPG for AS/400 299 including code C 228 C++ 228 COBOL 254 COBOL COPY statement 254 FORTRAN 840 ILE RPG for AS/400 312 PL/I 281 RPG for AS/400 299 index columns used for keys 396 creating from another index 414 definition 8 recovery 376 using 96 using effectively. using effectively 464 selecting data from multiple tables 442 SQL blocking 462 improving performance 467. 67 implementing a UDF 160 implicit connect 565 implicit disconnect 565 IMPLICIT statement FORTRAN 841 improving performance 464. 244 C++ 241. 465 (continued) using close SQL cursor (CLOSQLCSR) 467.ILE RPG for AS/400 program /COPY statement 312. 468 FETCH FOR n ROWS 462 INSERT n ROWS 463 parameter passing techniques 472 precompile options 471 IN keyword description 73 subquery. example 446 working with 96 index advisor query optimizer 482 index created summary record 505 index-from-index access method 414 index only access method 412 indexes using with sort sequence 449 indicator array C 241. 468 SELECT statements. using 461 join queries 439 paging interactively displayed data 463 PREPARE statement 470 retaining cursor positions across program call 467. storing 145 Integrated Language Environment (ILE) module 12 program 11 service program 12 integrity catalog 377 data 99. 358 interactively displayed data. 390 performance 382. 570 join cross 78 definitions 30 exception 77 hash 427 inner 75 left outer 76 optimization 426 join operation definition 23 in a view 30 join optimization performance tips 439 join order optimization 432 join position 385 join secondary dials costing 432 joining data from multiple tables 75 table with WHERE clause 76 technique 79 journal 6 journal receiver 6 journaling 368 K key positioning access method 406 Index 863 . paging affect on performance 463 INTO clause description 32 PREPARE statements 202 restriction 208 invoking UDFs 164 J JOB 392 job attribute DDMCNV 573 job-level commitment definition 565. 357 statement entry 349. 32 description 31 VALUES clause 31 inserting information into table 18 multiple rows into tables 69 note 70 inserting data into a CLOB column example 154 instances of object-oriented data types. 366 referential 99 interactive data definition utility 6 interactive interface concepts 1 Interactive SQL 1 interactive SQL accessing remote databases 359 Interactive SQL adding DBCS data 353 interactive SQL change session attributes 357 description 349 exiting 357 interactive SQL (continued) function 357 general use 349 getting started 350 overview 349 package 360 Interactive SQL prompting 354 interactive SQL prompting DBCS consideration 353 overview 349 session services 349. example 220 with host structure 220 indicator variables stored procedures 132 indicator variables and LOB locators 151 infix notation and UDFs 168 information. 356. 388 inner join 75 INSERT n ROWS improving performance 463 INSERT statement blocked 31 ILE RPG for AS/400 314 RPG for AS/400 301 column value 216 default value 18. inserting into table 18 information messages open data path 388. 351 statement processing mode 353 Interactive SQL syntax checking 353 interactive SQL terminology 3 testing your SQL statements with 349.indicator structure 220 indicator variable C 249 C++ 249 COBOL 276 definition 219 FORTRAN 844 ILE RPG for AS/400 322 PL/I 294 REXX 332 RPG for AS/400 306 used to set null value 220 used with host structure. SQC C program listing 149 LOBs (Large Objects) and DB2 object extensions 145 file reference variables 146 examples of using 152 input values 151 output values 152 SQL_FILE_APPEND. 315 PL/I 284 LOB locator COBOL 262.SQC C program listing 153 LOBLOC. 553 UNION ALL. specifying 83 L LABEL ON statement 16. 316 LOB locators PL/I 285 LOBEVAL. output value option 152 SQL_FILE_OVERWRITE. time 392 linking a UDF 160 list function 356 list function in interactive SQL description 354 listing output from precompiler 335 live data using to improve performance 464 LOB file reference variable COBOL 262. 316 LOB file reference variables PL/I 286 LOB host variable COBOL 261. use in 72 UNION 80. 316 locators LOB PL/I 285 locators for manipulating LOBs 146 locks analyzing 381 logical file 3.SQB COBOL program listing 153 LOBEVAL. output value option 152 SQL_FILE_CREATE.SQB COBOL program listing 150 LOBLOC. parameter 213 maximum size for large object columns. 87 LIKE 73 NOT 40 OR 74 search condition. 7 logical file DDS database monitor 493 long object names performance 470 LONG VARCHAR storage limits 146 LONG VARGRAPHIC storage limits 146 Loosely Coupled Parallelism 2 LR indicator ending RPG for AS/400 programs 307 M manipulating large objects 145 mapping error data 37 margins C 229 C++ 229 COBOL 254 FORTRAN 840 PL/I 281 REXX 329 MARGINS parameter C 229 C++ 229 marker. 48 information in catalog 48 package 560 language.key range estimate 424 key selection access method 404 keyed sequence access path 396 keyword AND 74 BETWEEN 72 COMMIT 370 DISTINCT 553 EXISTS 87 GROUP BY 553 IN 73. 147 example of using 148 indicator variables 151 manipulating 145 programming options for values 147 storing 145 synergy with UDTs and UDFs examples of complex applications 177 locator LOB COBOL 262. input value option 152 large object descriptor 146 large object value 146 locators 146. host concepts and rules 215 large object descriptor 146 large object value 146 learn how to prompt using interactive SQL 354 leaving interactive SQL 357 left outer join 76 library definition 3 LIKE keyword 73 limit. output value option 152 SQL_FILE_READ. defining 147 864 DB2 UDB for AS/400 SQL Programming V4R4 . using 218 numeric conversion error 38 numeric host variable C 230 C++ 230 COBOL 255 FORTRAN 841 ILE RPG for AS/400 318 PL/I 283 RPG for AS/400 303 O object application program 9 collection 3 module 9 Integrated Language Environment (ILE) package 9 program Integrated Language Environment (ILE) service program 9 Integrated Language Environment (ILE) SQL 5 object-orientation and UDFs 156 object-oriented extensions and UDTs 169 12 11 12 199 Index 865 . value 33 UPDATE statement 33 used with GROUP BY clause 41 used with ORDER BY clause 44 null value. 390 performance information 382. processing NOT keyword 40. 388 running in debug mode 382 minus COBOL 255 mode interactive SQL 353 modelling entities as independent objects 145 module Integrated Language Environment (ILE) object 12 money using CREATE DISTINCT TYPE example 171 monitor (ENDDBMON) command. 74 NOW scalar function 46 NUL-terminator C 232 C++ 232 character host variables C 231 C++ 231 null usage in C 229 usage in C++ 229 null string in REXX 329 NULL value 14 null value 45 NULL value definition 40 null value INSERT statement 32 inserting in a view 96 set by indicator variable 220 SET clause. end database 480 monitoring database query performance 478 moving large objects using a file reference variable 146 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 442 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 229 C++ 229 COBOL 254 FORTRAN 840 ILE RPG for AS/400 312 PL/I 282 REXX 329 RPG for AS/400 299 SQL 4 system 3 negative SQLCODEs 591 nested loop join 426 new release considerations 346 non-SELECT statements. SQL contrasted with null value in REXX 329 number of calls using a FETCH statement 462 number of open database operations improving performance by reducing 459 numbers sequence COBOL 254 ILE RPG for AS/400 312 RPG for AS/400 299 numeric assignment rule host variable.member output source file 11 user source file 11 message analyzing error and warning messages 343 cause and user response 382 error and warning during a compile 343 open data path information 388. 557 Delete SQL Package (DLTSQLPKG) command 557 deleting 557 interactive SQL 360 labeling 560 restore 560 save 560 SQL statement size 559 statements that do not require package 559 page fault 397 paging interactively displayed data 463 retrieved data 551 parallel data space scan access method 403 parallel key positioning access method 411 parallel key selection access method 405 parallel pre-fetch access method 401 parallel pre-load index-based 413 table-based 413 parallel processing controlling in jobs (CHGQRYA command) 474 system wide (QQRYDEGREE) value 474 parameter markers in functions example 166 866 DB2 UDB for AS/400 SQL Programming V4R4 . interactive SQL 349 P package authority to create 557 authority to run 557 bind to an application 9 CCSID considerations for 561 consistency token 560 Create SQL Package (CRTSQLPKG) command 557 authority required 558 creating authority required 557 effect of ARD programs 577 errors during 558 on local system 560 RDB parameter 557 RDBCNNMTH parameter 560 TGTRLS parameter 559 type of connection 560 unit of work boundary 560 creating on a non-DB2 UDB for AS/400 errors during 558 required precompiler options for DB2 Common Server 558 unsupported precompiler options 558 DB2 UDB for AS/400 support 557 definition 9. 12. 346. 367. precompile improving performance by using 471 ORDER BY clause 43 using null values with 44 data mapping errors 37 sort sequence.object-relational application domain and object-orientation 145 constraint mechanisms 145 data types 145 definition 145 LOBs 145 support for 146 triggers 145 UDTs and UDFs 145 why use the DB2 object extensions 145 occurrence data structure ILE RPG for AS/400 314 RPG for AS/400 301 ODBC 199 ODP (open data path) 459 ODP implementation and host variable summary record 518 open closing 459 determing number 461 effect on performance 459 reducing number 459 open cursor during a unit of work 68 open data path 459 definition 388 information messages 388 open database connectivity (ODBC) 199 OPEN statement 213 operation. comparison 40 OPNQRYF (Open Query File) command 477 optimization 395 grouping 442 join 426 join order 432 nested loop join 426 OPTIMIZE FOR n ROWS clause effect on query optimizer 423 optimizer operation 422 query index advisor 482 optimizer timed out summary record 515 options. using 50 using 51 outer join 76 outer-level SELECT 84 output all queries that performed table scans 484 SQL queries that performed table scans 483 output source file member definition 11 overloaded function names and UDFs 158 override consideration running a program with embedded SQL 346 Override Database File (OVRDBF) command 62. 462 used with RPG for AS/400 /COPY 302 overview. 459. atomic 373 operators. declaring 279 SQLDA. declaring 279 SQLCODE. 390 OPNQRYF 477 optimizing 477 tools 477 UDFs 156 using long object names 470 performance analysis example 1 483 example 2 484 example 3 484 performance and UDTs 169 performance considerations 393. using effectively 464 selecting data from multiple tables 442 SQL blocking 462 using copy of the data 465 using INSERT n ROWS 463 using live data 464 using precompile options 471 performance records database monitor 481 performance verification 381 performing complex search condition 72 physical file 3. declaring 279 structure parameter passing 294 WHENEVER statement 282 pointer C 244 C++ 244 positive SQLCODEs 589 pre-fetching 399 precompile options improving performance.parameter passing differences 473 PL/I 294 RPG for AS/400 307 stored procedures 128. 192 SQL-state 188 path. 468 SELECT statements. 291 BEGIN/END DECLARE SECTION 282 coding SQL statements 279. 459 performance improvement blocking. 6 physical file DDS database monitor 489 PL/I SQL statements in. declaring 280 SQLSTATE. 192 SQL-result-ind 188. 465 CLOSQLCSR (close SQL cursor) 467. 132 table 128 parameters marker 213 parameters. using 471 precompiler basic process 333 complete diagnostics 334 concepts 1 diagnostic messages 558 diagnostics 335 displaying options 345 errors 343 Index 343 867 . 284 externally described 291 LOB 284 numeric 283 INCLUDE statement 281 including code 281 indicator structure 294 indicator variable 294 locators LOB 285 margin 281 naming convention 282 SQL data types determining equivalent PL/I 292 SQLCA. 468 passing argument to UDF call-type 190 dbinfo 190 diagnostic-message 189 function-name 189 scratchpad 190 specific-name 189 SQL-argument 190. declaring 289 declaring 286 indicator array 288 host variable 282 character 283 declaring 282. 295 comment 281 compiler parameters 340 continuation 281 dynamic SQL coding 280 error and warning message during a compile external file description 291 file reference variables LOB 286 host structure array indicator structure. declaring 290 arrays. 191 SQL-argument-ind 188 SQL-argument-ind-array 191 SQL-result 190. 388 monitoring 477 monitoring query 478 open data path messages 388. sample 621 PL/I program %INCLUDE directive 281. using 461 paging interactively displayed data 463 PREPARE statement 470 reducing number of open database operation 459 retaining cursor positions across program call 467. command ALWCPYDTA (allow copy data) 464. open data 388 pending check 107 performance 395 information messages 382. 317 DATSEP 313. 234. 234. 341 CRTSQLFTN 835 CRTSQLPLI 281. 232. 334. 340 CRTSQLRPG 340 CRTSQLRPGI 341 CRTSQLxxx 51. 317 predicate definition 38 transitive closure 436 Predictive Query Governor 391 PREPARE statement improving performance 470 non-SELECT statement 200 restrictions 199 using 213 prepared statement distributed unit of work 576 preparing program with SQL statements 333 preprocessor usage with SQL C++ program 229 usage with SQL C program 229 with SQL 334 preventing duplicate rows 71 Print SQL Information (PRTSQLINF) 345. 343 C 229 C++ 229 OBJ 335 OBJTYPE(*MODULE) 341 OBJTYPE(*PGM) 341 OBJTYPE(*SRVPGM) 341 OPTION(*APOST) 254 OPTION(*CNULRQD) 232. 335 OUTPUT 334 parameters passed to compiler 340 PGM 335 PRTFILE 335 RDB Effect on precompile 333 TIMFMT 313. 232. 232. 234 precompiler parameter (continued) OPTION(*NOGEN) 316. 341 default 468 description 340 precompiler file QSQLTEMP 335 QSQLTEMP1 335 precompiler parameter *CVTDT 316 *NOCVTDT 316. 558 CVTSQLCPP 229. 341 CRTSQLCPPI 229. 317 TIMSEP 313. 341 OPTION(*NOSEQSRC) 312 OPTION(*SEQSRC) 299 OPTION(*QUOTE) 254 OPTION(*SEQSRC) 312 OPTION(*SOURCE) 334 OPTION(*XREF) 334. 393 printer file 335 CCSID 335 printing current session 357 problem handling 221 problems join query performance 438 problems. 234. basic precompiler 333 PROCESS statement COBOL 254 FORTRAN 841 processing data in a view 36 non-SELECT statements 199 SELECT statement with SQLDA 201 producing reports from sample programs 643 program application 379 compiling application ILE 341 non-ILE 340 debugging 380 definition 11 Integrated Language Environment (ILE) object 11 non-ILE object 11 performance verification 381 868 DB2 UDB for AS/400 SQL Programming V4R4 . 317 ALWCPYDTA 464 CLOSQLCSR 469 DATFMT 313.precompiler (continued) include file CCSID 334 input to 334 other preprocessors 334 output from listing 335 sample 336 temporary source file member 335 parameters passed to compiler 340 passing host variables 472 record number 337 reference column 339 secondary input 334 sequence number 337 source file CCSID 334 containing DBCS constants 334 margins 334 source record 337 VisualAge C++ for OS/400 342 warning 343 precompiler command CRTSQLC 819 CRTSQLCBL 340 CRTSQLCBLI 341 CRTSQLCI 229. solving database 551 process. 382. 234 OPTION(*CVTDT) 316 OPTION(*NOCNULRQD) 232. 317 DBGVIEW(*SOURCE) 380 displayed on listing 335 INCFILE 334 MARGINS 281. 354 prompting CREATE TABLE 353 function 349. 559 ending connection 573 remote databases accessing from interactive SQL 359 remote unit of work 555. 351 overview 349 subqueries 353 protected connections dropping 570 protected resource 567 protection. journal 6 Reclaim DDM connections (RCLDDMCNV) command 573 record. data 365 PRTSQLINF (Print SQL Information) command 784 public authority 365 Query options file 543 query options file changing 546 query performance monitoring 478 query sort summary record 508 query time limit 392 quotation mark C 249 C++ 249 R re-use and UDFs 156 read-only table 59 view 96 read-only connection 567 receiver. definition 3 record selection 52 sort sequence. program 345 referential constraints check pending 107 creating tables 100 definition 8 delete rules 105 deleting from tables 105 inserting into tables 102 removing 102 update rules 103 updating tables 103 referential integrity 99 definition 8 registering UDFs 160 related information 845 relational database 3 RELEASE statement 555.program (continued) preparing and running with SQL statements 379 reference 345 report produced by sample 643 running with embedded SQL DDM consideration 346 instruction 346 override consideration 346 return code 347 sample 605 SQL statements in COBOL 613 ILE C 606 ILE COBOL 613 ILE RPG for AS/400 program 634 PL/I 621 REXX 640 RPG for AS/400 628 program calls rules for retaining cursor positions 469 project table 584 prompt using interactive SQL 349. using 50 records database monitor performance 481 records retrieved detail record 523 recovering effect on open cursor 68 index 376 interactive SQL saved or failed session 358 reducing number of open database operations improving performance. example 459 reference. 566 connection status 570 connection type 567 example program 556 Index Q QAQQINI 546 QDT 425 QRYTIMLMT parameter CHGQRYA (Change Query Attributes) command 381 QSQCHKS 2 QSQLTEMP 335 QSQLTEMP1 335 QSQPRCED 2 package 9 QSYS2 catalog views 6 QSYSPRT listing SQL statement processor example 363 query cancelling 392 Query Definition Template (QDT) 425 query optimizer 395 cost estimation 423 decision-making rules 425 default filter factors 424 optimization goals 423 query optimizer index advisor 482 query options file 546 869 . declaring 301 declaring 300 host variable 300 character 303 declaring 300 externally described 302 numeric 303 including code 299 indicator structure 306 indicator variable 306 naming convention 299 occurrence data structure 301 sequence numbers 299 SQL data types determining equivalent RPG 303 SQL statements in sample 628 SQLCA placement 297 statement label 300 structure parameter passing 307 using the SQLDA 298 WHENEVER statement 300 RRN scalar function 77 rule host variable. using 215 rules that govern operations on large objects 145 run mode interactive SQL 353 Run SQL Statements (RUNSQLSTM) command 1 run-time support concepts 1 running dynamic SQL application 199 program with embedded SQL DDM consideration 346 instruction 346 override consideration 346 return code 347 programs 346 RUNSQLSTM (Run SQL Statements) 357. 302 character host variables 300 coding SQL statements 297. 218 SQL with host language. 20 in reverse order 551 row using a cursor 60 SELECT statement result cursor. 332 SQL statements in sample 640 ROLLBACK prepared statements 201 rollback rollback required state 572 ROLLBACK statement 559 row definition 3. INSERT n improving performance 463 RPG 297. 190.removing all entries from current session 357 Reorganize Physical File Member (RGZPFM) command effect on variable-length columns 458 getting rid of deleted rows 399 report produced by sample programs 643 resource optimization 395 restriction FOR UPDATE OF 553 result table 80 resume using CREATE DISTINCT TYPE example 171 retaining cursor positions across program call improving performance 467. using 218 retaining cursor positions program calls 469 rule 216. 361 command errors 362 commitment control 362 RUNSQLSTM (Run SQL Statements) command 794 RUW (remote unit of work) 555 S sales using CREATE TABLE example 171 870 DB2 UDB for AS/400 SQL Programming V4R4 . using 212 RETRN statement ending RPG for AS/400 programs 307 return code 38 handling in general 221 running a program with embedded SQL 347 RETURNS TABLE clause 188. 6 delete current 61 inserting multiple into a table 69 note 70 preventing duplicate 71 ROWS. 468 all program calls rules 469 Retrieve Message (RTVMSG) command 587 retrieving data from a table. 192 reuse deleted records INSERT 33 Revoke Object Authority (RVKOBJAUT) command 365 REVOKE PACKAGE statement 555 REXX 2 coding SQL statements 325. 358 command 1. 307 comment 299 compiler parameters 340 RPG for AS/400 program 299 (continued) continuation 299 dynamic SQL coding 298 ending using LR indicator 307 using RETRN statement 307 error and warning message during a compile 344 external file description 302 host structure array. 309 RPG for AS/400 program 309 /COPY statement 299. 358 recovering 358 scalar functions 159 schedule table class 585 schema-name and UDFs 158 schemas SQL statement processor 362 scratchpad. using 605 distributed RUW program 556 report 643 SQL statements in COBOL 613 ILE C 606 ILE COBOL 613 ILE RPG for AS/400 program 634 PL/I 621 REXX 640 RPG for AS/400 628 sample tables DB2 UDB for AS/400 579 save/restore 375 packages 560 saved session in a source file 357. 358 session services in interactive SQL 349. 356. session 356 session 358 printing current 357 removing all entries from current 357 saving in a source file 357. 559 SET CURRENT FUNCTION PATH statement SET TRANSACTION statement effect on implicit disconnect 565 not allowed in package 558 setting query time limit 394 SEU (source entry utility) 358 SIGNAL ON ERROR in REXX 329 SIGNAL ON FAILURE in REXX 329 signature. 357 SET clause description 33 value column name 33 constant 33 expression 33 host variable 33 null 33 scalar subselect 34 special register 33 SET CONNECTION statement 555. output definition 11 160 Index 871 . 192 solving 551 common database problem 551 solving common problems 551 SOME 86 sort sequence CREATE INDEX 53 used with ORDER BY 50 used with record selection 50 using 50 using indexes 449 views 53 source entry utility (SEU) 358 source file CCSID 334 containing DBCS constants 334 for RUNSQLSTM 361 include files 334 input to precompiler 334 margins 334 member. passing to UDF 190 scrollable cursor 55 search condition definition 38 performing complex 72 subqueries 85 using keyword in 72 security 365 authorization 380 authorization ID 366 commitment control 369 data integrity 366 concurrency 367 public authority 365 view 366 SELECT clause 38 select information into host variables 36 SELECT INTO statement column value 216 restriction 199 retrieving row 35 SELECT statement definition 20 example of allocating storage for SQLDA 208 processing and using SQLDA 201 using effectively to improve performance 464 using fixed-list 201 using varying-list 202 selecting column 70 data from multiple tables 442 semantic behavior of stored objects 145 Send Program Message (SNDPGMMSG) command 587 Send User Message (SNDUSRMSG) command 587 sensitivity immediate 63. two functions and the same 158 SMALLINT 188. 67 sequence numbers COBOL 254 ILE RPG for AS/400 program 312 RPG for AS/400 program 299 sequential access path 396 serial cursor 55 service program Integrated Language Environment (ILE) object 12 services.sample programs DB2 UDB for AS/400 statements. input value option 152 SQL information summary record 494. value 33 USER 45 specific-name. passing to UDF 188 215 SQL statement processor commitment control 362 example QSYSPRT listing 363 schemas 362 using 361 SQLCA (SQL communication area) C 225 C++ 225 COBOL 251 FORTRAN 837 ILE RPG for AS/400 309 PL/I 279 REXX 325 RPG for AS/400 297 SQLCOD FORTRAN 837 SQLCODE C 225 C++ 225 COBOL 251 FORTRAN 837 in REXX 325 PL/I 279 SQLCODEs definition 221. use in 203 REXX 325 RPG for AS/400 298 SELECT statement for allocating storage for SQLDA 208 SQLDABC 204 SQLDAID 204 SQLDATA 206 SQLDATA field of SQLDA in REXX 327 SQLERRD field of SQLCA 325 SQLERRD(3) field of SQLCA determining connection status 570 determining number of rows fetched 63 SQLERRD(4) field of SQLCA 570 determining connection type 567 determining length of each row retrieved 63 872 DB2 UDB for AS/400 SQL Programming V4R4 . temporary output from precompiler 335 member. passing to UDF 191 SQL blocking improving performance 462 SQL data types determining equivalent C 246 C++ 246 COBOL 274 FORTRAN 842 ILE RPG for AS/400 318 PL/I 292 REXX 330 RPG for AS/400 303 SQL_FILE_READ. 192 SQL-state.source file (continued) member. 526 SQL naming convention 4 SQL package 3 SQL-result. 587 description 589 negative 591 positive 589 testing application program 380 SQLD 204 SQLD field of SQLDA in REXX 326 SQLDA (SQL descriptor area) allocating storage for 208 C 226 C++ 226 COBOL 252 format 204 FORTRAN 838 ILE RPG for AS/400 310 PL/I 280 processing SELECT statement 201 programming language. passing to UDF 190. 192 SQL-result 188 SQL-result-ind. concepts and rules SQL-argument. passing to UDF 188. 621 REXX 640 RPG for AS/400 628 types 4 using host variable 215 using with host language. 358 temporary for precompile 335 sourced UDF 174 special register CURRENT DATE 45 CURRENT SERVER 45 CURRENT TIME 45 CURRENT TIMESTAMP 45 CURRENT TIMEZONE 45 definition 40 SET clause. SELECT INTO statement 38 UNION ALL 83 SQL 1 call level interface 2 introduction 1 object 5 statements COBOL 613 ILE COBOL 613 ILE RPG for AS/400 program 634 PL/I 606. passing to UDF 188 SQL-argument-ind-array. user 11 multiple source in COBOL 255 saving a session in 357. passing to UDF 189 specifying column. passing to UDF 190. 191 SQL-argument 188 SQL-argument-ind. 587 description 589 testing application program 380 SQLTYPE 204 SQLTYPE field of SQLDA in REXX 326 sqludf. 640 statements 48. 351 statement label COBOL 255 in C 229 in C++ 229 requirements for FORTRAN program 840 requirements for ILE RPG for AS/400 312 RPG for AS/400 300 statement-name in DESCRIBE in REXX 325 statement processing mode interactive SQL 353 statements 45. 640 (continued) ALIAS statement example 48 basic. 628. 613. 634. 621. 200 FETCH 212 FOR n ROWS 462 multiple-row 62 number of calls 462 GRANT PACKAGE 555 host variable in SQL. 606. 606. 221.h include file for UDFs 190 SQLVAR 204 SQLWARN field of SQLCA 325 Start Commitment Control (STRCMTCTL) command 370 Start Database Monitor (STRDBMON) command 479 Start Journal Access Path (STRJRNAP) command 376 Start SQL (STRSQL) command 801 starting interactive SQL 350 statement entry 349.SQLERRD field of SQLCA 570 (continued) SQLERRD(5) field of SQLCA determining end-of-file 63 SQLERRMC field of SQLCA 325 SQLERROR statement WHENEVER 221 SQLERRP field of SQLCA 325 SQLIND 206 SQLIND field of SQLDA in REXX 327 SQLLEN 204 SQLLEN field of SQLDA in REXX 326 SQLN 204 SQLNAME 206 SQLNAME field of SQLDA in REXX 326 SQLPRECISION field of SQLDA 326 SQLRES 206 SQLSCALE field of SQLDA 327 SQLSTA FORTRAN 837 SQLSTATE C 225 C++ 225 COBOL 251 FORTRAN 837 in REXX 325 PL/I 279 SQLSTATEs code definition 587 definition 221. 628. using 31 COMMENT ON statement 49 COMMIT 6 CONNECT 555 CREATE COLLECTION 13 CREATE INDEX sort sequence 53 CREATE PROCEDURE external procedure 117 SQL procedure 117 CREATE SCHEMA 362 CREATE TABLE 14 CREATE VIEW 29 data definition (DDL) 4 data manipulation (DML) 4 date value 47 DECLARE CURSOR 36 DELETE example 34 WHERE clause 28 DISCONNECT 555 DROP PACKAGE 555 dynamic 4 EXECUTE 199. 621. 634. 221. using 215 INSERT assignment operation 216 n ROWS 463 using 31 LABEL ON statement example 48 examples 16 multiple-row FETCH 64 OPEN 213 package not required 559 packages 558 PREPARE cursor 213 improving performance 470 non-SELECT statement 200 using 199 preparing and running a program with 333 processing non select 199 RELEASE 555 REVOKE PACKAGE 555 ROLLBACK 6 sample programs 605 select 20 SELECT INTO column value 216 example 35 processing data (view) 36 Index 873 . 613. allocating for SQLDA 208 stored procedures 117. 634. 535. 841 handling exception condition 222 ILE RPG for AS/400 312 RPG for AS/400 300 WHENEVER SQLERROR 221 stopping interactive SQL 357 storage. 6 deleting information in 28 establishing position at the end 551 getting catalog information about column 97 getting information from multiple 23 from one 20 IN_TRAY 585 inserting information into 18 multiple rows into 69 joining 75 874 DB2 UDB for AS/400 SQL Programming V4R4 .PROJECT (project) 584 creating CREATE TABLE statement 14 view 29 data management methods 420 DB2 UDB for AS/400 sample 579 defining name 48 definition 3. 144 definition 8 parameter passing 128 indicator variables 132 table 128 storing large objects 145 STRDBMON (Start Database Monitor) command 479 STRDBMON/ENDDBMON commands summary record 522 string assignment rule using host variable 217 string search and defining UDFs example 162 string search on BLOBs 162 string search over UDT example 163 strong typing and UDTs 172 STRSQL (Start SQL) command 350. 255. 613. 621. 536.EMPLOYEE 580 CORPDATA. 606. 88 correlated names and references 91 definition 84 examples 84 EXISTS keyword 87 IN keyword 87 notes on using with UPDATE and DELETE 88 prompting 353 quantified comparison 86 search condition 85 subquery processing summary record 517 subselect combining with the UNION keyword. 539 Symmetric Multiprocessing 2 symmetrical multiprocessing 397 sync point manager 567 syntax check QSQCHKS 2 syntax check mode interactive SQL 353 syntax for referring to functions 165 system naming convention 3 system table name 17 T table adding data to the end 552 changing definition 93.DEPARTMENT (department) 579 CORPDATA.statements 216. 533. 530. 531. 640 (continued) restriction 48 specifying column 38 SET CONNECTION 555 SQL packages 558 testing in application program 379 using interactive SQL 349.EMP_ACT (employee to project activity) 581 CORPDATA. value 34 summary records access plan rebuilt 513 arrival sequence 498 generic query information 520 host variable and ODP implementation 518 index created 505 optimizer timed out 515 query sort 508 SQL information 494. 628. 554 changing information in 25 CL_SCHED (class schedule) 585 CORPDATA. 537. 538. 221. 526 STRDBMON/ENDDBMON commands 522 subquery processing 517 table locked 511 temporary file 509 using existing index 502. example 80 SET clause. 801 structure parameter passing 473 PL/I 294 RPG for AS/400 307 Structured Query Language 1 structured query language package creating 763 deleting 782 subfields ILE RPG for AS/400 314 RPG for AS/400 300 subquery 88 basic comparison 86 correlated 85. 282. 358 time value 47 timestamp value 47 UPDATE assignment operation 216 changing data value 25 example 33 WHENEVER 230. using 218 time format 47 specifying current value 47 timestamp assignment rule host variable. 55.PROJECT (project) 584 using 14 table functions 159 contents of call-type argument 190 table locked summary record 511 table name system 17 table scans output for all queries 484 output for SQL queries 483 TAG statement ILE RPG for AS/400 312 RPG for AS/400 300 technique coding 31. 461 transitive closure 436 TRCJOB (Trace Job) command 382 trigger definition 8 event 8 trigger support 111 triggers and DB2 object extensions 145 trigraph C 229 C++ 229 truncation error 36 two-phase commit 567 typing interactive SQL 351 U UDFs (User-defined functions) and DB2 object extensions 145 casting 169 concepts 158 definition 156 function path 158 function selection algorithm 158 general considerations 168 implementing UDFs 156 infix notation 168 invoking examples of invocations 164 parameter markers in functions 166 qualified function reference 166 unqualified function reference 167 LOB types 168 overloaded function names 158 process of implementation 160 referring to functions 165 registering UDFs 161 examples of registering 161 schema-name and UDFs 158 sourced 174 summary of function references 167 synergy with UDTs and LOBs examples of complex applications 177 type of functions 159 unqualified reference 158 why use UDFs 156 writing your own UDF 185 UDFs and LOB types 168 UDTs (User-defined types) and DB2 object extensions 145 defining a UDT 170 defining tables 171 manipulating examples of 172 resolving unqualified UDTs 171 strong typing 172 Index 875 .EMP_ACT (employee to project activity) 581 CORPDATA. 317 TIMSEP ILE RPG for AS/400 313. using 218 timestamp format 47 specifying current value 47 TIMFMT ILE RPG for AS/400 313. 358 statements in application program 379 view 379 time assignment rule host variable. 69 solving database problem 551 temporary file summary record 509 temporary keyed access path 435. 436 temporary source file member output from precompiler 335 terminology interactive SQL 3 relational database 3 relationship table *SQL 3 *SYS 3 testing authorization 379.EMPLOYEE 580 CORPDATA.DEPARTMENT (department) 579 CORPDATA. 380 debugging your program 380 input data 379 performance verification 381 SQL statements using interactive SQL 349. 317 tolerance.table (continued) the WHERE clause 552 multiple creating view over 30 improving performance when selecting data from 442 sample 579 used in examples CORPDATA. damage 376 tools performance 477 Trace Job (TRCJOB) command 382. 539 using interactive SQL 349 after first time 356 list selection function 354 prompting 351 statement entry 351 using JOB parameter 394 using qualified function reference example 166 using SQL application programs 395 V validate mode interactive SQL 353 value default 14. 535. 18 inserting into table or view 31 VALUES clause 31 variable 230. 531.UDTs (User-defined types) (continued) synergy with UDFs and LOBs examples of complex applications 177 why use UDTs 169 union C 230 C++ 230 UNION ALL. 533. using in 91 description 33 WHERE clause 25 updating data as it is retrieved. 7 limiting access 28 processing data in 36 read-only 96 security 366 sort sequence 53 testing 379 using 95 WITH CASCADED CHECK 108 175 220 876 DB2 UDB for AS/400 SQL Programming V4R4 . restrictions 552 committable updates 567 previously retrieved 553 use of UDTs in UNION example 177 user auxiliary storage pool (ASP) 378 user-defined sourced functions on UDTs example user profile authorization ID 3 authorization name 3 user source file member definition 11 USER special register 45 using a copy of the data 464. 530. 465 blocked insert statement 70 USING clause 210 using close SQL cursor (CLOSQLCSR) 464. 249 host REXX 330 indicator 219 use of indicator with host structure. 469 cursor example 56 retrieve row 60 date value 47 USING DESCRIPTOR clause 213 using FETCH statement 462 index 96 null value 45 ORDER BY 51 using (continued) parameter markers 462 parameter passing techniques performance improvement 472 record selection 52 sort sequence 50 time value 47 timestamp value 47 Using views 95 using a locator to work with a CLOB value example 148 using existing index summary record 502. 538. 465 allow copy data (ALWCPYDTA) 464. 537. example used to set null value 220 variable-length data tips 456 varying-list SELECT statement definition 202 using 202 verification performance 381 view creating 95 CREATE VIEW statement 28 on a table 29 over multiple tables 30 definition 3. specifying 83 UNION keyword restriction 553 using to combine subselects 80 unique constraint definition 8 unit of work distributed 555 effect on open cursor 68 package creation 560 remote 555 rollback required 572 unit of work boundary package creation 560 unprotected resource 567 unqualified function reference example 167 unqualified reference 158 UPDATE statement assignment operation 216 correlated subquery. 536. 344 PL/I program 343 RPG program 343. using 39 joining tables 76 multiple search condition within a NOT keyword 40 WHERE CURRENT OF clause WITH CHECK OPTION 108 6 61 108 WITH CASCADED CHECK OPTION WITH DATA DICTIONARY clause CREATE COLLECTION statement CREATE SCHEMA statement 6 creating data dictionary 6 WITH LOCAL CHECK OPTION working with index 96 109 221 60 221 343 warning message during a compile 222 74 X X/Open call level interface 2 Index 877 .view (continued) WITH CHECK 95 WITH LOCAL CHECK 109 W warning test for negative SQLCODEs C++ program 343 C program 343 COBOL program 343. substitute for 329 RPG for AS/400 300 WHERE clause character string 31 constant 39 description 38 example 213 expression in. 344 WHENEVER NOT FOUND clause WHENEVER SQLERROR WHENEVER statement C 230 C++ 230 COBOL 255 FORTRAN 841 handling exception condition with ILE RPG for AS/400 312 PL/I 282 REXX. 878 DB2 UDB for AS/400 SQL Programming V4R4 . you grant IBM a nonexclusive right to use or distribute your comments in any way it believes appropriate without incurring any obligation to you. May we contact you? h Yes h No When you send comments to IBM. Address .Readers’ Comments — We’d Like to Hear from You AS/400e DB2 UDB for AS/400 SQL Programming Version 4 Publication No. Name Company or Organization Phone No. how satisfied are you with the information in this book? Very Satisfied h Satisfied h Neutral h Dissatisfied h Very Dissatisfied h Overall satisfaction How satisfied are you that the information in this book is: Very Satisfied h h h h h h Satisfied h h h h h h Neutral h h h h h h Dissatisfied h h h h h h Very Dissatisfied h h h h h h Accurate Complete Easy to find Easy to understand Well organized Applicable to your tasks Please tell us how we can improve this book: Thank you for your responses. RBAF-Y000-00 Overall. 40 ARMONK.___________________________________________________________________________________________________ Readers’ Comments — We’d Like to Hear from You RBAF-Y000-00 Cut or Fold Along Line Please _ _ _ _ staple Fold and _ _ _ _ _ _ _ _ _ _Fold and_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ do not_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ Tape _ _ _ _ _ _ _ _ Tape NO POSTAGE NECESSARY IF MAILED IN THE UNITED STATES BUSINESS REPLY MAIL FIRST-CLASS MAIL PERMIT NO. NEW YORK POSTAGE WILL BE PAID BY ADDRESSEE IBM CORPORATION ATTN DEPT 542 IDCLERK 3605 HWY 52 N ROCHESTER MN 55901-7829 ________________________________________________________________________________________ Fold and Tape Please do not staple Fold and Tape RBAF-Y000-00 Cut or Fold Along Line . . RBAF-Y000-00 .A.Printed in U.S.
Copyright © 2024 DOKUMEN.SITE Inc.