IBM i Database SQL programming 7.1 IBM i Database SQL programming 7.1 Note Before using this information and the product it supports, read the information in “Notices,” on page 491 This edition applies to IBM i 7.1 (product number 5770-SS1) and to all subsequent releases and modifications until otherwise indicated in new editions This version does not run on all reduced instruction set computer (RISC) models nor does it run on CISC models © Copyright IBM Corporation 1998, 2010 US Government Users Restricted Rights – Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp Contents SQL programming | | | | What's new for IBM i 7.1 PDF file for SQL programming Introduction to DB2 for i Structured Query Language SQL concepts SQL relational database and system terminology SQL and system naming conventions Types of SQL statements SQL communication area SQL diagnostics area SQL objects Schemas Journals and journal receivers Catalogs 10 Tables, rows, and columns 10 Aliases 10 Views 10 Indexes 11 Constraints 11 Triggers 12 Stored procedures 12 Sequences 12 Global variables 12 User-defined functions 12 User-defined types 13 XSR objects 13 SQL packages 13 Application program objects 13 User source file 15 Output source file member 15 Program 15 SQL package 15 Module 16 Service program 16 Data definition language 16 Creating a schema 16 Creating a table 17 Adding and removing constraints 17 Referential integrity and tables 18 Adding and removing referential constraints 18 Example: Adding referential constraints 19 Example: Removing constraints 20 Check pending 20 Creating a table using LIKE 21 Creating a table using AS 21 Creating and altering a materialized query table 22 Declaring a global temporary table 23 Creating a table with remote server data 23 Creating a row change timestamp column 24 Creating and altering an identity column 24 Using ROWID 25 Creating and using sequences 26 Comparison of identity columns and sequences 27 © Copyright IBM Corp 1998, 2010 | | | | | | | | | | | | | | | | | | | | | | | | Defining field procedures Field definition for field procedures Specifying the field procedure When field procedures are invoked Parameter list for execution of field procedures The field procedure parameter value list (FPPVL) Parameter value descriptors for field procedures Field-definition (function code 8) Field-encoding (function code 0) Field-decoding (function code 4) Example field procedure program General guidelines for writing field procedures Index considerations Thread considerations Guidelines for writing field procedures that mask data Example field procedure program that masks data Creating descriptive labels using the LABEL ON statement Describing an SQL object using COMMENT ON Changing a table definition Adding a column Changing a column Allowable conversions of data types Deleting a column Order of operations for the ALTER TABLE statement Creating and using ALIAS names Creating and using views WITH CHECK OPTION on a view WITH CASCADED CHECK OPTION WITH LOCAL CHECK OPTION Example: Cascaded check option Creating indexes Creating and using global variables Replacing existing objects Catalogs in database design Getting catalog information about a table Getting catalog information about a column Dropping a database object Data manipulation language Retrieving data using the SELECT statement Basic SELECT statement Specifying a search condition using the WHERE clause Expressions in the WHERE clause Comparison operators NOT keyword GROUP BY clause HAVING clause ORDER BY clause 28 29 29 29 30 32 32 33 34 35 36 37 38 38 38 40 42 43 44 44 44 45 46 46 46 47 49 49 50 50 51 52 52 53 53 53 54 54 54 55 56 57 58 58 58 60 61 iii Static SELECT statements 63 Handling null values 64 Special registers in SQL statements 65 Casting data types 66 Date, time, and timestamp data types 67 Specifying current date and time values 67 Date/time arithmetic 67 Row change expressions 68 Handling duplicate rows 68 Defining complex search conditions 69 Special considerations for LIKE 70 Multiple search conditions within a WHERE clause 71 Using OLAP specifications 72 Joining data from more than one table 74 Inner join 75 Left outer join 76 Right outer join 77 Exception join 77 Cross join 78 Full outer join 79 Multiple join types in one statement 79 Using table expressions 80 Using recursive queries 82 Using the UNION keyword to combine subselects 94 Specifying the UNION ALL keyword 97 Using the EXCEPT keyword 98 Using the INTERSECT keyword 100 Data retrieval errors 102 Inserting rows using the INSERT statement 104 Inserting rows using the VALUES clause 105 Inserting rows using a select-statement 106 Inserting multiple rows using the blocked INSERT statement 106 Inserting data into tables with referential constraints 107 Inserting values into an identity column 108 Selecting inserted values 108 Inserting data from a remote database 109 Changing data in a table using the UPDATE statement 109 Updating a table using a scalar-subselect 111 Updating a table with rows from another table 111 Updating tables with referential constraints 111 Examples: UPDATE rules 112 Updating an identity column 113 Updating data as it is retrieved from a table 113 Removing rows from a table using the DELETE statement 114 Removing rows from tables with referential constraints 115 Example: DELETE rules 116 Merging data 118 Using subqueries 119 Subqueries in SELECT statements 119 Subqueries and search conditions 120 Usage notes on subqueries 121 Including subqueries in the WHERE or HAVING clause 121 | | iv IBM i: Database SQL programming | | Correlated subqueries Correlated names and references Example: Correlated subquery in a WHERE clause Example: Correlated subquery in a HAVING clause Example: Correlated subquery in a select-list Example: Correlated subquery in an UPDATE statement Example: Correlated subquery in a DELETE statement Sort sequences and normalization in SQL Sort sequence used with ORDER BY and row selection Sort sequence and ORDER BY Sort sequence and row selection Sort sequence and views Sort sequence and the CREATE INDEX statement Sort sequence and constraints ICU sort sequence Normalization Data protection Security for SQL objects Authorization ID Views Auditing Data integrity Concurrency Journaling Commitment control Savepoints Atomic operations Constraints Adding and using check constraints Save and restore functions Damage tolerance Index recovery Catalog integrity User auxiliary storage pool Independent auxiliary storage pool Routines Stored procedures Defining an external procedure Defining an SQL procedure Defining a procedure with default parameters Calling a stored procedure Using the CALL statement where procedure definition exists Using the embedded CALL statement where no procedure definition exists Using the embedded CALL statement with an SQLDA Using the dynamic CALL statement where no CREATE PROCEDURE exists Examples: CALL statements Returning result sets from stored procedures Example 1: Calling a stored procedure that returns a single result set 123 123 123 124 125 126 126 127 128 129 130 131 131 132 132 133 133 133 134 134 135 135 135 137 138 141 143 144 145 145 146 147 147 148 148 148 148 149 150 155 157 157 158 159 160 160 167 167 | | | | | | | | | | | | | Example 2: Calling a stored procedure that returns a result set from a nested procedure Writing a program or SQL procedure to receive the result sets from a stored procedure Parameter passing conventions for stored procedures and user-defined functions Indicator variables and stored procedures Returning a completion status to the calling program Passing parameters from DB2 to external proceduress Parameter style SQL Parameter style GENERAL Parameter style GENERAL WITH NULLS Parameter style DB2GENERAL Parameter style Java Using user-defined functions UDF concepts Writing UDFs as SQL functions Example: SQL scalar UDFs Example: SQL table UDFs Writing UDFs as external functions Registering UDFs Passing arguments from DB2 to external functions Table function considerations Error processing for UDFs Threads considerations Parallel processing Fenced or unfenced considerations Save and restore considerations Examples: UDF code Example: Square of a number UDF Example: Counter Example: Weather table function Using UDFs in SQL statements Using parameter markers or the NULL values as function arguments Using qualified function references Using unqualified function references Summary of function references Triggers SQL triggers BEFORE SQL triggers AFTER SQL triggers Multiple event SQL triggers INSTEAD OF SQL triggers Handlers in SQL triggers SQL trigger transition tables External triggers Array support in SQL procedures Debugging an SQL routine Obfuscating an SQL routine Managing SQL and external routine objects Improving performance of procedures and functions Improving implementation of procedures and functions Redesigning routines for performance 168 174 179 184 186 186 186 188 188 189 189 189 190 192 192 192 192 193 196 201 202 202 203 203 204 204 204 206 206 212 213 213 214 214 216 217 217 219 220 221 223 224 224 224 226 227 228 229 230 232 | | | | | | | | | | Processing special data types Large objects Large object data types Large object locators Example: Using a locator to work with a CLOB value Example: LOBLOC in C Example: LOBLOC in COBOL Indicator variables and LOB locators LOB file reference variables Example: Extracting CLOB data to a file Example: LOBFILE in C Example: LOBFILE in COBOL Example: Inserting data into a CLOB column Displaying the layout of LOB columns Journal entry layout of LOB columns User-defined distinct types Defining a UDT Example: Money Example: Resumé Defining tables with UDTs Example: Sales Example: Application forms Manipulating UDTs Examples: Using UDTs Example: Comparisons between UDTs and constants Example: Casting between UDTs Example: Comparisons involving UDTs Example: Sourced UDFs involving UDTs Example: Assignments involving UDTs Example: Assignments in dynamic SQL Example: Assignments involving different UDTs Example: Using UDTs in UNION Examples: Using UDTs, UDFs, and LOBs Example: Defining the UDT and UDFs Example: Using the LOB function to populate the database Example: Using UDFs to query instances of UDTs Example: Using LOB locators to manipulate UDT instances Using DataLinks Linking control levels in DataLinks NO LINK CONTROL FILE LINK CONTROL with FS permissions FILE LINK CONTROL with DB permissions Working with DataLinks SQL statements and SQL/XML functions XML input and output overview Comparison of XML and relational models Tutorial for XML Exercise 1: Creating a table that can store XML data Exercise 2: Inserting XML documents into XML typed columns Exercise 3: Updating XML documents stored in an XML column Contents 233 233 233 233 234 234 236 238 238 239 239 240 241 241 242 242 243 243 243 243 244 244 244 245 245 245 246 246 247 247 248 249 249 249 250 250 251 251 252 252 252 253 253 255 256 257 259 259 259 260 v | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Exercise 4: Validating XML documents against XML schemas Exercise 5: Transforming with XSLT stylesheets Inserting XML data Addition of XML columns to existing tables Insertion into XML columns XML parsing SQL/XML publishing functions for constructing XML values Example: Construct an XML document with values from a single table Example: Construct an XML document with values from multiple tables Example: Construct an XML document with values from table rows that contain null elements Example: Transforming with XSLT stylesheets Example: Using XSLT as a formatting engine Example: Using XSLT for data exchange Example: Using XSLT to remove namespaces Important considerations for transforming XML documents Special character handling in SQL/XML publishing functions XML serialization Differences in an XML document after storage and retrieval Data types for archiving XML documents Using XMLTABLE to reference XML content as a relational table Example: Use XMLTABLE to handle missing elements Example: Use XMLTABLE to subset result data Example: Use XMLTABLE to handle multiple values Example: Use XMLTABLE with namespaces Example: Number result rows for XMLTABLE Updating XML data Deletion of XML data from tables XML schema repository Application programming language support XML column inserts and updates in CLI applications XML data retrieval in CLI applications Declaring XML host variables in embedded SQL applications Example: Referencing XML host variables in embedded SQL applications Recommendations for developing embedded SQL applications with XML Identifying XML values in an SQLDA Java XML data in JDBC applications XML data in SQLJ applications Routines XML support in SQL procedures XML data type support in external routines vi IBM i: Database SQL programming 261 263 265 266 266 267 268 269 270 271 271 273 275 276 279 280 280 282 282 283 284 284 285 287 289 290 291 291 292 292 293 294 295 296 296 297 297 302 305 305 305 | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | XML data encoding Encoding considerations when storing or passing XML data Encoding considerations for input of XML data to a database Encoding considerations for retrieval of XML data from a database Encoding considerations for passing XML data in routine parameters Encoding considerations for XML data in JDBC and SQLJ applications Effects of XML encoding and serialization on data conversion Encoding scenarios for input of internally encoded XML data to a database Encoding scenarios for input of externally encoded XML data to a database Encoding scenarios for retrieval of XML data with implicit serialization Encoding scenarios for retrieval of XML data with explicit XMLSERIALIZE Mappings of encoding names to effective CCSIDs for stored XML data Mappings of CCSIDs to encoding names for serialized XML output data Annotated XML schema decomposition Decomposing XML documents with annotated XML schemas Registering and enabling XML schemas for decomposition Sources for annotated XML schema decomposition XML decomposition annotations Specification and scope of XML decomposition annotations Annotations as attributes Annotations as structured child elements Global annotations XML decomposition annotations Summary db2-xdb:defaultSQLSchema decomposition annotation db2-xdb:rowSet decomposition annotation db2-xdb:table decomposition annotation db2-xdb:column decomposition annotation db2-xdb:locationPath decomposition annotation db2-xdb:expression decomposition annotation db2-xdb:condition decomposition annotation db2-xdb:contentHandling decomposition annotation db2-xdb:normalization decomposition annotation db2-xdb:order decomposition annotation db2-xdb:truncate decomposition annotation db2-xdb:rowSetMapping decomposition annotation 309 310 310 310 310 310 311 311 313 314 316 319 319 319 319 320 320 320 321 321 321 322 322 324 326 329 332 334 337 340 343 347 349 351 352 | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | db2-xdb:rowSetOperationOrder decomposition annotation Keywords for annotated XML schema decomposition Treatment of CDATA sections in annotated XML schema decomposition NULL values and empty strings in annotated XML schema decomposition Checklist for annotated XML schema decomposition Examples of mappings in annotated XML schema decomposition Annotations of derived complex types Decomposition annotation example: Mapping to an XML column Decomposition annotation example: A value mapped to a single table that yields a single row Decomposition annotation example: A value mapped to a single table that yields multiple rows Decomposition annotation example: A value mapped to multiple tables Decomposition annotation example: Grouping multiple values mapped to a single table Decomposition annotation example: Multiple values from different contexts mapped to a single table XML schema to SQL types compatibility for annotated schema decomposition Limits and restrictions for annotated XML schema decomposition Schema for XML decomposition annotations Using SQL in different environments Using a cursor Types of cursors Examples: Using a cursor Step 1: Defining the cursor Step 2: Opening the cursor Step 3: Specifying what to when the end of data is reached Step 4: Retrieving a row using a cursor Step 5a: Updating the current row Step 5b: Deleting the current row Step 6: Closing 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 Dynamic SQL applications Designing and running a dynamic SQL application CCSID of dynamic SQL statements Processing non-SELECT statements Using the PREPARE and EXECUTE statements Processing SELECT statements and using a descriptor 355 356 357 357 358 358 359 364 365 367 368 370 372 373 379 381 382 382 382 383 385 386 386 387 387 388 388 389 389 391 393 393 394 395 395 395 396 | Fixed-list SELECT statements Varying-list SELECT statements SQL descriptor areas SQLDA format Example: A SELECT statement for allocating storage for SQLDA Example: A SELECT statement using an allocated SQL descriptor Parameter markers Using interactive SQL Starting interactive SQL Using the statement entry function Prompting Syntax checking Statement processing mode Subqueries CREATE TABLE prompting Entering DBCS data Using the list selection function Example: 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 Using the SQL statement processor Execution of statements after errors occur Commitment control in the SQL statement processor Source listing for the SQL statement processor Using the RUNSQL CL command Distributed relational database function and SQL DB2 for i distributed relational database support DB2 for i distributed relational database example program SQL package support Valid SQL statements in an SQL package Considerations for creating an SQL package CRTSQLPKG authorization Creating a package on a database other than DB2 for i Target release (TGTRLS) parameter SQL statement size Statements that not require a package Package object type ILE programs and service programs Package creation connection Unit of work Creating packages locally Labels Consistency token SQL and recursion CCSID considerations for SQL Connection management and activation groups Source code for PGM1 Source code for PGM2 Source code for PGM3 Multiple connections to the same relational database Contents 396 397 398 398 401 405 407 409 410 411 411 412 413 413 413 413 414 414 416 417 418 418 418 420 422 422 422 424 426 426 427 428 429 429 429 429 430 430 430 431 431 431 431 431 431 431 432 432 432 433 433 434 436 vii | | | | | | | | | | | | | | | Implicit connection management for the default activation group Implicit connection management for nondefault activation groups Distributed support Determining the connection type Connect and commitment control restrictions Determining the connection status Distributed unit of work connection considerations Ending connections Distributed unit of work Managing distributed unit of work connections Checking the connection status Cursors and prepared statements DRDA stored procedure considerations WebSphere MQ with DB2 WebSphere MQ messages WebSphere MQ message handling DB2 MQ services DB2 MQ policies DB2 MQ functions DB2 MQ dependencies DB2 MQ tables DB2 MQ CCSID conversion Websphere MQ transactions Basic messaging with WebSphere MQ Sending messages with WebSphere MQ Retrieving messages with WebSphere MQ Application to application connectivity with WebSphere MQ Reference DB2 for i sample tables Department table (DEPARTMENT) DEPARTMENT Employee table (EMPLOYEE) EMPLOYEE Employee photo table (EMP_PHOTO) EMP_PHOTO Employee resumé table (EMP_RESUME) EMP_RESUME viii IBM i: Database SQL programming 437 438 438 439 441 441 443 443 444 444 446 446 447 447 448 448 448 449 450 451 452 457 458 459 460 461 462 462 462 463 464 464 465 466 467 467 468 | | | | | | | | | | | | | | | | Employee to project activity table (EMPPROJACT) EMPPROJACT Project table (PROJECT) PROJECT Project activity table (PROJACT) PROJACT Activity table (ACT) ACT Class schedule table (CL_SCHED) CL_SCHED In-tray table (IN_TRAY) IN_TRAY Organization table (ORG) ORG Staff table (STAFF) STAFF Sales table (SALES) SALES Sample XML tables Product table (PRODUCT) PRODUCT Purchase order table (PURCHASEORDER) PURCHASEORDER Customer table (CUSTOMER) CUSTOMER Catalog table (CATALOG) CATALOG Suppliers table (SUPPLIERS) SUPPLIERS Inventory table (INVENTORY) INVENTORY Product Supplier table (PRODUCTSUPPLIER) PRODUCTSUPPLIER DB2 for i CL command descriptions 468 468 470 471 472 473 475 475 476 476 476 477 477 478 478 479 480 480 481 481 482 483 483 486 487 488 488 488 488 489 489 489 489 490 Appendix Notices 491 Programming interface information Trademarks Terms and conditions 492 493 493 | | | | | | PRICE PROMOPRICE PROMOSTART PROMOEND DESCRIPTION PRIMARY KEY DECIMAL(30,2), DECIMAL(30,2), DATE, DATE, XML, (PID) ) | PRODUCT: | Here is a complete listing of the data in the PRODUCT table || PID | | | NAME PRICE PROMO PRICE PROMO START 9.99 7.25 11/19/2004 12/19/2004 Snow Shovel, Basic 22 inch Basic Snow Shovel, 22 inches wide, straight handle with D-Grip 9.99 1 kg | 100-101-01 Snow Shovel, 19.99 | Deluxe 24 inch | | | | | | | | | | 15.99 12/18/2005 02/28/2006 Snow Shovel, Deluxe 24 inch A Deluxe Snow Shovel, 24 inches wide, ergonomic curved handle with D-Grip 19.99 2 kg | 100-103-01 Snow Shovel, | Super Deluxe | 26 inch | | | | | | | | | | | 39.99 12/22/2005 02/22/2006 Snow Shovel, Super Deluxe 26 inch Super Deluxe Snow Shovel, 26 inches wide, ergonomic battery heated curved handle with upgraded D-Grip 49.99 3 kg | 100-100-01 Snow Shovel, Basic 22 inch | | | | | | | | | | | 482 49.99 IBM i: Database SQL programming PROMO END DESCRIPTION, shown as it appears using the XMLSERIALIZE scalar function to convert it to serialized character data | | | | PID | | | | | | | | | | | 100-201-01 Ice Scraper, Windshield inch | | | Purchase order table (PURCHASEORDER) | | | | | | | | | | | | | | The purchase order table is created with the following CREATE TABLE and ALTER TABLE statements: | PURCHASEORDER: | Here is a complete listing of the data in the PURCHASEORDER table NAME PRICE PROMO PRICE PROMO START PROMO END DESCRIPTION, shown as it appears using the XMLSERIALIZE scalar function to convert it to serialized character data 3.99 - - - Ice Scraper, Windshield inch Basic Ice Scraper inches wide, foam handle 3.99 The purchase order table identifies every purchase order by a purchase order ID and lists basic purchase order information CREATE TABLE PURCHASEORDER ( POID BIGINT NOT NULL, STATUS VARCHAR(10) NOT NULL WITH DEFAULT(’Unshipped’), CUSTID BIGINT ORDERDATE DATE PORDER XML COMMENTS VARCHAR(1000), PRIMARY KEY (POID) ) ALTER TABLE PURCHASEORDER ADD FOREIGN KEY FK_PO_CUST(CUSTID) REFERENCES CUSTOMER(CID) ON DELETE CASCADE SQL programming 483 || POID | | STATUS | 5000 | | | | | | | | | | | | | | | | | | | Unshipped 1002 02/18/2006 100-100-01 Snow Shovel, Basic 22 inch 3 9.99 100-103-01 Snow Shovel, Super Deluxe 26 inch 5 49.99 THIS IS A NEW PURCHASE ORDER | 5001 | | | | | | | | | | | | | | | | | | | | | | | | | | | Shipped 02/03/2005 100-101-01 Snow Shovel, Deluxe 24 inch 1 19.99 100-103-01 Snow Shovel, Super Deluxe 26 inch 2 49.99 100-201-01 Ice Scraper, Windshield inch 1 3.99 THIS IS A NEW PURCHASE ORDER 484 CUSTID 1003 IBM i: Database SQL programming ORDERDATE PORDER, shown as it appears using COMMENTS the XMLSERIALIZE scalar function to convert it to serialized character data | | | POID STATUS CUSTID ORDERDATE PORDER, shown as it appears using COMMENTS the XMLSERIALIZE scalar function to convert it to serialized character data | 5002 | | | | | | | | | | | | | | | | | | | | | | | | | | | Shipped 1001 02/29/2004 100-100-01 Snow Shovel, Basic 22 inch 3 9.99 100-101-01 Snow Shovel, Deluxe 24 inch 5 19.99 100-201-01 Ice Scraper, Windshield inch 5 3.99 THIS IS A NEW PURCHASE ORDER | 5003 | | | | | | | | | | | Shipped 1002 02/28/2005 100-100-01 Snow Shovel, Basic 22 inch 1 9.99 THIS IS A NEW PURCHASE ORDER SQL programming 485 | POID | | STATUS CUSTID ORDERDATE PORDER, shown as it appears using COMMENTS the XMLSERIALIZE scalar function to convert it to serialized character data | 5004 | | | | | | | | | | | | | | | | | | | Shipped 1005 11/18/2005 100-100-01 Snow Shovel, Basic 22 inch 4 9.99 < item> 100-103-01 Snow Shovel, Super Deluxe 26 inch 2 49.99 THIS IS A NEW PURCHASE ORDER | 5005 | | | | | | | | | | | | | | | | | | | | | | | | | | | | Shipped 1002 03/01/2006 100-100-01 Snow Shovel, Basic 22 inch 3 9.99 100-101-01 Snow Shovel, Deluxe 24 inch 5 19.99 100-201-01 Ice Scraper, Windshield inch 5 3.99 THIS IS A NEW PURCHASE ORDER | Customer table (CUSTOMER) | The customer table identifies every customer by a customer ID and lists basic customer information | The customer table is created with the following CREATE TABLE statement: 486 IBM i: Database SQL programming | | | | | CREATE TABLE CUSTOMER ( CID INFO HISTORY PRIMARY KEY | CUSTOMER: | Here is a complete listing of the data in the CUSTOMER table || | CID INFO, shown as it appears using the XMLSERIALIZE scalar function to convert it to serialized character data HISTORY | | | | | | | | | | 1000 Kathy Smith 5 Rosewood Toronto Ontario M6W 1E6 416-555-1358 ? | | | | | | | | | | 1001 Kathy Smith 25 EastCreek Markham Ontario N9C 3T6 905-555-7258 ? | | | | | | | | | | 1002 Jim Noodle 25 EastCreek Markham Ontario N9C 3T6 905-555-7258 ? | | | | | | | | | | | | | 1003 Robert Shoemaker 1596 Baseline Aurora Ontario N8X 7F8 905-555-7258 416-555-2937 905-555-8743 613-555-3278 ? BIGINT NOT NULL, XML, XML, (CID) ) SQL programming 487 | CID | INFO, shown as it appears using the XMLSERIALIZE scalar function to convert it to serialized character data HISTORY | 1004 | | | | | | | | | | | | | | Matt Foreman 1596 Baseline Toronto Ontario M3Z 5H9 905-555-4789 416-555-3376 Gopher Runner 416-555-3426 ? | 1005 | | | | | | | | | | | | | | | Larry Menard 223 Nature Valley Road Toronto Ontario M4C 5K8 905-555-9146 416-555-6121 Goose Defender 416-555-1943 ? | Catalog table (CATALOG) | The catalog table describes each catalog | The catalog table is created with the following CREATE TABLE statement: | CREATE TABLE CATALOG | ( NAME VARCHAR(128) NOT NULL, | CATLOG XML, | PRIMARY KEY (NAME) ) | CATALOG: | The CATALOG table contains no data | Suppliers table (SUPPLIERS) | The suppliers table identifies every supplier and lists basic supplier information | The suppliers table is created with the following CREATE TABLE statement: | CREATE TABLE SUPPLIERS | ( SID VARCHAR(10) NOT NULL, | ADDR XML, | PRIMARY KEY (SID) ) | SUPPLIERS: | Here is a complete listing of the data in the SUPPLIERS table 488 IBM i: Database SQL programming || SID ADDR | | | | | | | | | 100 Harry Suppliers 50 EastCreek Markham Ontario N9C 3T6 | | | | | | | | | | 101 Johnston Suppliers 302 NatureValley Road Toronto Ontario M4C 5K8 | | Inventory table (INVENTORY) | | | | | | The inventory table is created with the following CREATE TABLE statement: | INVENTORY: | Here is a complete listing of the data in the INVENTORY table || PID QUANTITY LOCATION | 100-100-01 - | 100-101-01 25 Store | 100-103-01 55 Store | | 100-201-01 99 Warehouse | | Product Supplier table (PRODUCTSUPPLIER) | | | | | The product supplier table is created with the following CREATE TABLE statement: | PRODUCTSUPPLIER: | Here is a complete listing of the data in the PRODUCTSUPPLIER table The inventory table describes the inventory based on a product ID CREATE TABLE INVENTORY ( PID QUANTITY LOCATION PRIMARY KEY VARCHAR(10) NOT NULL, INTEGER, VARCHAR(128), (PID) ) The product supplier table describes the relationship between a product and its supplier CREATE TABLE PRODUCTSUPPLIER ( PID VARCHAR(10) NOT NULL, SID VARCHAR(10) NOT NULL, PRIMARY KEY (PID, SID) ) SQL programming 489 || PID SID | 100-101-01 100 | 100-201-01 | 101 | DB2 for i CL command descriptions DB2 for i provides these CL commands for SQL v Create SQL Package (CRTSQLPKG) command v Delete SQL Package (DLTSQLPKG) command v Print SQL Information (PRTSQLINF) command v Run SQL Statement (RUNSQLSTM) command v Start SQL Interactive Session (STRSQL) command Related reference: “DB2 for i distributed relational database support” on page 426 The IBM DB2 Query Manager and SQL Development Kit for i licensed program supports interactive access to distributed databases Code license and disclaimer information IBM grants you a nonexclusive copyright license to use all programming code examples from which you can generate similar function tailored to your own specific needs SUBJECT TO ANY STATUTORY WARRANTIES WHICH CANNOT BE EXCLUDED, IBM, ITS PROGRAM DEVELOPERS AND SUPPLIERS MAKE NO WARRANTIES OR CONDITIONS EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OR CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT, REGARDING THE PROGRAM OR TECHNICAL SUPPORT, IF ANY UNDER NO CIRCUMSTANCES IS IBM, ITS PROGRAM DEVELOPERS OR SUPPLIERS LIABLE FOR ANY OF THE FOLLOWING, EVEN IF INFORMED OF THEIR POSSIBILITY: LOSS OF, OR DAMAGE TO, DATA; DIRECT, SPECIAL, INCIDENTAL, OR INDIRECT DAMAGES, OR FOR ANY ECONOMIC CONSEQUENTIAL DAMAGES; OR LOST PROFITS, BUSINESS, REVENUE, GOODWILL, OR ANTICIPATED SAVINGS SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF DIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, SO SOME OR ALL OF THE ABOVE LIMITATIONS OR EXCLUSIONS MAY NOT APPLY TO YOU 490 IBM i: Database SQL programming Appendix Notices This information was developed for products and services offered in the U.S.A IBM may not offer the products, services, or features discussed in this document in other countries Consult your local IBM representative for information on the products and services currently available in your area Any reference to an IBM product, program, or service is not intended to state or imply that only that IBM product, program, or service may be used Any functionally equivalent product, program, or service that does not infringe any IBM intellectual property right may be used instead However, it is the user's responsibility to evaluate and verify the operation of any non-IBM product, program, or service IBM may have patents or pending patent applications covering subject matter described in this document The furnishing of this document does not grant you any license to these patents You can send license inquiries, in writing, to: IBM Director of Licensing IBM Corporation North Castle Drive Armonk, NY 10504-1785 U.S.A For license inquiries regarding double-byte (DBCS) information, contact the IBM Intellectual Property Department in your country or send inquiries, in writing, to: Intellectual Property Licensing Legal and Intellectual Property Law IBM Japan, Ltd 3-2-12, Roppongi, Minato-ku, Tokyo 106-8711 The following paragraph does not apply to the United Kingdom or any other country where such provisions are inconsistent with local law: INTERNATIONAL BUSINESS MACHINES CORPORATION PROVIDES THIS PUBLICATION “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE Some states not allow disclaimer of express or implied warranties in certain transactions, therefore, this statement may not apply to you This information could include technical inaccuracies or typographical errors Changes are periodically made to the information herein; these changes will be incorporated in new editions of the publication IBM may make improvements and/or changes in the product(s) and/or the program(s) described in this publication at any time without notice Any references in this information to non-IBM Web sites are provided for convenience only and not in any manner serve as an endorsement of those Web sites The materials at those Web sites are not part of the materials for this IBM product and use of those Web sites is at your own risk IBM may use or distribute any of the information you supply in any way it believes appropriate without incurring any obligation to you Licensees of this program who wish to have information about it for the purpose of enabling: (i) the exchange of information between independently created programs and other programs (including this one) and (ii) the mutual use of the information which has been exchanged, should contact: IBM Corporation © Copyright IBM Corp 1998, 2010 491 Software Interoperability Coordinator, Department YBWA 3605 Highway 52 N Rochester, MN 55901 U.S.A Such information may be available, subject to appropriate terms and conditions, including in some cases, payment of a fee The licensed program described in this document and all licensed material available for it are provided by IBM under terms of the IBM Customer Agreement, IBM International Program License Agreement, IBM License Agreement for Machine Code, or any equivalent agreement between us Any performance data contained herein was determined in a controlled environment Therefore, the results obtained in other operating environments may vary significantly Some measurements may have been made on development-level systems and there is no guarantee that these measurements will be the same on generally available systems Furthermore, some measurements may have been estimated through extrapolation Actual results may vary Users of this document should verify the applicable data for their specific environment Information concerning non-IBM products was obtained from the suppliers of those products, their published announcements or other publicly available sources IBM has not tested those products and cannot confirm the accuracy of performance, compatibility or any other claims related to non-IBM products Questions on the capabilities of non-IBM products should be addressed to the suppliers of those products All statements regarding IBM's future direction or intent are subject to change or withdrawal without notice, and represent goals and objectives only This information contains examples of data and reports used in daily business operations To illustrate them as completely as possible, the examples include the names of individuals, companies, brands, and products All of these names are fictitious and any similarity to the names and addresses used by an actual business enterprise is entirely coincidental COPYRIGHT LICENSE: This information contains sample application programs in source language, which illustrate programming techniques on various operating platforms You may copy, modify, and distribute these sample programs in any form without payment to IBM, for the purposes of developing, using, marketing or distributing application programs conforming to the application programming interface for the operating platform for which the sample programs are written These examples have not been thoroughly tested under all conditions IBM, therefore, cannot guarantee or imply reliability, serviceability, or function of these programs The sample programs are provided "AS IS", without warranty of any kind IBM shall not be liable for any damages arising out of your use of the sample programs Each copy or any portion of these sample programs or any derivative work, must include a copyright notice as follows: © (your company name) (year) Portions of this code are derived from IBM Corp Sample Programs © Copyright IBM Corp _enter the year or years_ If you are viewing this information softcopy, the photographs and color illustrations may not appear Programming interface information This SQL programming publication documents intended Programming Interfaces that allow the customer to write programs to obtain the services of IBM i 492 IBM i: Database SQL programming Trademarks IBM, the IBM logo, and ibm.com are trademarks or registered trademarks of International Business Machines Corp., registered in many jurisdictions worldwide Other product and service names might be trademarks of IBM or other companies A current list of IBM trademarks is available on the Web at Copyright and trademark information at www.ibm.com/legal/copytrade.shtml Adobe, the Adobe logo, PostScript, and the PostScript logo are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States, and/or other countries Linux is a registered trademark of Linus Torvalds in the United States, other countries, or both Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft Corporation in the United States, other countries, or both Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc in the United States, other countries, or both UNIX is a registered trademark of The Open Group in the United States and other countries Other company, product, or service names may be trademarks or service marks of others Terms and conditions Permissions for the use of these publications is granted subject to the following terms and conditions Personal Use: You may reproduce these publications for your personal, noncommercial use provided that all proprietary notices are preserved You may not distribute, display or make derivative works of these publications, or any portion thereof, without the express consent of IBM Commercial Use: You may reproduce, distribute and display these publications solely within your enterprise provided that all proprietary notices are preserved You may not make derivative works of these publications, or reproduce, distribute or display these publications or any portion thereof outside your enterprise, without the express consent of IBM Except as expressly granted in this permission, no other permissions, licenses or rights are granted, either express or implied, to the publications or any information, data, software or other intellectual property contained therein IBM reserves the right to withdraw the permissions granted herein whenever, in its discretion, the use of the publications is detrimental to its interest or, as determined by IBM, the above instructions are not being properly followed You may not download, export or re-export this information except in full compliance with all applicable laws and regulations, including all United States export laws and regulations IBM MAKES NO GUARANTEE ABOUT THE CONTENT OF THESE PUBLICATIONS THE PUBLICATIONS ARE PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY, NON-INFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE Appendix Notices 493 494 IBM i: Database SQL programming Printed in USA ... 4 68 4 68 470 471 472 473 475 475 476 476 476 477 477 4 78 4 78 479 480 480 481 481 482 483 483 486 487 488 488 488 488 489 489 489 489 490 Appendix Notices ... 364 365 367 3 68 370 372 373 379 381 382 382 382 383 385 386 386 387 387 388 388 389 389 391 393 393 394 395 395 395 396 | Fixed-list SELECT statements Varying-list SELECT statements SQL... 1 68 174 179 184 186 186 186 188 188 189 189 189 190 192 192 192 192 193 196 201 202 202 203 203 204 204 204 206 206 212 213 213 214 214 216 217 217 219 220 221 223 224 224 224 226 227 2 28 229