Teradata Preprocessor2 for Embedded SQL. Programmer Guide

Size: px
Start display at page:

Download "Teradata Preprocessor2 for Embedded SQL. Programmer Guide"

Transcription

1 Teradata Preprocessor2 for Embedded SQL Programmer Guide Release B A February 2009

2 The product or products described in this book are licensed products of Teradata Corporation or its affiliates. Teradata, BYNET, DBC/1012, DecisionCast, DecisionFlow, DecisionPoint, Eye logo design, InfoWise, Meta Warehouse, MyCommerce, SeeChain, SeeCommerce, SeeRisk, Teradata Decision Experts, Teradata Source Experts, WebAnalyst, and You ve Never Seen Your Business Like This Before are trademarks or registered trademarks of Teradata Corporation or its affiliates. Adaptec and SCSISelect are trademarks or registered trademarks of Adaptec, Inc. AMD Opteron and Opteron are trademarks of Advanced Micro Devices, Inc. BakBone and NetVault are trademarks or registered trademarks of BakBone Software, Inc. EMC, PowerPath, SRDF, and Symmetrix are registered trademarks of EMC Corporation. GoldenGate is a trademark of GoldenGate Software, Inc. Hewlett-Packard and HP are registered trademarks of Hewlett-Packard Company. Intel, Pentium, and XEON are registered trademarks of Intel Corporation. IBM, CICS, DB2, MVS, RACF, Tivoli, and VM are registered trademarks of International Business Machines Corporation. Linux is a registered trademark of Linus Torvalds. LSI and Engenio are registered trademarks of LSI Corporation. Microsoft, Active Directory, Windows, Windows NT, and Windows Server are registered trademarks of Microsoft Corporation in the United States and other countries. Novell and SUSE are registered trademarks of Novell, Inc., in the United States and other countries. QLogic and SANbox trademarks or registered trademarks of QLogic Corporation. SAS and SAS/C are trademarks or registered trademarks of SAS Institute Inc. SPARC is a registered trademarks of SPARC International, Inc. Sun Microsystems, Solaris, Sun, and Sun Java are trademarks or registered trademarks of Sun Microsystems, Inc., in the United States and other countries. Symantec, NetBackup, and VERITAS are trademarks or registered trademarks of Symantec Corporation or its affiliates in the United States and other countries. Unicode is a collective membership mark and a service mark of Unicode, Inc. UNIX is a registered trademark of The Open Group in the United States and other countries. Other product and company names mentioned herein may be the trademarks of their respective owners. THE INFORMATION CONTAINED IN THIS DOCUMENT IS PROVIDED ON AN AS-IS BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO THE ABOVE EXCLUSION MAY NOT APPLY TO YOU. IN NO EVENT WILL TERADATA CORPORATION BE LIABLE FOR ANY INDIRECT, DIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS OR LOST SAVINGS, EVEN IF EXPRESSLY ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. The information contained in this document may contain references or cross-references to features, functions, products, or services that are not announced or available in your country. Such references do not imply that Teradata Corporation intends to announce such features, functions, products, or services in your country. Please consult your local Teradata Corporation representative for those features, functions, products, or services available in your country. Information contained in this document may contain technical inaccuracies or typographical errors. Information may be changed or updated without notice. Teradata Corporation may also make improvements or changes in the products or services described in this information at any time without notice. To maintain the quality of our products and services, we would like your comments on the accuracy, clarity, organization, and value of this document. Please [email protected] Any comments or materials (collectively referred to as Feedback ) sent to Teradata Corporation will be deemed non-confidential. Teradata Corporation will have no obligation of any kind with respect to Feedback and will be free to use, reproduce, disclose, exhibit, display, transform, create derivative works of, and distribute the Feedback and derivative works thereof without limitation on a royalty-free basis. Further, Teradata Corporation will be free to use any ideas, concepts, know-how, or techniques contained in such Feedback for any purpose whatsoever, including developing, manufacturing, or marketing products or services incorporating Feedback. Copyright by Teradata Corporation. All Rights Reserved.

3 Preface Purpose This book provides information about Teradata Preprocessor2 for Embedded SQL, which is a Teradata Tools and Utilities product. Teradata Tools and Utilities is a group of products designed to work with Teradata Database. PP2 is used to incorporate Structured Query Language (SQL) statements into application programs that access data in a Teradata Database. Audience This book is intended for use by application programmers who must incorporate Teradata SQL statements into COBOL, C, or PL/I application programs to access data stored in a Teradata Database. Supported Releases This book supports the following releases: Teradata Database 12.0 Teradata Tools and Utilities Teradata Preprocessor2 for Embedded SQL Note: See Release Number Information on page 26 to verify the Teradata Preprocessor2 for Embedded SQL version number. To locate detailed supported-release information: 1 Go to 2 Navigate to General Search>Publication Product ID. 3 Enter Open the version of the Teradata Tools and Utilities ##.##.## Supported Versions spreadsheet associated with this release. The spreadsheet includes supported Teradata Database versions, platforms, and product release numbers. Teradata Preprocessor2 for Embedded SQL Programmer Guide 3

4 Preface Prerequisites Prerequisites The following prerequisite knowledge is required for this product: Basic computer technology Developing application programs in PL/I, C, or COBOL SQL Teradata Database Changes to This Book The following changes were made to this book in support of the current release. Changes are marked with change bars. For a complete list of changes to the product, see the Release Definition associated with this release. Date and Release July Description Added DML array support for the following platforms: Network Cobol Mainframe C Mainframe Cobol Mainframe PL/I Support for online archive logging was added. Changed application linking instructions for: C on UNIX Micro Focus COBOL on UNIX LPI COBOL on MP-RAS Added support for extended ANSI-compliant Unicode delimited identifiers and character string literals. Added support for query banding. Removed limitation regarding compiling a 32-bit application on a 64-bit Windows EM64T machine. Added Microsoft Windows Vista support. Clarified that, in a mainframe environment, a TDP module must be started prior to precompiling. Additional Information Additional information that supports this product and Teradata Tools and Utilities is available at the web sites listed in the table that follows. In the table, mmyx represents the publication date of a manual, where mm is the month, y is the last digit of the year, and x is an internal 4 Teradata Preprocessor2 for Embedded SQL Programmer Guide

5 Preface Additional Information publication code. Match the mmy of a related publication to the date on the cover of this book. This ensures that the publication selected supports the same release. Type of Information Description Access to Information Release overview Late information Additional product information CD-ROM images Use the Release Definition for the following information: Overview of all of the products in the release Information received too late to be included in the manuals Operating systems and Teradata Database versions that are certified to work with each product Version numbers of each product and the documentation for each product Information about available training and the support center Use the Teradata Information Products Publishing Library site to view or download specific manuals that supply related or additional information to this manual. Access a link to a downloadable CD-ROM image of all customer documentation for this release. Customers are authorized to create CD-ROMs for their use from this image. 1 Go to 2 Select the General Search check box. 3 In the Publication Product ID box, type Click Search. 5 Select the appropriate Release Definition from the search results. 1 Go to 2 Select the Teradata Data Warehousing check box. 3 Do one of the following: For a list of Teradata Tools and Utilities documents, click Teradata Tools and Utilities and then select a release or a specific title. Select a link to any of the data warehousing publications categories listed. Specific books related to Teradata Preprocessor2 for Embedded SQL are as follows: Teradata Call-Level Interface Version 2 Reference for Channel-Attached Systems B mmyx SQL Reference: Data Definition Statements B mmyx SQL Reference: Fundamentals B mmyx SQL Reference: Stored Procedures and Embedded SQL B mmyx Teradata Director Program Reference B mmyx 1 Go to 2 Select the General Search check box. 3 In the Title or Keyword box, type CD-ROM. 4 Click Search. Teradata Preprocessor2 for Embedded SQL Programmer Guide 5

6 Preface Additional Information Type of Information Description Access to Information Ordering information for manuals General information about Teradata Use the Teradata Information Products Publishing Library site to order printed versions of manuals. The Teradata home page provides links to numerous sources of information about Teradata. Links include: Executive reports, case studies of customer experiences with Teradata, and thought leadership Technical information, solutions, and expert advice Press releases, mentions, and media resources 1 Go to 2 Select the How to Order check box under Print & CD Publications. 3 Follow the ordering instructions. 1 Go to Teradata.com. 2 Select a link. 6 Teradata Preprocessor2 for Embedded SQL Programmer Guide

7 Table of Contents Preface Purpose Audience Supported Releases Prerequisites Changes to This Book Additional Information Chapter 1: Introduction PP2 Processes Using Static and Dynamic SQL Upgrading PP2 and CLIv Mainframe and Windows Platforms UNIX/LINUX Platforms Supported Operating Systems and Host Programming Languages PP2 Input PP2 Output Contents of PP2 Output Listing Release Number Information OPTIONS, SOURCE, and XREF Sections PRINT Option Diagnostic Messages Client Language Source Code Server Failure and Recovery PP2 Behavior Application Behavior Query Banding Finding Information Teradata Preprocessor2 for Embedded SQL Programmer Guide 7

8 Table of Contents Chapter 2: Connecting to the Database and Invoking PP Connecting to the Teradata Database PP2 Connection Runtime Execution Connection Explicit Connection Implicit Connection Invoking PP IBM Mainframe Environment: z/os and z/vm CMS Network-Attached Environments PP2 Options How to Read the Option Syntax APOST QUOTE -a -q APOSTSQL QUOTESQL -as -qs CHARSET(charset) -cs charset CURPREFIX(prefix) -c prefix DATABASE(dbname) -db dbname DATE(D E I J U) -d D E I J U DYNPREFIX (prefix) -dp prefix FLAG(I W E S) -f I W E S INPUT(file spec) -i filespec ld logdata LINECOUNT(integer) -lc integer lm logmech MARGINS(m,n[,c]) -m m,n[,c] NULLSCAN NONULLSCAN -ns -nns OPTIONS NOOPTIONS -lo -nlo PRINT[(file spec)] NOPRINT -l [filespec] -nl Teradata Preprocessor2 for Embedded SQL Programmer Guide

9 Table of Contents PUNCH[(file spec)] NOPUNCH -o [filespec] -no SOURCE NOSOURCE -ls -nls SQLCHECK(FULL NOSYNTAX) -sc FULL NOSYNTAX SQLFLAGGER (NONE ENTRY INTERMEDIATE) -sf (NONE ENTRY INTERMEDIATE) TDPID(tdpid network group name) -t tdpid network group name TERM[(file spec)] NOTERM -e [filespec] -ne TRANSACT(ANSI BTET COMMIT 2PC) -tr ANSI BTET COMMIT USERID(userid[,password[,accountid]]) -u userid[,password[,accountid]] VERSION(COBOL COBOLII COBOL3) -v MF1 MF2 LPI XREF NOXREF -lx -nlx Chapter 3: Writing Embedded SQL Applications in C C Language Support Program Status Information Teradata Mode Communications Area ANSI-Compatible Mode Communications Variables BIGINT Support C Coding Considerations Embedded SQL Statement Format Array Support Comments Continuation for SQL Statements Dynamic SQL Including Code Margins Sequence Numbers SQL Strings Statement Labels String Delimiters User Defined Functions Multi-Session Programming Considerations Teradata Preprocessor2 for Embedded SQL Programmer Guide 9

10 Table of Contents Special Considerations Host Variables Using C Structures as Output Host Variables Using C Structures as Input Host Variables Example Overview Requirements for Host Variables C Language and Host Variables SQL and Host Variables Indicator Variables PP2 Issues Host Variable Declaration Host Variable Values Server to Host Assignment Conversion Rules Byte String Assignment Character Assignment Single Character Data Varying Character Data Character String Data Character String Padding Character Truncation Numeric Value Assignment Date Assignment Host to Server Assignment Assignment Rules Host Variable Declaration Indicator Variables Rules for Indicator Variables Indicator Variables and Input Indicator Variables and Output Indicator Variables and Structures SQL Error Return ANSI Mode SQLCODE Variable SQLSTATE Variable Using PPRTEXT to Retrieve Return Codes SQL Error Return Teradata Mode SQLCODE Field Using PPRTEXT to Retrieve Return Codes Exception Conditions: WHENEVER Exception Conditions WHENEVER Is Declarative Rules for Using WHENEVER Teradata Preprocessor2 for Embedded SQL Programmer Guide

11 Table of Contents Dynamic Statement Example A Caution When Using Dynamic SQL Include SQLDA Example Multi-Session Programming Online Archive Performing a Stored Procedure Using Stored Procedure Dynamic Result Sets Using UPSERT in Embedded SQL Chapter 4: Writing Embedded SQL Applications in COBOL COBOL Language Support COBOL Application Requirements Program Status Information Teradata Mode Communications Area ANSI-Compatible Mode Communications Variables BIGINT Support Large Decimal Support COBOL Coding Considerations Array Support Embedded SQL Statement Format Comments Continuation for SQL Statements Dynamic SQL Including Code Margins Paragraph Names Sequence Numbers SQL Strings String Delimiters APOSTSQL Example QUOTESQL Example User Defined Functions Multisession Programming Considerations Special Considerations Host Variables Using COBOL Structures as Output Host Variables Using COBOL Structures as Input Host Variables Example Overview Teradata Preprocessor2 for Embedded SQL Programmer Guide 11

12 Table of Contents Requirements for Host Variables COBOL and Host Variables SQL and Host Variables PP2 Issues Host Variable Values Server to Host Assignment Host to Server Assignment Host Variable Declaration Indicator Variables Rules for Indicator Variables Indicator Variables and Input Indicator Variables and Output Indicator Variables and Structures SQL Error Return ANSI Mode SQLCODE Variable SQLSTATE Variable Using PPRTEXT to Retrieve Return Codes SQL Error Return Teradata Mode SQLCODE Field Using PPRTEXT to Retrieve Return Codes Exception Conditions: WHENEVER Exception Conditions WHENEVER Is Declarative Rules for Using WHENEVER Dynamic Statement Example Online Archive Chapter 5: Writing Embedded SQL Applications in PL/I PL/I Language Support PL/I Application Requirements Program Status Information Teradata Mode Communications Area ANSI-Compatible Mode Communications Variables BIGINT Support Large Decimal Support PL/I Coding Considerations Array Support Embedded SQL Statement Format Teradata Preprocessor2 for Embedded SQL Programmer Guide

13 Table of Contents Comments Continuation for SQL Statements Dynamic SQL Including Code Macro Processor Margins Sequence Numbers SQL Strings Statement Labels String Delimiters Multi-Session Programming Considerations Special Considerations Host Variables Using PL/I Structures as Output Host Variables Using PL/I Structures as Input Host Variables Example Overview Requirements for PL/I Host Variables Server to Host Assignment Conversion Rules Byte String Assignment Character String Assignment String Truncation Numeric Value Assignment Date Assignment Host to Server Assignment Graphic Literals for Multibyte Characters Host Variable Declaration Indicator Variables Rules for Indicator Variables Indicator Variables and Input Indicator Variables and Output Indicator Variables and Structures SQL Error Return ANSI Mode SQLCODE Variable SQLSTATE Variable Using PPRTEXT to Retrieve Return Codes SQL Error Return Teradata Mode SQLCODE Field Using PPRTEXT to Retrieve Return Codes Exception Conditions: WHENEVER Exception Conditions WHENEVER Is Declarative Teradata Preprocessor2 for Embedded SQL Programmer Guide 13

14 Table of Contents Rules for Using WHENEVER Dynamic Statement Example Online Archive Appendix A: SQL Data Type Codes Data Type Codes Unused/Internal Data Type Codes Appendix B: Sample Application Linkage Procedure Overview Bit Platform Linking Concerns Application Linking for z/os Application Linking for CICS Application Linking for IMS Application Linking for z/vm CMS Application Linking for C on UNIX Linkage Script for a 64-Bit Application on AIX Linkage Script for a 64- Bit Application on Itanium HP-UX Linkage Script for a 64-Bit Application on 64-Bit Itanium RH Linkage Script for a 32-Bit Application on Opteron Solaris Linkage Script for a 64-Bit Application on Opteron Solaris Application Linking for Micro Focus COBOL on UNIX Linkage Script for a 64-Bit Application on AIX Script Notes Application Linking for LPI COBOL on MP-RAS Application Linking for Visual C++ on Windows Appendix C: Embedded SQL Examples About the Examples LAB Files Setting Up the Examples Teradata Preprocessor2 for Embedded SQL Programmer Guide

15 Table of Contents Procedure Overview z/os Operating Systems Where to Find Source Code and LAB Files Which Setup Files to Use z/os JCL Network-Attached Operating Systems Where to Find Source Code and LAB Files Which Setup Files to Use z/vm Operating Systems Where to Find Source Code and LAB Files Which Setup Files to Use z/vm EXEC Operator Messages EMPLOYEE Table Source Code LAB6 and LAB7 Macros Source Code EMPLOYEE Table Glossary Index Teradata Preprocessor2 for Embedded SQL Programmer Guide 15

16 Table of Contents 16 Teradata Preprocessor2 for Embedded SQL Programmer Guide

17 List of Figures Figure 1: PP2 Operation Teradata Preprocessor2 for Embedded SQL Programmer Guide 17

18 List of Figures 18 Teradata Preprocessor2 for Embedded SQL Programmer Guide

19 List of Tables Table 1: Upgrading PP2 and CLIv2 on UNIX and LINUX Table 2: Supported Host Programming Languages Listed by Operating System Table 3: OPTIONS, SOURCE, and XREF Section Information Table 4: Teradata-Defined Character Sets for Mainframe Environments Table 5: Site-Defined Character Sets for Mainframe Environments Table 6: Teradata-Defined Character Sets for Network-Attached Environments Table 7: Site-Defined Character Sets for Network-Attached Environments Table 8: C Definitions for Teradata Database Data Types Table 9: COBOL Definitions for Teradata Database Data Types Table 10: PL/I Definitions for Teradata Database Data Types Table 11: SQL Data Type Codes Teradata Preprocessor2 for Embedded SQL Programmer Guide 19

20 List of Tables 20 Teradata Preprocessor2 for Embedded SQL Programmer Guide

21 CHAPTER 1 Introduction Teradata Preprocessor2 for Embedded SQL, PP2, provides an easy-to-use method of accessing data stored in the Teradata Database. PP2 does this by interpreting and expanding Teradata SQL statements that have been embedded in an application program. Interpretation of the statements allows the program to perform tasks supported by Teradata SQL, such as data retrieval. The application program is called an embedded SQL host program. The language in which the host program is written is called the host programming language. Therefore, the host program consists of Teradata SQL code that provides the database interface, plus the host programming language, which provides remaining instructions for application execution. Review the next sections in this chapter for information on: PP2 Processes Using Static and Dynamic SQL Upgrading PP2 and CLIv2 Supported Operating Systems and Host Programming Languages PP2 Input PP2 Output Contents of PP2 Output Listing Diagnostic Messages Client Language Source Code Server Failure and Recovery Finding Information PP2 Processes PP2 includes a precompiler as well as the services that execute, or provide runtime support for a compiled application. A precompiler is necessary to interpret the embedded SQL statements in the host program. Regardless of the host language, PP2 operation consists of two stages: 1 The precompile phase, which precedes application compilation and linking. 2 Execution, or runtime support, of the application. During precompilation, PP2 reads and replaces all the SQL statements embedded in the host program with CLIv2 calls that are acceptable to the native compiler for the host language. The host programming language syntax remains unchanged. Teradata Preprocessor2 for Embedded SQL Programmer Guide 21

22 Chapter 1: Introduction PP2 Processes At runtime, the inserted syntax runs in conjunction with Call-Level Interface version 2 (CLIv2) and Teradata Director Program (TDP) modules to provide an efficient, convenient interface between the application program and the Teradata Database. Note: In a mainframe environment, a TDP module must be started prior to PP2 performing the precompile step, even if no data access is required (that is, using NOSYNTAX). The following example uses a COBOL program to show the operations PP2 performs, from logging on to the Teradata Database through precompilation. The process is similar for other languages: 1 Logs a session onto the Teradata Database and determines whether it is to be a Teradata mode or ANSI-compatible mode session. 2 Checks the syntax of SQL statements in the host language source program, validating database objects against the entries in the Data Dictionary. 3 Builds code in the DATA division for the data elements. 4 Builds code in the PROCEDURE division to handle SQL statement passing to the Teradata Database. 5 Comments out the SQL source code. 6 Produces COBOL source for input to the COBOL compiler. Figure 1 gives a high-level view of starting with a PL/I embedded SQL program as the source input file, then precompiling, compiling, linking, and finally, running the PL/I program. Figure 1: PP2 Operation PL/I PP2 PL/I embedded SQL programs CICS precompiler In CICS environment precompiler Translates embedded SQL into appropriate host language COMPILE LOAD/LINK (For CICS, use Teradata CICS libraries) EXECUTION Execute program with communication to Teradata RDBMS 2446B Teradata Preprocessor2 for Embedded SQL Programmer Guide

23 Chapter 1: Introduction Using Static and Dynamic SQL Using Static and Dynamic SQL Both static and dynamic SQL statements are allowed in the embedded SQL host program. Static SQL statements, as the name implies, remain static each time the program is run. Dynamic SQL statements are built at runtime. To use static SQL statements in a host program, be sure to know the SQL statement type, plus database table and column names when the program is written. Only the specific data values the statement is looking for are unknown. Use host language variables to represent those unknown values. For example, use a static SQL statement to enter an order, and a host language variable to represent the quantity of an item in the order. Because static SQL statements are hard-coded into the program, the statements require parsing, and so forth, only once. Therefore, using static SQL tends to result in faster processing. Dynamic SQL is useful for programs where the content of a SQL statement is un-known at the time the program is written. For example, an interactive application that prompts the user for a table name, would be a good situation in which to use dynamic SQL. Each host programming language handles dynamic SQL statements differently. Refer to Writing Embedded SQL Applications in C, Writing Embedded SQL Applications in COBOL, Writing Embedded SQL Applications in PL/I, and Embedded SQL Examples for more information. Upgrading PP2 and CLIv2 Mainframe and Windows Platforms When upgrading to a newer version of the Teradata Database, install the latest versions of Teradata Preprocessor2 for Embedded SQL and CLIv2.When you upgrade to a newer version of Teradata Warehouse, install the latest versions of PP2 and CLIv2. UNIX/LINUX Platforms If you have not made changes to the source code in your existing application programs, execute your programs using the latest versions of PP2 and CLIv2. It is not necessary to precompile, compile, and link the existing applications again. If you have made changes to the source code in the existing application programs, run the PP2 precompiler, compile, then link the applications. When you upgrade to a newer version of Teradata Warehouse, install the latest versions of PP2 and CLIv2. Refer to Table 1 for instructions on whether or not it is necessary to precompile, compile, and link existing applications before executing them with the new PP2 and CLIv2 versions. Teradata Preprocessor2 for Embedded SQL Programmer Guide 23

24 Chapter 1: Introduction Supported Operating Systems and Host Programming Languages Table 1: Upgrading PP2 and CLIv2 on UNIX and LINUX Have you made changes to the source code in your existing application program? 32-Bit Platforms 64-Bit Platforms no Relink the application with the latest PP2 runtime library. If the application was last precompiled with TTU 8.2 PP2, relink the application with the latest PP2 runtime library. If the application was last precompiled with a version of PP2 earlier than TTU 8.2 PP2: precompile, compile, then link the application again. yes Precompile, compile, then link the application again. Supported Operating Systems and Host Programming Languages PP2 operates with host programming languages in several environments: Table 2: Supported Host Programming Languages Listed by Operating System Operating System HP-UX 11.0, 11.11, and 11i (PA-RISC 2) (32- bit) HP-UX 11.0, 11.11, and 11i (PA-RISC 2) (64- bit) HP-UX and (Itanium) (64-bit) IBM AIX 5.1 (32-bit) IBM AIX 5.2 (64-bit) IBM AIX 5.1 (64-bit) IBM AIX 5.2 (32-bit) IBM AIX 5.3 (32-bit) IBM AIX 5.3 (64-bit) IBM z/os (MVS) Note: USS is not supported. IBM z/vm Microsoft Windows bit SP4 Host Programming Language C and Micro Focus COBOL (32-bit) C (32-bit or 64-bit) C (64-bit) C and Micro Focus COBOL (32-bit) C (32-bit and 64-bit) C (32-bit and 64-bit) C and Micro Focus COBOL (32-bit) C and Micro Focus COBOL (32-bit) C and Micro Focus COBOL (64-bit) SAS/C, IBM COBOL, IBM PL/I (32-bit) SAS/C, IBM COBOL, IBM PL/I (32-bit) C (32-bit) 24 Teradata Preprocessor2 for Embedded SQL Programmer Guide

25 Chapter 1: Introduction Supported Operating Systems and Host Programming Languages Table 2: Supported Host Programming Languages Listed by Operating System (continued) Operating System Microsoft Windows.NET Server 2003 (32-bit or 64-bit) Microsoft Windows Server 2003, Standard Edition/Enterprise Edition on Intel EM64T Microsoft Windows Vista Microsoft Windows XP Professional (32-bit or 64-bit) Microsoft Windows XP Professional on Intel EM64T Novell SUSE Linux Enterprise 9 on 32-bit Intel x86 Novell SUSE Linux Enterprise 9 on Intel EM64T Novell SUSE Linux Enterprise 9 and 10 on 64-bit AMD Opteron RedHat Enterprise Linux Advanced Server 4.0 on AMD Opteron Red Hat Linux Advanced Server 2.1 and 3.0 (32-bit) RedHat Linux Advanced Server 4.0 on 32-bit Intel x86 RedHat Linux Advanced Server 4.0 on Intel EM64T Red Hat Linux Advanced Server 4.0 and above on 64-bit AMD Opteron Red Hat Linux Itanium 64-bit Advanced Server 3.0 SUN Solaris 8 and 9 SPARC (32-bit) SUN Solaris 8 and 9 SPARC (64-bit) SUN Solaris 10 on 64-bit AMD Opteron Host Programming Language C (32-bit and 64-bit) C (32-bit and 64-bit) C (32-bit and 64-bit) C (32-bit and 64-bit) C (32-bit and 64-bit) C (32-bit) C (32-bit and 64-bit) C (32-bit and 64-bit) C (32-bit and 64-bit) C (32-bit) C (32-bit) C (32-bit and 64-bit) C (32-bit and 64-bit) C (64-bit) C (32-bit) C (32-bit and 64-bit) C (32-bit and 64-bit) UNIX MP-RAS C, Micro Focus COBOL and LPI COBOL (32- bit) Note: The IBM mainframes are channel-attached to the NCR hardware platform running the Teradata Database. Other environments are referred to as network-attached systems. Teradata Preprocessor2 for Embedded SQL Programmer Guide 25

26 Chapter 1: Introduction PP2 Input PP2 Input The PP2 input file is the embedded SQL host program (also called the source input file). Depending on the program environment, one or more additional files are required in addition to the PP2 input file if when using an SQL INCLUDE statement.the PP2 input file is the embedded SQL host program (also called the source input file). Depending on the program environment, one or more additional files are required in addition to the PP2 input file if you use a SQL INCLUDE statement. PP2 Output The source output program is the source input program as modified by PP2. Modifications to the program include: Inclusion of host language comments that identify the program as output from PP2 and that provide the date and time of precompilation. These comments are inserted near the beginning. Conversion of all embedded Teradata SQL statements to host language comments. Insertion of host data variable declarations and procedural statements to implement the embedded Teradata SQL statements. Contents of PP2 Output Listing The output listing is headed by release number and date and time information (see Release Number Information on page 26). The next three sections of the listing are based on the OPTIONS, SOURCE, and XREF PP2 options (see OPTIONS, SOURCE, and XREF Sections on page 27). The line-by-line listing of the input program is augmented by: An analysis of the PP2 options specified and defaulted Input line numbers assigned by PP2 PP2 diagnostics Cross-references of host variables, cursor, and dynamic statement names A summary of diagnostics A summary of input and output file record counts Release Number Information The first block of the PP2 output listing indicates the date and time of compilation, the PP2 release number, and, if known, the Teradata Database release number. When precompiling using the NOSYNTAX option or if the Teradata Database level is earlier than V2R6.2, the 26 Teradata Preprocessor2 for Embedded SQL Programmer Guide

27 Chapter 1: Introduction Contents of PP2 Output Listing Teradata Database release number does not display. Here is an example where the Teradata Database release number is not known: /* THIS PROGRAM WAS PREPROCESSED ON JAN 30, 2006 AT 12:08:48 BY THE C PREPROCESSOR2 PREPROCESSOR SOFTWARE RELEASE: PP DBS N/A */ OPTIONS, SOURCE, and XREF Sections Table 3: OPTIONS, SOURCE, and XREF Section Information Section The section contains: Output/suppression of this section is controlled by this option: Other information OPTIONS PP2 options that have been specified at invocation options used by PP2 option errors detected by PP2 OPTIONS/NOOPTIONS This section does not contain specified userid. SOURCE the same source that is input to PP2. The section format depends on the host language and includes line numbers known to PP2 and any included lines brought in via EXEC SQL INCLUDE statements. source errors detected by PP2 SOURCE/NOSOURCE - XREF host variable, cursor, and dynamic statement declarations and usages summary of input/output records summary of the warnings and errors detected by PP2 XREF/NOXREF Asterisks in the variable declaration type field indicate that the size of the field exceeds the capability of the cross reference. However, this variable remains valid for use in SQL requests. Teradata Preprocessor2 for Embedded SQL Programmer Guide 27

28 Chapter 1: Introduction Diagnostic Messages PRINT Option The PRINT option must be in effect for the output listing to be produced. The listing is placed in the file specified or defaulted for the PRINT option. No listing is produced if the NOPRINT PP2 option is specified. Diagnostic Messages Message Form Diagnostic messages returned by PP2 occupy two lines and take the following form: SPPnnnn <severity>, at line nnn, column nn: <diagnostic message text> where <severity> is one of the following: Warning SQL Flagger Warning Error Severe Error Fatal Error SPPnnnn is an identifying value unique to PP2. The qualifying phrases at line nnn and column nn vary to suit conditions. If the diagnostic originates with the Teradata Database, the message begins with a four digit Teradata error code. See Messages. Client Language Source Code PP2 produces client language source code as a result of the precompilation. Code generation is enabled or suppressed via the PUNCH/NOPUNCH option. The code is placed in the file specified or is defaulted for the PUNCH option. No code is produced if the NOPUNCH PP2 option is specified. C and COBOL code generation is also suppressed if an error is encountered during the precompilation phase. Server Failure and Recovery This section describes the behavior of PP2 and Teradata Database-generated applications when they encounter a node reset. 28 Teradata Preprocessor2 for Embedded SQL Programmer Guide

29 Chapter 1: Introduction Server Failure and Recovery PP2 Behavior If Teradata Preprocessor2 for Embedded SQL is running on a Resetting node Non-Resetting node LAN-attached client Channel-attached client Then it aborts. Preprocessing must be restarted after the node resets. This is equivalent to the situation where a utility or application is initiated on an external client that fails. reconnects its session (if connected to a server) and the current SQL statement undergoing a syntax check returns an error. Restart preprocessing to ensure complete syntax checking. Application Behavior The behavior of Teradata Database-generated applications in the event of a node resetting depends on the: Crash notification setting Type of node on which PP2 is running Application Behavior on a Resetting Node IF a PP2-generated application is running on a Resetting node THEN it aborts. Restart the application after the node resets. This is equivalent to the situation where a utility or application is initiated on an external client that fails. Setting Crash Notification Specify crash notification behavior with the SET CRASH statement, which sets the following wait_across_crash (WAC) and tell_about _crash (TAC) options: IF specified... THEN WAC is set to... AND TAC is set to... WAIT_NOTELL Y N NOWAIT_TELL N Y The default settings for these options are: wait_across_crash (WAC) = Y tell_about_crash (TAC) = N Teradata Preprocessor2 for Embedded SQL Programmer Guide 29

30 Chapter 1: Introduction Server Failure and Recovery For information on GET CRASH and SET CRASH, see SQL Reference: Stored Procedures and Embedded SQL. Application Response When WAC is Set to Y and TAC is Set to N The following table describes the behavior of PP2-generated applications when a node resets and WAC = Y and TAC = N. IF a PP2-generated application is running on a Non-Resetting node LAN-attached client Channel-attached client THEN it reconnects its session and returns one of the following error codes from the server and the PP2-generated application takes action appropriate to the error condition: Code Number Error 2825 Error 2826 Error 2828 Error 3120 Description No record of the last request was found after the Teradata Database restart. Request completed but all output was lost due to Teradata Database restart. Request was rolled back during system recovery. The request is aborted because of a Teradata Database recovery. Application Response When WAC is Set to N and TAC is Set to Y The following table describes the behavior of PP2-generated applications when a node resets and WAC = N and TAC = Y. IF a PP2-generated application is running on a Non-Resetting node LAN-attached client Channel-attached client THEN it immediately disconnects the session and the application receives one of the following CLI error codes: Code Number Description Error 219(EM_DBC_CRASH_B) Error 220(EM_DBC_CRASH_A) Server connection lost (network or server problem). Server connection lost (network or server problem). 30 Teradata Preprocessor2 for Embedded SQL Programmer Guide

31 Chapter 1: Introduction Query Banding Query Banding A query band is a set of name-value pairs that can be set on a session or transaction to identify a query's originating source. The query band enables users to add their own identifiers to the current set of session identification fields. Without query bands, the pooling mechanisms that SQL-generating tools and web applications use hide the identity of users because each connection in the pool logs into the database using the same user account. Therefore, there is no way to tell the source of the request when the request comes from a multi-tiered application. The Query Band feature enables requests coming from a single logon process to be classified into different workloads based on the query band that is set by the originating application. Query banding also enables an application to set different priorities for different requests. The application can set a different query band for each type of job, causing the requests to be classified into different workloads. Then the different workloads can run at different priorities, instead of running the entire application at a high priority. By adjusting the priorities of its requests, the application can enable better use of system resources. A session query band is stored in a session table and recovered after a system reset. A transaction query band is discarded when the transaction ends (commits, rolls back, or aborts). The syntax of SET QUERY_BAND is: <set_query_band> ::= SET QUERY_BAND = <query_band_attribute> FOR <session_or_txn>; <query_band_attribute> ::= <query_band expression> NONE <session_or_txn> ::= SESSION TRANSACTION <query_band expression> ::= <quote> <pair chain> <quote> <pair chain> ::= <name-value pair> [<name-value pair>?] <name-value pair> ::= <pair name> <equal sign> <pair value> <semicolon operator> <pair name> ::= <character representation> <pair value> ::= <character representation> For example: EXEC SQL SET QUERY_BAND = 'priority=1;workload=high;' FOR SESSION ; Finding Information The following table provides pointers to the Teradata Database SQL Reference book set, which provides detailed information on programming with SQL: Teradata Preprocessor2 for Embedded SQL Programmer Guide 31

32 Chapter 1: Introduction Finding Information This topic Is found in this chapter / appendix Of Session management SQL Data Handling SQL Reference: Fundamentals Return codes Statement responses Introduction to Embedded SQL SQL Data Definition, Control, and Manipulation Host structures Embedded SQL SQL Reference: Stored Procedures Host variables and Embedded SQL Input host variables Output host variables SQL character strings as host variables Multistatement requests with embedded SQL SQL statements for miscellaneous embedded SQL activities Static Embedded SQL Statements BEGIN DECLARE SECTION COMMENT (returning form) DATABASE DECLARE TABLE DELETE (positioned form) END DECLARE SECTION END-EXEC EXEC EXEC SQL INCLUDE INCLUDE SQLCA INCLUDE SQLDA SELECT INTO SELECT AND CONSUME INTO Note: Teradata Preprocessor2 for Embedded SQL does not support SELECT AND CONSUME within cursors. UPDATE (positioned form) WHENEVER Dynamic SQL statement syntax EXECUTE EXECUTE IMMEDIATE PREPARE Dynamic Embedded SQL Statements 32 Teradata Preprocessor2 for Embedded SQL Programmer Guide

33 Chapter 1: Introduction Finding Information This topic Is found in this chapter / appendix Of SQL statements for client-server connectivity Client-Server Connectivity Statements CONNECT GET CRASH LOGOFF LOGON SET BUFFERSIZE SET CHARSET SET CONNECTION SET CRASH SET ENCRYPTION SQL statements for multisession programming ASYNC TEST WAIT SQL statements for cursor declaration and manipulation CLOSE DECLARE CURSOR FETCH FETCH (for scrollable cursor) OPEN POSITION REWIND SQLSTATE variable Multisession Asynchronous Programming with Embedded SQL SQL Cursor Control and DML Statements Result Code Variables SQLCODE variable ACTIVITY_COUNT variable SQL Descriptor Area (SQLDA) SQL Communications Area (SQLCA) SQL Descriptor Area (SQLDA) SQL Communications Area (SQLCA) Security Administration provides information on the LOGDATA and LOGMECH commands. Teradata Preprocessor2 for Embedded SQL Programmer Guide 33

34 Chapter 1: Introduction Finding Information 34 Teradata Preprocessor2 for Embedded SQL Programmer Guide

35 CHAPTER 2 Connecting to the Database and Invoking PP2 The normal sequence of operations when using PP2 is to connect to the Teradata Database, then invoke PP2 to run against the embedded SQL host program. This chapter discusses these operations, plus exceptions (for example, it is not necessary to connect to the Teradata Database before you invoke PP2). The chapter also includes PP2 options, which allow control of the preprocessing environment of an application module. Connecting to the Teradata Database Invoking PP2 PP2 Options Connecting to the Teradata Database No association exists between the PP2 connection to the Teradata Database made at precompile time and the connection made by an application at execution time. Embedded LOGON and CONNECT statements have no effect on the PP2 connection. Conversely, tdpid and userid PP2 options do not affect the application logon at execution time. For more information, refer to USERID(userid[,password[,accountid]]) -u userid[,password[,accountid]] on page 77. Normal operation, however, means connecting to the Teradata Database for the precompilation and application execution phases. This requires: tdpid userid password for the specified userid If you do not specify a tdpid, the connection is made using the system default. The runtime returns a positive SQLCODE value and sets SQLWARN0 and SQLWARN2 to W. The next table lists the system defaults for IBM mainframes and network-attached systems. Teradata Preprocessor2 for Embedded SQL Programmer Guide 35

36 Chapter 2: Connecting to the Database and Invoking PP2 Connecting to the Teradata Database IF your application runs on this platform IBM mainframe network-attached system THEN the default tdp is obtained from the HSHSPB data area module (see Teradata Call-Level Interface Version 2 Reference for Channel-Attached Systems for details.) the mtdpid, obtained from the user-defined clispb.dat file or the CLI2SPB data area. For more information about userid security, tdpids, and userids, see Teradata Director Program Reference. PP2 Connection It is possible to run PP2 against an application without connecting to the Teradata Database, depending on the SQLCHECK option you have chosen. IF you specify the SQLCHECK option as NOSYNTAX FULL (or use FULL as the default) SQLFLAGGER(ENTRY) THEN PP2 does not require connection to the Teradata Database. requires connection to the Teradata Database. Establish PP2 connection by using the TDPID and USERID PP2 options. If you provide no USERID and PP2 is operating in the IBM mainframe environment, an implicit connection is attempted (see Implicit Connection on page 39 for more information on implicit connections). Runtime Execution Connection At runtime execution, connection to the Teradata Database is made either explicitly or implicitly. The transaction mode (ANSI, BTET, COMMIT or 2PC) for a session is established when the connection (either explicit or implicit) is made. The mode is based on the TRANSACT PP2 option for the program that established the session. Explicit Connection An application may specify its connection to the Teradata Database explicitly via the CONNECT or the LOGON statement, which are described in SQL Reference: Stored Procedures and Embedded SQL. Explicit connection permits precise control over which tdp and userid to connect to. Implicit connection uses system defaults for the tdp and userid. (See Implicit Connection on page 39). For this reason, any time you need to connect to a nondefault tdp or userid, make an explicit connection. 36 Teradata Preprocessor2 for Embedded SQL Programmer Guide

37 Chapter 2: Connecting to the Database and Invoking PP2 Connecting to the Teradata Database Explicit connections are generally advocated because of this precise control, even when default tdps and userids are satisfactory for your required level of security. IF you specify this statement CONNECT LOGON THEN you can specify only the userid and password. The tdpid is taken from the system default value. The CONNECT userid and password are each restricted to eight characters. This statement is IBM SQL-compatible. a complete Teradata Database logon string, including tdpid and accountid. The userid and password each may be a maximum of 30 characters. Note: On Windows platforms only: 1 The <userid> and <password> are optional on Windows NT. 2 A LOGON string without a <userid> and <password> will be interpreted as an SSO logon. IF an explicit connection request is made AND THEN the application is already connected to the Teradata Database the previous connection is dropped before the new connection is attempted. a transaction is active the connection request is rejected with a SQLCODE of the application must terminate the current transaction explicitly using one of the following before attempting to issue a new explicit connection request: COMMIT ROLLBACK (or ABORT) LOGOFF Extended Security with LOGMECH and LOGDATA Network versions of PP and above support LOGMECH and LOGDATA statements for use with logon mechanisms. The channel attached (mainframe) version of PP2 does not support these statements. Teradata Preprocessor2 for Embedded SQL Programmer Guide 37

38 Chapter 2: Connecting to the Database and Invoking PP2 Connecting to the Teradata Database Syntax LOGMECH type LOGDATA:data_address type data_address The logon mechanism type, such as KRB5 or NTLM. The host variable name containing the data to be passed to the logon mechanism. The value is entirely dependent on the LOGMECH type. C Example EXEC SQL BEGIN DECLARE SECTION; VARCHAR LOGON_STRING[40]; VARCHAR LOGDATA_STRING[40]; EXEC SQL END DECLARE SECTION; EXEC SQL LOGMECH LDAP; strcpy (LOGDATA_STRING.arr, "authcid=guestldap password=password"); LOGDATA_STRING.len = strlen(logdata_string.len); EXEC SQL LOGDATA :LOGDATA_STRING; strcpy (LOGON_STRING.arr, "tdname"); LOGON_STRING.len = 6; EXEC SQL LOGON :LOGON_STRING; Cobol Example 01 LOGON-STRING. 49 FILLER PIC S9(4) COMP VALUE FILLER PIC X(5) VALUE 'TDP1/'. 01 LOGDATA-STRING. 49 FILLER PIC S9(4) COMP VALUE FILLER PIC X(28) VALUE '[email protected]@@PASSWORD EXEC SQL LOGMECH KRB5 END-EXEC. EXEC SQL LOGDATA :LOGDATA-STRING END-EXEC. EXEC SQL LOGON :LOGON-STRING END-EXEC. If you use LOGMECH and LOGDATA statements to pass logon credentials to the database, it may not be necessary to use the default LOGON dialog box in GUI applications. It depends on 38 Teradata Preprocessor2 for Embedded SQL Programmer Guide

39 Chapter 2: Connecting to the Database and Invoking PP2 Invoking PP2 Implicit Connection the type of logon mechanism that you use. To disable the LOGON dialog box, specify GUILOGON=NO as an environmental variable. If a PP2 application running in an IBM mainframe environment submits a SQL request without specifying an explicit connection to the server, an implicit connection is attempted, based on the job or session under which the application is running. However, network-attached platforms do not provide an implicit connection mechanism. See Teradata Call-Level Interface Version 2 Reference for Network-Attached Systems for details of the implicit connection mechanism. Invoking PP2 PP2 operates in a number of mainframe or network-attached environments. See Supported Operating Systems and Host Programming Languages on page 24 for more information. PP2 accepts a number of options that control the operating characteristics. The next sections discuss these options and how to invoke PP2 in different environments. IBM Mainframe Environment: z/os and z/vm CMS Note: Before invoking PP2 in a mainframe environment, start at least one TDP module on the mainframe, even if no data access is required (that is, using NOSYNTAX). If a precompile step is performed prior to starting a TDP module, a fatal error occurs. You can invoke PP2 as a: z/os batch program using a JCL (job control language) procedure. z/os TSO batch or TSO online program, either directly or using a CLIST. Teradata Preprocessor2 for Embedded SQL Programmer Guide 39

40 Chapter 2: Connecting to the Database and Invoking PP2 Invoking PP2 Operating PP2 in an IBM z/os or z/vm mainframe environment involves these files: File Name Usage Requirement SYSLIB Library input Required if the embedded SQL INCLUDE text name statement is used and PP2 is executing in the z/os environment. SYSIN Source input Mandatory SYSPRINT Listing Required unless the NOPRINT option is specified. z/os JCL must define DCB information for LRECL, RECFM and BLKSIZE parameters. SYSTERM Diagnostics Required if the TERM option is present. z/os JCL must define DCB information for LRECL, RECFM and BLKSIZE parameters. SYSPUNCH Source output Required unless the NOPUNCH option is specified. z/os JCL must define DCB information for LRECL, RECFM and BLKSIZE parameters. SYSUT1 Work file 1 z/os JCL must define DCB information for LRECL, RECFM and BLKSIZE parameters. Required for C and COBOL precompilation. z/os Batch When running PP2 in the z/os batch environment, use standard z/os job control language (JCL). The next example shows preprocessor invocation JCL stream for the COBOL preprocessor. Line numbers relate to the notes following the code and are not part of the JCL syntax. //PRECOMP JOB (job statement information) 1 //PRECOMP EXEC PGM=PPBMAIN, // PARM= option option 2 //STEPLIB DD DSN=TERADATA.TRLOAD,DISP=SHR 3 //DD DSN=TERADATA.APPLOAD,DISP=SHR 4 //SYSPRINT DD SYSOUT=*, //DCB=(LRECL=133,RECFM=FBA,BLKSIZE=1330) 5 //SYSTERM DD DUMMY 6 //SYSLIB DD DSN=customer.include.library,DISP=SHR 7 //SYSPUNCH DD DSN=customer.compiler.input, // UNIT=SYSDA,SPACE=(TRK,(5,5)), // DCB=(LRECL=80,RECFM=FB,BLKSIZE=3600) // DISP=(NEW,CATLG) 8 //SYSIN DD DSN=customer.preproc.input,DISP=SHR 9 //SYSUT1 DD UNIT=SYSDA,SPACE=(CYL,(5,2)), // DCB=(LRECL=80,RECFM=FB,BLKSIZE=3600) // 40 Teradata Preprocessor2 for Embedded SQL Programmer Guide

41 Chapter 2: Connecting to the Database and Invoking PP2 Invoking PP2 Note: 1) The PARM field specifies the options to be used by the preprocessor; within the PARM field, options must be separated by commas and/or blanks. For details on the options, see PP2 Options on page 45. 2) This STEPLIB partitioned data set is the Teradata-supplied C runtime library. 3) This STEPLIB partitioned data set contains the preprocessor load module: PPBMAIN (COBOL) PPIMAIN (PL/I) PPCMAIN (C) 4) SYSPRINT receives the preprocessor listing. SYSPRINT is required unless the NOPRINT option is specified. The required DCB parameters are: LRECL RECFM BLKSIZE 5) SYSTERM receives the preprocessor diagnostics, separated from the preprocessor listing. SYSTERM is required when the TERM option is specified. The required DCB parameters are: LRECL RECFM BLKSIZE 6) The SYSLIB partitioned data set contains the preprocessor include members. SYSLIB is required if the embedded SQL INCLUDE text name statement is used. 7) SYSPUNCH receives the precompiler source. SYSPUNCH is required unless the NOPUNCH option is specified. SYSPUNCH may be temporary if the appropriate host language compiler is invoked in a following job step. The required DCB parameters are: LRECL RECFM BLKSIZE 8) SYSIN contains the preprocessor source input. Teradata Preprocessor2 for Embedded SQL Programmer Guide 41

42 Chapter 2: Connecting to the Database and Invoking PP2 Invoking PP2 9) SYSUT1 is a preprocessor work file. UNIT=VIO may be used instead of UNIT=SYSDA. The required DCB parameters are: LRECL RECFM BLKSIZE Required for C and COBOL precompilation. z/os TSO When running PP2 in an z/os TSO environment, use standard TSO commands. You can create a command list to simplify this process. The next example shows a preprocessor invocation command stream for COBOL. Line numbers relate to the notes following the code and are not part of the syntax. ATTR VBA1330 RECFM(V,B,A) LRECL(133) BLKSIZE(1330) ATTR F80 RECFM(F) LRECL(80) BLKSIZE(80) ATTR FB3120 RECFM(F,B) LRECL(80) BLKSIZE(3120) 1 ALLOCATE DDNAME(CTRANS) DATASET( TERADATA.TRLOAD ) SHR 2 ALLOCATE DDNAME(SYSPRINT) SYSOUT(A) USING(VBA1330) 3 ALLOCATE DDNAME(SYSTERM) DATASET(*) USING(F80) 4 ALLOCATE DDNAME(SYSLIB) + DATASET( customer.include.library ) SHR 5 ALLOCATEDDNAME(SYSPUNCH) + DATASET( customer.fompiler.input ) NEW + TRACKS SPACE(5,5) USING(FB3120) 6 ALLOCATEDDNAME(SYSIN) + DATASET( customer.preproc.input ) SHR 7 ALLOCATEDDNAME(SYSUT1) NEW BLOCK(1024) SPACE(50,50) 8 CALL TERADATA.APPLOAD(PPBMAIN) + option option FREE DDNAME(CTRANS) FREE DDNAME(SYSPRINT) FREE DDNAME(SYSTERM) FREE DDNAME(SYSLIB) FREE DDNAME(SYSPUNCH) FREE DDNAME(SYSIN) FREE DDNAME(SYSUT1) FREE ATTRL(VBA1330) FREE ATTRL(F80) FREE ATTRL(FB3120) Note: 1) The CTRANS data set is the Teradata-supplied C runtime library. 2) The SYSPRINT data set receives the preprocessor listing. SYSPRINT is required unless you specify the NOPRINT option. 3) The SYSTERM data set receives the preprocessor diagnostics, separated from the preprocessor listing. SYSTERM is required only if you specify the TERM option. 42 Teradata Preprocessor2 for Embedded SQL Programmer Guide

43 Chapter 2: Connecting to the Database and Invoking PP2 Invoking PP2 4) The SYSLIB partitioned data set contains the preprocessor include members. SYSLIB is required only if you specify the embedded SQL INCLUDE text name statement. 5) The SYSPUNCH data set receives the precompiler source. SYSPUNCH is required unless you specify the NOPUNCH option. 6) The SYSIN data set contains the preprocessor source input. 7) The SYSUT1 data set is a preprocessor work file. 8) TERADATA.APPLOAD contains the preprocessor load module - PPBMAIN (COBOL), PPIMAIN (PL/I) or PPCMAIN (C). The CALL parameter specifies the PP2 options to be used; within the parameter, you must separate options by commas and/or blanks. For details on the options, see PP2 Options on page 45. z/vm CMS Use standard CMS commands when running PP2 in a z/vm CMS environment. You can create an EXEC to simplify this process. The next example shows a preprocessor invocation command stream for COBOL. Line numbers relate to notes following the code. 1 GLOBAL TXTLIB COBLIBVS TSOLIB CMSLIB CLI 2 GLOBAL LOADLIB LSCRTL 3 FILEDEF SYSPRINT PRINTER (RECFM VA LRECL 121) 4 FILEDEF SYSTERM TERMINAL (RECFM F LRECL 80) 5 FILEDEF SYSPUNCH DISK compiler input (RECFM F LRECL 80) 6 FILEDEF SYSIN DISK preproc input 7 FILEDEF SYSUT1 DISK SQLPPUT1 DATA A3 8 PPBMAIN option option FILEDEF SYSPRINT CLEAR FILEDEF SYSTERM CLEAR FILEDEF SYSPUNCH CLEAR FILEDEF SYSIN CLEAR FILEDEF SYSUT1 CLEAR Teradata Preprocessor2 for Embedded SQL Programmer Guide 43

44 Chapter 2: Connecting to the Database and Invoking PP2 Invoking PP2 Note: 1) Specifies the libraries needed to resolve included members. In the preprocessor, the libraries are used only with the SQL INCLUDE statement. 2) Specifies the location of the PPBMAIN module. 3) Specifies the print output to which the preprocessor listing is sent. This command is required unless the NOPRINT option is specified. 4) Specifies the location of preprocessor diagnostics. This is required only if the TERM option is specified. 5) Specifies the output of the preprocessor, which is the input to the compiler. 6) Specifies the input to the preprocessor. The input, which is your application, includes any embedded SQL statements. 7) Specifies a work file location. 8) Each option should be separated by a space. Network-Attached Environments In the network-attached environment, PP2 operates on UNIX and Windows. PP2 operation in these environments is described in the sections that follow. PP2 supports both 32-bit and 64-bit platforms on AIX, HP-UX, Linux, Solaris, and Windows. UNIX Use standard commands to invoke the process when running PP2 in a UNIX environment. The next example shows an invocation for the C preprocessor. Line numbers relate to the notes following the code and are not part of the syntax. 1 ppcmain option option \ 2 -Include (infile) (outfile) Note: 1) Separate the options with a space. 2) (infile) designates the preprocessor source input filename. (outfile) designates the precompiler output. Windows Use standard commands to invoke the process when running PP2 in an Windows environment. The next example shows an invocation for the C preprocessor. Line numbers relate to the notes following the code and are not part of the syntax. 1 ppcmain option option 2 /I<dir> <infile> <outfile> 44 Teradata Preprocessor2 for Embedded SQL Programmer Guide

45 Chapter 2: Connecting to the Database and Invoking PP2 PP2 Options 1 Separate the preprocessor options with blanks. 2 Use the /I to indicate the search path for embedded SQL INCLUDE text name statements; <infile> is a designator for the preprocessor source input filename. Specify <infile> by using the INPUT preprocessor option, -i filespec, or by the indirection operator <; <outfile> is a designator for the precompiler output. Specify <outfile> by using the PUNCH preprocessor option, -o filespec, or by the indirection operator >. 3 Surround each option by quotes ( ) when using the standard option syntax. PP2 Options PP2 options allow control of the preprocessing environment of an application module. The VERSION option specifies the target COBOL compiler. Use the SQLCHECK option to disable the logon to the server. Other options control other aspects of the preprocessing function. You can specify a maximum of 20 options. How to Read the Option Syntax Option specification is different for applications written for channel- or network-attached systems. This symbol (for channelattached systems) [] (for networkattached systems) Means OR For example, APOST QUOTE means you can specify either APOST or QUOTE (but not both). the enclosed variable is optional. Supported PP2 options are: Syntax for Channel-Attached Systems Syntax for Network-Attached Systems APOST QUOTE -a -q APOSTSQL QUOTESQL CHARSET (charset) CURPREFIX (prefix) -as -qs -cs charset -c prefix Teradata Preprocessor2 for Embedded SQL Programmer Guide 45

46 Chapter 2: Connecting to the Database and Invoking PP2 PP2 Options Syntax for Channel-Attached Systems DATABASE (dbname) DATE (D E I J U) DYNPREFIX (prefix) FLAG (I W E S) INPUT (file spec) LINECOUNT (integer) N/A N/A MARGINS (m,n [,c ] ) NULLSCAN NONULLSCAN OPTIONS NOOPTIONS PRINT [ (file spec) ] NOPRINT PUNCH [ (file spec) ] NOPUNCH SOURCE NOSOURCE SQLCHECK (FULL NOSYNTAX) SQLFLAGGER (NONE ENTRY INTERMEDIATE) TDPID (tdpid network group name) TERM [ (file spec) ] NOTERM TRANSACT (ANSI COMMIT BTET 2PC) USERID (userid [,password [,accountid ] ] ) VERSION (COBOL COBOLII MF1 MF2 LPI) XREF NOXREF Syntax for Network-Attached Systems -db dbname -d D E I J U -dp prefix -f I W E S -i filespec -lc integer -ld logdata -lm logmech -m m,n[,c] -ns -nns -lo -nlo -l [filespec] -nl -o [filespec] -no -ls -nls -sc FULL NOSYNTAX -sf NONE ENTRY INTERMEDIATE -t tdpid network group name -e [filespec] -ne -tr ANSI BTET COMMIT -u userid[,password[,accountid]] -v COBOL COBOLII MF1 MF2 LPI -lx -nlx Note: Whenever the DATABASE or USERID option values contain any Kanji or other multibyte character set characters, the CHARSET option must precede them in the preprocessor invocation line. 46 Teradata Preprocessor2 for Embedded SQL Programmer Guide

47 Chapter 2: Connecting to the Database and Invoking PP2 PP2 Options The file-spec variable used with some options takes the following forms: Client Type z/os mainframe z/vm CMS mainframe Network-attached File Spec ddname filedef_name name[.xtn] Note: If you specify associated PP2 options more than once (for example, both TERM and NOTERM), the rightmost specification prevails. The next pages describe PP2 options in detail. The UNIX-style syntax appears below the standard syntax. Teradata Preprocessor2 for Embedded SQL Programmer Guide 47

48 Chapter 2: Connecting to the Database and Invoking PP2 APOST QUOTE -a -q APOST QUOTE -a -q Purpose APOSTSQL specifies that for embedded SQL statements, the string delimiter is the apostrophe (') and that the SQL escape (name) delimiter is the quotation mark ("). Usage Notes Abbreviation for QUOTE Q Mutually Exclusive APOST and QUOTE This specification Is the default for Notes APOST APOST QUOTE COBOL and may be changed. Refer to the Notes column. PL/I and may not be changed. C and may not be changed. You can explicitly specify QUOTE for COBOL; if you do, also specify the COBOL compiler QUOTE option. Host language statements generated by PP2 obey the same conventions. These options do not affect string and SQL escape (name) delimiters in embedded SQL statements. See APOSTSQL QUOTESQL -as -qs on page Teradata Preprocessor2 for Embedded SQL Programmer Guide

49 Chapter 2: Connecting to the Database and Invoking PP2 APOSTSQL QUOTESQL -as -qs APOSTSQL QUOTESQL -as -qs Purpose APOSTSQL specifies that for embedded SQL statements, the string delimiter is the apostrophe (') and that the SQL escape (name) delimiter is the quotation mark ("). QUOTESQL specifies that in embedded SQL statements, the string delimiter is the quotation mark (") and that the SQL escape (name) delimiter is the apostrophe ('). Usage Notes APOSTSQL and QUOTESQL are mutually exclusive. QUOTESQL may not be explicitly specified for any language except COBOL. These options do not affect string delimiters in host language statements. This specification QUOTESQL APOSTSQL APOSTSQL APOSTSQL Is the default for COBOL, if QUOTE is specified. COBOL, if APOST is specified or defaulted. PL/I and may not be changed. C and may not be changed. Teradata Preprocessor2 for Embedded SQL Programmer Guide 49

50 Chapter 2: Connecting to the Database and Invoking PP2 CHARSET(charset) -cs charset CHARSET(charset) -cs charset Purpose Controls the mapping of data, object names and identifier values. Usage Notes CHARSET specifies the predefined character set name or character set code to be used at the following times: At this time precompile run This happens the CHARSET option tells the precompiler the character set in which your input/ output source files, the output listing, and output messages are written. the precompiler establishes the character set for communicating with the Teradata Database as the value of the CHARSET option unless overridden by the character set designated by the SET CHARSET request. For information on SET CHARSET, see SQL Reference: Data Definition Statements Subsequent connections to the Teradata Database use the most recently established character set. Specify the CHARSET option before the DATABASE or USERID operations if the DATABASE or USERID option values contain any Kanji or other multibyte character set characters. CHARSET controls the mapping of data, object names and identifier values. On IBM mainframe client platforms, if the CHARSET option is not specified, PP2 establishes the default character set by order of precedence: 1 Character set specified in the HSHSPB parameter module. 2 Default character set defined on the server specified by the TDPID option when SQLCHECK(FULL) is specified. 3 EBCDIC On network platforms, if the CHARSET option is not specified, PP2 establishes the default character set by order of precedence: 1 The character set specified in the clispb.dat file 2 ASCII UTF8 and UTF16 Support The Teradata Warehouse offers UTF8 (Universal Transformation Format) and UTF16 character set support. 50 Teradata Preprocessor2 for Embedded SQL Programmer Guide

51 Chapter 2: Connecting to the Database and Invoking PP2 CHARSET(charset) -cs charset See Table 4: Teradata-Defined Character Sets for Mainframe Environments on page 52 and Table 7: Site-Defined Character Sets for Network-Attached Environments on page 55 for details. Use the SET CHARSET control statement with these character sets. See SQL Reference: Stored Procedures and Embedded SQL for details. When you use the SET CHARSET control statement for processing UTF8 and UTF16 data, precompile PP2 applications using one of these PP2 options: CHARSET(EBCDIC) on mainframe systems -cs ASCII on network-attached systems Programming Considerations When Programming with UTF8 and UTF16 Character Sets Object Names in Embedded SQL When setting CHARSET to UTF16 on network-attached systems or when setting CHARSET to UTF8 and UTF16 on mainframe systems, avoid problems with object names in embedded SQL by coding in the following ways: Use only digits (0-9) and simple, single-byte Latin letters (A to Z, a to z). Because these characters always translate to the same internal representation, they appear exactly the same in any session, regardless of the client system or the character set. Do not use the hexadecimal representation to represent a character name. Host Variables or Constants and Literals in Embedded SQL When setting CHARSET to UTF16 on network-attached systems or when setting CHARSET to UTF8 and UTF16 on mainframe systems: Use host variables in the embedded SQL to supply UTF8 and UTF16 input values to or receive UTF8 and UTF16 output values from Teradata Database. Use host variables in the embedded SQL statements instead of UTF8 and UTF16 string constants. Use only digits and simple single byte Latin letters (A to Z, a to z) as constants in the EXEC SQL statements. The constants must be in the same charset encoding as the SQL keywords. When deciding size of a character string, remember that storage for UTF8 data is one to four bytes per character. Storage for UTF16 data is two bytes per character. Supported Character Sets There is support for Chinese and Korean character sets. UTF16 support is available on Microsoft Windows, UNIX, and mainframe environments. When Teradata-defined character sets are not appropriate for your site, create site-defined character sets. See Site-Defined Character Sets for Mainframe Environments on page 53 and Site-Defined Character Sets for Network-Attached Environments on page 55 for details. See SQL Reference: Fundamentals to learn about international character sets, character set restrictions, export rules, and defining your own character sets. Teradata Preprocessor2 for Embedded SQL Programmer Guide 51

52 Chapter 2: Connecting to the Database and Invoking PP2 CHARSET(charset) -cs charset Teradata-Defined Character Sets for Mainframe Environments Table 4: Teradata-Defined Character Sets for Mainframe Environments Character Set Name Character Set Code Number Description EBCDIC 192 Uppercase and lowercase English characters Special characters HANGULEBCDIC933_1II 108 Korean characters Uppercase and lowercase English characters Multibyte characters Special characters KATAKANAEBCDIC 111 Uppercase English characters katakana characters Special characters Note: Not supported for the C preprocessor. KANJIEBCDIC5026_0I 112 Uppercase and lowercase English characters katakana characters Multibyte characters Special characters Note: Not supported with the C preprocessor. KANJIEBCDIC5035_0I 113 Uppercase and lowercase English characters katakana characters Multibyte characters Special characters SCHEBCDIC935_21J 109 Simplified Chinese characters Uppercase and lowercase English characters Multibyte characters Special characters TCHEBCDIC937_3IB 110 Traditional Chinese characters Uppercase and lowercase English characters Multibyte characters Special characters UTF8 191 Compressed UNICODE (1-3 byte on Teradata) UTF byte UTF Teradata Preprocessor2 for Embedded SQL Programmer Guide

53 Chapter 2: Connecting to the Database and Invoking PP2 CHARSET(charset) -cs charset Site-Defined Character Sets for Mainframe Environments Table 5: Site-Defined Character Sets for Mainframe Environments Character set Name Character Set Code Number Language SDKATAKANAEBCDIC_4IF 77 Japanese SDKANJIEBCDIC5026_4IG 78 Japanese SDKANJIEBCDIC5035_4IH 79 Japanese SDSCHEBCDIC935_6IJ 75 Simplified Chinese SDTCHEBDIC937_7IB 76 Traditional Chinese SDHANGULEBCDIC933_5II 74 Korean Teradata Preprocessor2 for Embedded SQL Programmer Guide 53

54 Chapter 2: Connecting to the Database and Invoking PP2 CHARSET(charset) -cs charset Teradata-Defined Character Sets for Network-Attached Environments Table 6: Teradata-Defined Character Sets for Network-Attached Environments Character Set Name Character Set Code Number Description ASCII 255 Uppercase and lowercase English characters Special characters JISCII8 115 (Intel based platforms) 243 (non-intel based platforms) Uppercase and lowercase English characters katakana characters Multibyte characters Special characters HANGULKSC5601_2R4 120 Uppercase and lowercase English characters Multibyte characters Special characters KANJISJIS_0S KANJIEUC_0U 119 (Intel-based platforms) 247 (non-intel-based platforms) 118 (Intel-based platforms) 246 (non-intel-based platforms) The SHIFT+JIS character set used by PC clients running DOS/V. It includes: Uppercase and lowercase English characters katakana characters multibyte characters Special characters The Extended Unix Code multibyte character set combined with the ASCII character set for single byte characters. It includes: Uppercase and lowercase English characters katakana characters Multibyte characters Special characters SCHGB2312_1T0 108 Simplified Chinese characters Uppercase and lowercase English characters Multibyte characters Special characters 54 Teradata Preprocessor2 for Embedded SQL Programmer Guide

55 Chapter 2: Connecting to the Database and Invoking PP2 CHARSET(charset) -cs charset Table 6: Teradata-Defined Character Sets for Network-Attached Environments (continued) Character Set Name Character Set Code Number Description TCHBIG5_1R0 122 Traditional Chinese characters Uppercase and lowercase English characters Multibyte characters Special characters UTF8 63 Intel-based platforms 191 non-intel-based platforms UTF16 62 Intel-based platforms 190 non-intel-based platforms Site-Defined Character Sets for Network-Attached Environments Table 7: Site-Defined Character Sets for Network-Attached Environments Character set Name Character Set Code Number Language SDKANJIEUC_1U3 91 Japanese SDKANJISJIS_1S3 92 Japanese SDTCHGB2312_2T0 94 Simplified Chinese SDTCHBIG5_3R0 95 Traditional Chinese SDHANGULKSC5601_4R4 93 Korean Teradata Preprocessor2 for Embedded SQL Programmer Guide 55

56 Chapter 2: Connecting to the Database and Invoking PP2 CURPREFIX(prefix) -c prefix CURPREFIX(prefix) -c prefix Purpose Specifies the prefix to be used in conjunction with the cursor id to identify the cursor to be used by the cursor manipulation statements. CLOSE DECLARE FETCH OPEN POSITION Usage Notes You may abbreviate CURPREFIX to CP. CURPREFIX is required for a C program precompilation that contains a cursor type request. CURPREFIX is optional for COBOL and PL/I. In the absence of this option, PP2 does the following: Language C COBOL PL/I Action Issues an error as each cursor request is processed. Uses as a default value the name found in the PROGRAM-ID COBOL statement. Uses as a default value the name found on the first PROC statement. For DB2 compatibility in cursor processing, the CURPREFIX option should specify different prefixes for each compile unit of the executable module. To maintain compatibility with earlier releases of PP2, the CURPREFIX value should be the same for all compile units of an executable module. The prefix must be no longer than eight characters and must not include any of these characters: Apostrophe Quote Space 56 Teradata Preprocessor2 for Embedded SQL Programmer Guide

57 Chapter 2: Connecting to the Database and Invoking PP2 DATABASE(dbname) -db dbname DATABASE(dbname) -db dbname Purpose Specifies a default database for use during preprocessing. Usage Notes Unqualified table, view, or macro references are qualified by this database name. In the absence of this option, references would be qualified by the default database for the userid specified by the USERID option. The DATABASE option does not affect the qualification of such unqualified references at application execution time. These are determined by SQL DATABASE statements (if any), by the default database for the userid specified by a SQL LOGON or CONNECT statements, or by the userid under which the program implicitly connected to the server. If the DATABASE option value contains any Kanji or other multibyte character set characters, then the CHARSET option must be specified before the DATABASE option. Warning: Use the DATABASE PP2 option in a consistent manner. While it does not have to name the same database that will be used at application execution time, all unqualified object references in the application program must, at application execution time, resolve to objects that are compatible with the ones to which they resolve at preprocess time. Teradata Preprocessor2 for Embedded SQL Programmer Guide 57

58 Chapter 2: Connecting to the Database and Invoking PP2 DATE(D E I J U) -d D E I J U DATE(D E I J U) -d D E I J U Purpose Specifies the format used at PP2 runtime when a date field is returned to a character field in the application from the Teradata Database. Usage Notes Format Code D E I J U Description Teradata Database format (mm/dd/yy) EUR format (dd.mm.yyyy) ISO format (yyyy-mm-dd) JIS format (yyyy-mm-dd) USA format (mm/dd/yyyy) DATE(D) is the default; however, because this code returns only the final two dates in the year, always select one of the other codes to ensure that all four digits of the year are returned. Specifying Date Format In obtaining DATE information, PP2 returns the data without changing its form. PP2 does not convert DATE data to the form specified for a column. To convert DATE data to a special form, use a specific SELECT statement. Using the SELECT Statement to Specify Date Format To obtain date information in the form yyyy/mm/dd, construct the SELECT statement as follows: SELECT fieldn (FORMAT yyyy/mm/dd ) (CHAR(10))... ; The date column fieldn in this example is of type DATE, but fieldn is returned as character data via the (CHAR(10)) clause, which causes the DATE option to be ignored. The DATE option applies only to DATE data being returned to character variables. The host variable to receive this field must be of character type, with a length of at least 10. The format specified in the SELECT statement overrides the DATE option only for the statement and for the field or fields which are specified. Use this method to obtain a format other than one available via the DATE option. 58 Teradata Preprocessor2 for Embedded SQL Programmer Guide

59 Chapter 2: Connecting to the Database and Invoking PP2 DYNPREFIX (prefix) -dp prefix DYNPREFIX (prefix) -dp prefix Purpose Specifies a prefix that identifies the dynamic statement used by the following manipulation statements: DECLARE PREPARE DESCRIBE EXECUTE OPEN The prefix is used in conjunction with the dynamic statement id. Usage Notes You may abbreviate DYNPREFIX to DP. The prefix must be no longer than 8 characters and must not include any of the following characters: Apostrophe Quote Space The following rules apply when the same dynamic statements are prepared in different modules: DYNPREFIX... Is required Should specify unique prefixes FOR... C, COBOL and PL/I programs, Each compilation unit of the executable module, Teradata Preprocessor2 for Embedded SQL Programmer Guide 59

60 Chapter 2: Connecting to the Database and Invoking PP2 FLAG(I W E S) -f I W E S FLAG(I W E S) -f I W E S Purpose FLAG specifies the minimum severity diagnostic to be printed. Diagnostics of lower severities are suppressed. Usage Notes FLAG(I) is the default. Diagnostic levels, from lowest to highest severity, are: 1 I Informational 2 W Warning (including SQL Flagger Warning) 3 E Error 4 S Severe 5 Fatal Fatal diagnostics are always reported, regardless of the FLAG setting. FLAG is relevant only if PRINT and/or TERM is also specified. 60 Teradata Preprocessor2 for Embedded SQL Programmer Guide

61 Chapter 2: Connecting to the Database and Invoking PP2 INPUT(file spec) -i filespec INPUT(file spec) -i filespec Purpose Specifies the source file containing embedded SQL statements to be used by PP2 as input. Usage Notes The following table describes the input file defaults. IF you do not specify INPUT when you run PP2 in this environment z/os z/vm UNIX Windows THEN the input file defaults to the file associated with a ddname name of SYSIN a filedef name of SYSIN Stdin Stdin If you provide a file name with no extension in network-attached environments, these default extensions are appended: Language COBOL C PL/I Default Extension.pb.pc.pi Teradata Preprocessor2 for Embedded SQL Programmer Guide 61

62 Chapter 2: Connecting to the Database and Invoking PP2 -ld logdata -ld logdata Purpose The -ld logdata option is a parameter list that the specified logon mechanism uses to complete the logon process. Usage Notes This option is only available for network-attached systems. If the logdata parameter list has embedded spaces, delimit the list with quotes ( ). For example: -lm LDAP ld "authcid=guestldap password=password" 62 Teradata Preprocessor2 for Embedded SQL Programmer Guide

63 Chapter 2: Connecting to the Database and Invoking PP2 LINECOUNT(integer) -lc integer LINECOUNT(integer) -lc integer Purpose Specifies the number of lines to be printed on each page of the PP2 output listing, including heading lines. Usage Notes Abbreviation Default Valid Range LC LINECOUNT(60) , inclusive LINECOUNT is ignored if you also specify the NOPRINT. Teradata Preprocessor2 for Embedded SQL Programmer Guide 63

64 Chapter 2: Connecting to the Database and Invoking PP2 -lm logmech -lm logmech Purpose The-lm logmech option specifies the logon mechanism to be used. Usage Notes This option is only available for network-attached systems. In the next example, LDAP is the specified logon mechanism: -lm LDAP ld authcid=guestldap password=password 64 Teradata Preprocessor2 for Embedded SQL Programmer Guide

65 Chapter 2: Connecting to the Database and Invoking PP2 MARGINS(m,n[,c]) -m m,n[,c] MARGINS(m,n[,c]) -m m,n[,c] Purpose Specifies the margins for the input source code. Usage Notes You may abbreviate MARGINS to MAR. The following table explains the correspondence between codes and columns: This code m n c Specifies this column Statement-begin Statement-end Carriage control (PL/I only) The MARGINS specified MUST agree with the columns expected by the particular language compiler. Use MARGINS(1,n) for COBOL in the network-attached environment to specify to PP2 that the input file is in terminal format. Refer to the next table for the defaults when using C, COBOL, or PL/I. Language Default Notes C MARGINS(1,72) COBOL MARGINS(8,72) Cannot be changed in the IBM mainframe environment. PL/I MARGINS(2,72,1) Teradata Preprocessor2 for Embedded SQL Programmer Guide 65

66 Chapter 2: Connecting to the Database and Invoking PP2 NULLSCAN NONULLSCAN -ns -nns NULLSCAN NONULLSCAN -ns -nns Purpose Specifies that PP2 scan for the null character (x 00') during precompilation. Usage Notes Default NONULLSCAN Mutually Exclusive NULLSCAN and NONULLSCAN Specify NULLSCAN if using null characters in a COBOL or PL/I program. NONULLSCAN causes the precompiler to bypass null character scanning. Caution: Make sure the NULLSCAN option is specified if the application program contains null characters. If your application program has null characters (x 00') and you specify or default to NONULLSCAN, PP2 will fail and various errors are generated. Depending on whether the null storage location is interpreted as an op code (S0C1) or a memory address (S0C4), an abend error can be generated during the preprocess step. For this type of error, there may or may not be any error messages indicating the cause of the abend. 66 Teradata Preprocessor2 for Embedded SQL Programmer Guide

67 Chapter 2: Connecting to the Database and Invoking PP2 OPTIONS NOOPTIONS -lo -nlo OPTIONS NOOPTIONS -lo -nlo Purpose OPTIONS specifies that PP2 is to list all options selected by the application. NOOPTIONS specifies that PP2 not list the options used. Usage Notes Default Abbreviation for OPTIONS Abbreviation for NOOPTIONS Mutually Exclusive OPTIONS OPTN NOOPTN OPTIONS and NOOPTIONS If you specify NOPRINT, NOOPTIONS is forced. Teradata Preprocessor2 for Embedded SQL Programmer Guide 67

68 Chapter 2: Connecting to the Database and Invoking PP2 PRINT[(file spec)] NOPRINT -l [filespec] -nl PRINT[(file spec)] NOPRINT -l [filespec] -nl Purpose PRINT specifies that PP2 output the listing to the associated file spec. NOPRINT specifies that PP2 suppress this listing. Usage Notes Default PRINT Mutually Exclusive PRINT and NOPRINT The following table explains the print file defaults for the different supported development environments: IF you specify PRINT with no file spec when running PP2 in this environment z/os z/vm CMS Network-attached THEN the print file defaults to the file associated with a ddname of SYSPRINT. a filedef name of SYSPRINT. The source input file name. PP2 generates a file extension of.lis. If you specify a file name with no extension when running PP2 in a network-attached environment, the default file extension is.lis. NOPRINT implies NOOPTIONS, NOSOURCE and NOXREF. 68 Teradata Preprocessor2 for Embedded SQL Programmer Guide

69 Chapter 2: Connecting to the Database and Invoking PP2 PUNCH[(file spec)] NOPUNCH -o [filespec] -no PUNCH[(file spec)] NOPUNCH -o [filespec] -no Purpose PUNCH specifies the file that contains the source code generated by PP2. NOPUNCH specifies that PP2 suppress source code generation. Usage Notes Default Abbreviation for PUNCH Abbreviation for NOPUNCH Mutually Exclusive PUNCH PU NOPU PUNCH and NOPUNCH IF you specify PUNCH with no file spec when running PP2 in this environment z/os z/vm CMS Network-attached THEN the output file defaults to the file associated with a ddname of SYSPUNCH. a filedef name of SYSPUNCH. an output file with the source input file name and a file extension appropriate to the source language. If you specify a file name without an extension, PP2 uses the defaults explained in the next table. If you specify a file name with no extension, the default extensions are: Language COBOL Default Extension.cob C.c PL/I.pli Teradata Preprocessor2 for Embedded SQL Programmer Guide 69

70 Chapter 2: Connecting to the Database and Invoking PP2 SOURCE NOSOURCE -ls -nls SOURCE NOSOURCE -ls -nls Purpose SOURCE specifies that source input be included in the PP2 listing. NOSOURCE specifies that source input be suppressed from the PP2 listing. Usage Notes Default Abbreviation for SOURCE Abbreviation for NOSOURCE Mutually Exclusive SOURCE S NOS SOURCE and NOSOURCE If you specify NOPRINT, NOSOURCE is forced. 70 Teradata Preprocessor2 for Embedded SQL Programmer Guide

71 Chapter 2: Connecting to the Database and Invoking PP2 SQLCHECK(FULL NOSYNTAX) -sc FULL NOSYNTAX SQLCHECK(FULL NOSYNTAX) -sc FULL NOSYNTAX Purpose Specifies the level of checking to be performed on embedded SQL statements. Usage Notes This option FULL NOSYNTAX Does this Specifies that syntax, object references and access rights checking are to be performed on embedded SQL statements. This is the default and must be used whenever you specify ENTRY or INTERMEDIATE for SQLFLAGGER. Specifies that no checking is to be performed on embedded SQL statements; and no syntax, object reference or access rights checking is performed. Specifying the NOSYNTAX option to the SQLCHECK parameter disables the logon to the Teradata Database during the precompile phase. It has no effect on runtime. If you specify NOSYNTAX, but then specify a SQLFLAGGER of ENTRY, PP2 generates an error and uses the default SQLFLAGGER value of NONE. Teradata Preprocessor2 for Embedded SQL Programmer Guide 71

72 Chapter 2: Connecting to the Database and Invoking PP2 SQLFLAGGER (NONE ENTRY INTERMEDIATE) -sf (NONE ENTRY INTERMEDIATE) SQLFLAGGER (NONE ENTRY INTERMEDIATE) -sf (NONE ENTRY INTERMEDIATE) Purpose Defines the type of SQL flagging to be performed on the SQL being preprocessed. Usage Notes SQLFLAGGER may be abbreviated SQLFLAG. Options for SQLFLAGGER (or -sf) are: This option NONE ENTRY INTERMEDIATE INTERMEDIATE Provides this level of SQL flagging None. This is the default value. Entry level ANSI compliance. Also specify SQLCHECK(FULL) when you specify SQLFLAG(ENTRY). Intermediate level ANSI-compliance. intermediate level ANSI-compliance. When you specify this option, the default value for TRANSACT becomes ANSI. Also specify SQLCHECK(FULL) when you specify SQLFLAG(INTERMEDIATE). When the SQL flagger is enabled, only static embedded SQL statements are flagged during precompilation and only dynamic embedded SQL statements are flagged during program execution (runtime). 72 Teradata Preprocessor2 for Embedded SQL Programmer Guide

73 Chapter 2: Connecting to the Database and Invoking PP2 TDPID(tdpid network group name) -t tdpid network group name TDPID(tdpid network group name) -t tdpid network group name Purpose Specifies the Teradata Database identifier used for PP2 connection. Usage Notes TDPID may be abbreviated TDP. If used, the tdpid network group name must obey the rules for specifying tdpid network group name in a logon string. Specification of this option does not affect, and is not related to, the connection established during application execution. If you specify SQLCHECK with a value other than NOSYNTAX, a hardware platform for the Teradata Database must be available to PP2. Refer to the next table for information on mainframe and network-attached connections. When PP2 is run in this environment... IBM mainframe network-attached THEN... the tdpid specifies the tdp to be used for connection. the network group name specifies the network group to be used for connection. If the TDPID option is not specified, THEN... the default tdp specified in the HSHSPB control block is used. See Teradata Call-Level Interface Version 2 Reference for Channel-Attached Systems for details on the HSHSPB control block. the default network group as specified either in the usersupplied clispb.dat file or the CLI2SPB control block is used. Teradata Preprocessor2 for Embedded SQL Programmer Guide 73

74 Chapter 2: Connecting to the Database and Invoking PP2 TERM[(file spec)] NOTERM -e [filespec] -ne TERM[(file spec)] NOTERM -e [filespec] -ne Purpose TERM specifies that PP2 diagnostics be directed to the associated file spec. NOTERM specifies that error output is suppressed. Usage Notes Default NOTERM Mutually Exclusive TERM and NOTERM For PP2 in the IBM mainframe environment, the error file defaults to the file associated with a ddname or filedef name of SYSTERM. If you specify TERM with no file spec when running PP2 in a network-attached environment, the error file defaults to the file associated with STDERR. If you specify a file name with no extension when running PP2 in a network-attached environment, the default file extension is.err. 74 Teradata Preprocessor2 for Embedded SQL Programmer Guide

75 Chapter 2: Connecting to the Database and Invoking PP2 TRANSACT(ANSI BTET COMMIT 2PC) -tr ANSI BTET COMMIT TRANSACT(ANSI BTET COMMIT 2PC) -tr ANSI BTET COMMIT Purpose TRANSACT specifies the transaction protocol that the application program (compile unit) is to use. Usage Notes TRANSACT(COMMIT) is the default. The following table explains the various transaction modes. In this mode ANSI COMMIT This behavior occurs ANSI transaction semantics are enabled. Selecting this option causes C language strings to be padded with blanks (rather than with nulls) by default. For all languages, truncation of any nonblank and nonzero character produces a warning SQLCODE and SQLSTATE. When you specify this option, the following modes are disabled: BTET COMMIT 2PC Execution of a Teradata SQL request when no transaction (unit of work) is active causes a transaction to be initiated. This is the default. The transaction that is initiated is not terminated until the application terminates or executes one of these statements: ABORT COMMIT LOGOFF ROLLBACK If the transaction is active and the application terminates without an explicit COMMIT or LOGOFF statement while executing in COMMIT mode, the Teradata Database rolls back all uncommitted work. This is a distinct difference between DB2 and the Teradata Database. When you specify this option, the following modes are disabled: ANSI BTET 2PC Teradata Preprocessor2 for Embedded SQL Programmer Guide 75

76 Chapter 2: Connecting to the Database and Invoking PP2 TRANSACT(ANSI BTET COMMIT 2PC) -tr ANSI BTET COMMIT In this mode BTET 2PC This behavior occurs Execution of a Teradata SQL request when no transaction is active causes that request to execute as an implicit transaction, even if the request consists of a single Teradata SQL statement. When you specify this option, the following modes are disabled: ANSI COMMIT 2PC Transactions spanning more than one request must be initiated and terminated using the BEGIN TRANSACTION and END TRANSACTION statements. This is a distinct difference between DB2 and the Teradata Database. The program uses the two phase commit protocol. In 2PC mode, an external resource manager (CICS, IMS, or one written by the user) controls transaction initiation and termination. When you specify this option, the following modes are disabled: ANSI BTET COMMIT Only available for channel-attached clients. An ABORT, BT, CHECKPOINT, COMMIT, DATABASE, ET, ROLLBACK or DDL statement causes an error if 2PC mode is specified. The ABORT, CHECKPOINT, DATABASE, ROLLBACK and DDL statements are valid with either the BTET or COMMIT transaction protocol but are disallowed with the 2PC protocol. This is a distinct difference between DB2 and the Teradata Database. TRANSACT(2PC) is valid only for channel-attached applications. PP2 issues a diagnostic if a BEGIN TRANSACTION or END TRANSACTION statement is found in a program precompiled with the TRANSACT(ANSI), TRANSACT(COMMIT) or TRANSACT(2PC) option; or if a COMMIT statement is found in a program precompiled with the TRANSACT(BTET) or TRANSACT(2PC) option. The transaction protocol for the compile unit where the session is established remains in effect until the session is terminated, regardless of additional compile units with different modes that may be invoked during the session. 76 Teradata Preprocessor2 for Embedded SQL Programmer Guide

77 Chapter 2: Connecting to the Database and Invoking PP2 USERID(userid[,password[,accountid]]) -u userid[,password[,accountid]] USERID(userid[,password[,accountid]]) -u userid[,password[,accountid]] Purpose Specifies the userid, password, and account id on the associated server. See the description of the TDPID(tdpid network group name) -t tdpid network group name on page 73. Usage Notes You may abbreviate USERID to USER. If supplied, the userid, password and accountid supplied must obey the usual rules for a logon string. Specification of this option does not affect, nor is related to the connection established during application execution. If you specify SQLCHECK with a value other than NOSYNTAX, a hardware platform for the Teradata Database must be available to PP2. If the USERID option value contains any Kanji or other multibyte character set characters, then the CHARSET option must be specified before the USERID option. If you do not specify the USERID option or one of the required elements is absent (userid and/or password) when running PP2 in the IBM mainframe environment, PP2 attempts an implicit connection to the Teradata Database if possible. See Teradata Call-Level Interface Version 2 Reference for Channel-Attached Systems for details on implicit connection. Always supply the userid and password when running PP2 in a network-attached environment. Network-attached environments do not support implicit logon. Single Sign On (Windows Platforms Only) If SQL syntax checking is requested, an SSO sign-on will be triggered either by: Omission of the USERID (-u ) PP2 option, or Specification of the userid option with only the accounting data supplied. For more information, see Creating A User for Single Sign-On and LOGON Statement in SQL Reference: Data Definition Statements. Teradata Preprocessor2 for Embedded SQL Programmer Guide 77

78 Chapter 2: Connecting to the Database and Invoking PP2 VERSION(COBOL COBOLII COBOL3) -v MF1 MF2 LPI VERSION(COBOL COBOLII COBOL3) -v MF1 MF2 LPI Purpose Specifies the input and target COBOL compiler code. Usage Notes The default value for VERSION is COBOL. This option is valid only with the COBOL precompiler PPBMAIN. PPBMAIN accepts all of the following as valid VERSION COBOL compilers. It flags all other values as errors. Compiler Name COBOL COBOLII COBOL3 MF1 MF2 LPI Description COBOL at the COBOL 74 level, as exemplified by the IBM dialects OS/VS COBOL and OS Full ANSI COBOL Version 3 and 4. You may abbreviate COBOL as COB. IBM dialect VS COBOL II. VS COBOL II contains significant language extensions over OS/VS COBOL and generally supports COBOL at the COBOL 85 level. PP2 output listing will show COBOLII. You may abbreviate COBOLII as COBII. IBM COBOL for z/os and z/vm. PP2 output listing will show COBOL for z/os and z/vm. You may abbreviate COBOL3 as COB3. Micro Focus COBOL 85 compiler in byte storage mode (compiler option NOIBMCOMP). Micro Focus COBOL 85 compiler in word storage mode (compiler option IBMCOMP). LPI COBOL 85 compiler. 78 Teradata Preprocessor2 for Embedded SQL Programmer Guide

79 Chapter 2: Connecting to the Database and Invoking PP2 XREF NOXREF -lx -nlx XREF NOXREF -lx -nlx Purpose Specifies that PP2 include a cross reference of symbols used in embedded SQL statements in the PP2 listing. Usage Notes Default Abbreviation for XREF Abbreviation for NOXREF Mutually Exclusive XREF X NOX XREF and NOXREF NOXREF specifies that PP2 suppress a cross reference of symbols used in embedded SQL statements from the listing. Teradata Preprocessor2 for Embedded SQL Programmer Guide 79

80 Chapter 2: Connecting to the Database and Invoking PP2 XREF NOXREF -lx -nlx 80 Teradata Preprocessor2 for Embedded SQL Programmer Guide

81 CHAPTER 3 Writing Embedded SQL Applications in C This chapter discusses the C-specific language-dependent functions and features of PP2. Certain non-language specific details are included for reference. C Language Support PP2 supports C in: IBM mainframe environment z/os z/vm CMS Network-attached environment UNIX Windows The C statements generated by PP2, when run in one of the above environments, are acceptable to the compilers for those environments. Execute the C precompiler by invoking module PPCMAIN. See Chapter 2: Connecting to the Database and Invoking PP2, for details. For linkage details, see Application Linking for Visual C++ on Windows on page 211. SQLCA is documented in SQL Communications Area (SQLCA) in SQL Reference: Stored Procedures and Embedded SQL. Every C program that requests Teradata services via embedded SQL statements requires a communications area. Program Status Information Each time a SQL statement is executed, it returns a code to communicate whether or not the statement executed successfully. Therefore, define an area to receive these codes. When you precompile your applications in Teradata mode (by setting the TRANSACT option to BTET, COMMIT or 2PC), define a communications area by using the INCLUDE SQLCA statement. When you precompile your applications in ANSI mode (by defining TRANSACT as ANSI), use variables named SQLCODE and SQLSTATE to receive feedback information. Teradata Preprocessor2 for Embedded SQL Programmer Guide 81

82 Chapter 3: Writing Embedded SQL Applications in C C Language Support Do not mix program status communication areas between Teradata and ANSI compatible modes. Teradata Mode Communications Area When writing C programs for Teradata mode, define a SQL communications area (SQLCA). PP2 generates statements that require the name sqlca. See SQL Reference: Stored Procedures and Embedded SQL, for details of the SQLCA fields. Obtain the necessary SQLCA structure in one of these ways: Code the SQLCA directly into the program. The structure must be named sqlca and must be unique. Incorporate an EXEC SQL INCLUDE SQLCA; the statement causes PP2 to generate the structure. You must determine the appropriate storage class for the SQLCA structure when you code it directly into the application. The SQLCA structure obtained by the INCLUDE SQLCA statement is defined as an auto storage class variable. This classification permits use of a single SQLCA structure by all functions within a given compilation unit. Always use a single, global SQLCA for each compilation unit because multiple SQLCA structures may cause communication problems. The precompiler generates code using references to SQLCODE and SQLWARN0. This usage requires that those fields be accessible by all of the SQL statements within the compilation unit. The code to generate an SQLCA structure for a C application is: #ifndef SQLCODE struct sqlca { unsigned char sqlcaid[8]; int sqlcabc; int sqlcode; struct { short StrLen; unsigned char Str[70]; } SqlErrm; unsigned char sqlerrp[8]; int sqlerrd[6]; unsigned char sqlwarn[11]; unsigned char sqlext[5]; }; #define SQLCODE sqlca.sqlcode #define SQLWARN0 sqlca.sqlwarn[0] #define SQLWARN1 sqlca.sqlwarn[1] #define SQLWARN2 sqlca.sqlwarn[2] #define SQLWARN3 sqlca.sqlwarn[3] #define SQLWARN4 sqlca.sqlwarn[4] #define SQLWARN5 sqlca.sqlwarn[5] #define SQLWARN6 sqlca.sqlwarn[6] #define SQLWARN7 sqlca.sqlwarn[7] 82 Teradata Preprocessor2 for Embedded SQL Programmer Guide

83 Chapter 3: Writing Embedded SQL Applications in C C Language Support #define SQLWARN8 sqlca.sqlwarn[8] #define SQLWARN9 sqlca.sqlwarn[9] #define SQLWARNA sqlca.sqlwarn[10] #define SQLCA sqlca #define SqlCABC sqlcabc #define SqlCode sqlcode #define sqlerrml SqlErrm.StrLen #define sqlerrmc SqlErrm.Str #define SqlErrp sqlerrp #define SqlErrd sqlerrd #define SqlWarn0 SQLWARN0 #define SqlWarn1 SQLWARN1 #define SqlWarn2 SQLWARN2 #define SqlWarn3 SQLWARN3 #define SqlWarn4 SQLWARN4 #define SqlWarn5 SQLWARN5 #define SqlWarn6 SQLWARN6 #define SqlWarn7 SQLWARN7 #define SqlWarn8 SQLWARN8 #define SqlWarn9 SQLWARN9 #define SqlWarnA SQLWARNA #define SqlExt sqlext #endif When coding the SQLCA for a program, use the #define for SQLCODE, as the precompiler generates code for the WHENEVER statement using an uppercase SQLCODE reference. Likewise, use the #define for SQLWARN0. Specify any other #defines as necessary. ANSI-Compatible Mode Communications Variables When writing C programs for ANSI mode, you must define a SQLCODE variable and may also define a SQLSTATE variable. If you define both variables, each contains valid error codes. Do not use the INCLUDE SQLCA construct when writing applications for ANSI mode. Instead, replace that construct with either a SQLSTATE or a SQLCODE variable. Declare SQLCODE as a 32-bit signed integer. Declare SQLSTATE as a fixed length 6 character array to hold the 5 character SQLSTATE code plus the null terminator. Example - Declare Variables for a C Application EXEC SQL BEGIN DECLARE SECTION; int SQLCODE; char SQLSTATE[6]; EXEC SQL END DECLARE SECTION; The SQLSTATE and SQLCODE variables are documented in Result Code Variables in SQL Reference: Stored Procedures and Embedded SQL. Teradata Preprocessor2 for Embedded SQL Programmer Guide 83

84 Chapter 3: Writing Embedded SQL Applications in C BIGINT Support BIGINT Support Beginning with PP2 9.2 and Teradata Database V2R6.2, there is increased byte support for integer operations. The limit has increased from 4 bytes (32 bits) to 8 bytes (64 bits). You can specify a 64 bit integer wherever integers are defined. A TYPEDEF BIGINT statement is also output for those C systems that do not have a native datatype of BIGTYPE. For example: typedef BIGINT long long; In this example, the employee number field is specified as a larger binary integer: struct employee { BIGINT double } empnum; salary; C Coding Considerations You may embed SQL statements into an application program wherever a C executable statement can be located. The format of an embedded SQL statement in a C program is: EXEC SQL embedded-sql-statement; Embedded SQL Statement Format Array Support Each of the SQL statements embedded into a C application must begin with the SQL prefix EXEC SQL, which identifies the statement as an embedded SQL statement. The complete SQL prefix must appear on one line. The prefix is case insensitive, but no character other than blank may appear between EXEC and SQL. The remainder of the statement may appear on the same line or on the next and subsequent lines. Subject to charset restrictions, SQL statements are case insensitive, except for host variable references. When dynamic SQL statement text is stored in a varchar host variable, the statement text cannot be longer than 64k. Each embedded SQL statement must end with a semicolon. The array insert feature for network and mainframe environments improves application performance by allowing iterative requests to be grouped together into a single step, resulting in a decrease of the step-processing overhead per request. Only single INSERT statements and references to arrays of variables are supported. References to arrays of structures are not supported. 84 Teradata Preprocessor2 for Embedded SQL Programmer Guide

85 Chapter 3: Writing Embedded SQL Applications in C C Coding Considerations To accommodate this feature, the EXEC SQL statement is modified to: EXEC SQL FOR (<countval) <sql statement string>; where: FOR indicates that this is an array statement <countval> is a user defined integer variable or literal integer constant that must be less than or equal to the smallest defined dimension in the list of arrays Note: Ensure that <countval> does not exceed the smallest defined dimension in the list of arrays. An error is generated if this condition is violated and countval is specified as a literal. At precompile time, no check is made when countval is specified as a variable. <sql statement string> is a character string containing a legal SQL statement with references to host variables Literal integer constants that are embedded in the SQL string are not iterated; they are propagated in every inserted row. The same host variable can be specified for two or more fields. Any given iteration will obtain the same value. Example char empname[50][20]; integer empnum[50]; float empsal[50]; integer cnewemployees = 50; short e_nameind = 0, e_numind =0, e_salind =-1; PREPARE exinsert01 FROM insert into employee values (?,?,?); EXEC SQL FOR cnewemployees EXECUTE exinsert01 USING :empname, :empnum, :empsal; Comments Place C comments within Teradata SQL statements wherever a blank is permitted, except between EXEC and SQL. Do not nest comments. Continuation for SQL Statements Line continuation rules for a SQL statement within EXEC SQL blocks are the same as C continuation rules, with the following exceptions: The EXEC SQL prefix, including the FOR clause, must be specified on one line. Strings within a SQL statement in Teradata mode cannot be continued with the backslash character. All characters, including blanks, from the beginning string delimiter to the ending string delimiter, form the string. If the ending string delimiter is not found on the current line, all characters up to the right margin are considered part of the string. Teradata Preprocessor2 for Embedded SQL Programmer Guide 85

86 Chapter 3: Writing Embedded SQL Applications in C C Coding Considerations Dynamic SQL On the next line, all characters beginning in the left margin and continuing to the ending string delimiter are part of the string. If no blanks are required, specify the string all the way to the right margin (column 72 or 80, depending on the MARGINS PP2 option), and immediately resume the left margin at (column 1) of the next line. Strings in ANSI compatible mode can be continued with the backslash character. The backslash is not included as part of the string. C supports dynamic SQL, and the application must contain the necessary SQL Descriptor Area (SQLDA) structures. The SQLSTATE and SQLCODE variables are documented in Result Code Variables in SQL Reference: Stored Procedures and Embedded SQL. Include an SQLDA structure in one of the following ways: Embed an EXEC SQL INCLUDE SQLDA; the statement in the application causes PP2 to generate the structure. Code the SQLDA directly into the program. You may use any name. The generated SQLDA structure for a C program is: #ifndef SQLDASIZE { struct sqlda { unsigned char sqldaid[8]; int sqldabc; short sqln; short sqld; struct sqlvar { short sqltype; unsigned short sqllen; unsigned char *sqldata; short *sqlind; struct sqlname { short length; unsigned char data[30]; } sqlname; } sqlvar[1]; }; #define SQLDASIZE(n)\ (sizeof(struct sqlda) + ((n)-1)*sizeof(struct sqlvar) #endif The second example dynamic program at the end of this chapter shows how to use the INCLUDE SQLDA statement. Including Code Use the SQL INCLUDE statement to incorporate those host variable definitions or SQL statements that come from an external copy file. 86 Teradata Preprocessor2 for Embedded SQL Programmer Guide

87 Chapter 3: Writing Embedded SQL Applications in C C Coding Considerations The precompiler does not recognize the normal C #include statement, so use the SQL INCLUDE statement to include header files containing host variable definitions anywhere you would normally use a C #include statement. Margins You can code SQL statement between columns 1 and 256, depending on the MARGINS option. All precompiler-generated code is contained within columns 1 to the column specified for the right margin in the MARGINS option. Sequence Numbers The precompiler does not generate sequence numbers in source statements. SQL Strings Define the variable name used for a SQL string as either a character or varying character type. See Host Variable Declaration on page 101 for details on declaring character fields. PP2 expects a terminating null character (a \0 ) if a character string variable is used as a SQL string. The code is generated based on the presence of the \0 in the string. The \0 is not used, however, when a varying character variable is used as a SQL string. Use of a character string variable as a SQL string is a PP2 extension over DB2 rules, although any DB2 conforming SQL string is valid. Statement Labels String Delimiters Specify labels for executable SQL statements following the rules of normal C statements. The APOST/QUOTE and APOSTSQL/QUOTESQL options control C string recognition and generation. The only values permitted for C are QUOTE and APOSTSQL. PP2 generates code appropriate for proper C string usage. QUOTE indicates that native C strings are enclosed by quotation marks ( ). APOSTSQL indicates that apostrophes ( ) delimit the strings embedded within a SQL statement and quotation marks (") are used for the escape character. APOSTSQL affects SQL string delimiters and escape characters. See Chapter 2: Connecting to the Database and Invoking PP2 for details on the use of these options. As an example, with QUOTE/APOSTSQL, the application is the following: EXEC SQL DECLARE cursor CURSOR FOR Teradata Preprocessor2 for Embedded SQL Programmer Guide 87

88 Chapter 3: Writing Embedded SQL Applications in C C Coding Considerations SELECT * FROM table WHERE COL1 = ABCD ; UPDATE table one SET COL2 = ABCD ; Delimited Identifiers and Character String Literals Teradata SQL for Teradata Database and later extends ANSI-compliant Unicode delimited identifiers and character string literals. This enables the Data Dictionary to function the same, whether or not Japanese character set support is enabled or not. Additionally, object names with multi-byte character sets can be shared between sessions that have non-japanese character sets. The Unicode delimited identifier is U&" ". The Unicode character string literal is U&' '. These new identifiers and literals are produced where ' 'XN and ' 'XC notation is used. For example, prior to Teradata Database , the syntax to represent a Kanji string was: ELECT * FROM ' 'XN; /* This hexadecimal string represents the Kanji1 string using the KANJIEUC_0U character set*/ For Teradata Database and later, the syntax is: SELECT * FROM U&"\FF34\FF21\FF22\FF11"; /* for post V2R Unicode Data Dictionary, the internal hex is based on UNICODE hex for object name */ In the above example, backslash (\) is the escape character. The default escape character depends on the session charset, but will be backslash (\) or yen sign for all supported character sets. The above SQL can also be written as: SELECT * FROM U&"$FF34$FF21$FF22$FF11" UESCAPE('$'); where $ is the escape character. User Defined Functions You can use the User Defined Function (UDF) in the embedded SQL statements, but not CREATE or REPLACE FUNCTION in PP2 applications. For further information, see SQL Reference: Data Definition Statements. Multi-Session Programming Considerations The specific SQL statements used for multiprogramming are documented in Multisession Asynchronous Programming in SQL Reference: Stored Procedures and Embedded SQL. 88 Teradata Preprocessor2 for Embedded SQL Programmer Guide

89 Chapter 3: Writing Embedded SQL Applications in C Host Variables Special Considerations Run PP2 either before or after the C preprocessor. PP2 does not support C preprocessor directives. Host Variables SQL statements may use C variables both for sending input values to, and for receiving output values from, the Teradata Database. Variables used in this manner are called host variables. Host variables allow an application to use the same statement in an iterative fashion, obtaining results based on the value of the variable when the statement is executed. PP2 supports structured host variables to a depth of two, following the same rules as SQL/DS and DB2. Host variables are documented in Embedded SQL in SQL Reference: Stored Procedures and Embedded SQL. Using C Structures as Output Host Variables Use C host structures to receive data from the Teradata Database. This capability is particularly useful if you are receiving multiple columns. A host structure is approved to receive data if and only if all fields of that structure are valid definitions to PP2. This does not preclude the use of the individual fields of the structure, as long as the field follows proper PP2 definition rules. Using C Structures as Input Host Variables Host structures insert data into a Teradata Database. This feature is particularly useful for an INSERT statement with a VALUES clause that inserts multiple fields into a table using host variables. A host structure as an entity is valid for input only if all fields of the structure are validly defined to PP2. Because all of the fields of the structure are passed to the Teradata Database, the application must ensure that the structure elements match the number and type of elements specified in the SQL statement. Do not use a structure reference as an input entity in a WHERE clause or any place where a single field is expected. Use individual fields of a structure for input as long as the fields are defined adhering to PP2 rules. Qualified references to database objects in embedded SQL statements are expressed with a dot separating the levels of qualification. See Host Variable Declaration on page 101. Teradata Preprocessor2 for Embedded SQL Programmer Guide 89

90 Chapter 3: Writing Embedded SQL Applications in C Host Variables Example Overview The structure level may go deeper than the two levels shown, but the items, if individually referenced, must be uniquely identifiable with a qualification depth of no more than two. Examples of referencing a structure for output are shown below. Assume you have the following table defined on the server: EXEC SQL CREATE TABLE TABLE1, NO FALLBACK, NO BEFORE JOURNAL, NO AFTER JOURNAL (field1 CHAR(20), field2 INTEGER, field3 CHAR(6), field4 FLOAT) UNIQUE PRIMARY INDEX (FIELD1) ; A typical host structure definition for this table takes the following form: struct { char field1[21]; long field2; char field3[7]; float field4; } structure1; When you declare character string variables, the length of the array must be one character longer than the length of the corresponding table column definition. The extra space is required for the terminating null. Example: Single Row SELECT EXEC SQL SELECT * INTO :structure1 FROM table1 WHERE field3 = ABCDEF ; Example: Multiple Row SELECT EXEC SQL DECLARE c1 CURSOR FOR SELECT * FROM table1; EXEC SQL OPEN c1; EXEC SQL FETCH c1 INTO :structure1; (loop for FETCH) EXEC SQL CLOSE c1; 90 Teradata Preprocessor2 for Embedded SQL Programmer Guide

91 Chapter 3: Writing Embedded SQL Applications in C Host Variables Example: Single Row SELECT That Returns Only Some Columns EXEC SQL SELECT field1, field3 INTO :field1, :field3 FROM table1 WHERE field2 = 99; Example: Single Row SELECT Using Qualified Variable References EXEC SQL SELECT field1, field3 INTO :structure1.field1, :structure1.field3 FROM table1 WHERE field2 = 99; Example: Single Row INSERT Using a Structure for Field Values EXEC SQL INSERT INTO table1 VALUES (:structure1); The fields in the table receive the following assignments: table1.field1 <- field1 of structure1 table1.field2 <- field2 of structure1 table1.field3 <- field3 of structure1 table1.field4 <- field4 of structure1 Caution: PP2 uses the elementary items as sending/receiving variables whenever you use a host structure name. Teradata Preprocessor2 for Embedded SQL Programmer Guide 91

92 Chapter 3: Writing Embedded SQL Applications in C Requirements for Host Variables If the structure had been defined as: struct { char field1[21]; long field2; struct { char field3a[3]; char field3b[3]; char field3c[3]; } field3; float field4; } structure1; and the single row SELECT statement as: EXEC SQL SELECT * INTO :structure1 FROM table1 WHERE field3 = ABCDEF ; then PP2 would generate code such that C would attempt the following assignments: table1.field1 -> field1 of structure1 table1.field2 -> field2 of structure1 table1.field3 -> field3a of structure1 table1.field4 -> field3b of structure1 Data moved into field 3a would be truncated with a \0 terminating null character, while moving data into field3b would cause an error. Requirements for Host Variables This section lists the requirements and limits for using host variables in a C program. C Language and Host Variables SQL and Host Variables You may use any valid C host variable in a SQL statement. This does not mean that all variables may be used, however. Host variables must meet certain requirements before PP2 can accept them as usable in SQL statements. See Host Variable Declaration on page 101. You may use any valid C variable name as a host variable name, including names with embedded underscores ( _ ). You must declare host variables to be used in SQL statements (that is, enclose them between BEGIN DECLARE/END DECLARE statements). You may use multiple declare sections. Variables declared elsewhere are not considered valid for SQL usage by PP2. 92 Teradata Preprocessor2 for Embedded SQL Programmer Guide

93 Chapter 3: Writing Embedded SQL Applications in C Requirements for Host Variables Indicator Variables BEGIN DECLARE and END DECLARE are documented in Embedded SQL in SQL Reference: Stored Procedures and Embedded SQL. Variable names used in SQL requests are case sensitive; for example, VAR1 is not equivalent to var1. Dynamic SQL, when executed in Teradata mode, returns a designation of character (452 or 453) to the SQLDA structure when a PREPARE...INTO or DESCRIBE is performed and no null terminator is supplied when the data is returned to the field. Host variables that are not SQL strings may represent data values only. They may not be used to represent database, table, view, macro or column names. Use the form short [int] var1[x] only as an indicator array with a structure reference. PP2 Issues PP2 expects a terminating null character ( \0 ) on input and terminates the string with a \0 on output when used with a static request. The application must change the type designation to receive a null terminated field. You may declare a host variable as a variable character field by using the PP2 directive VARCHAR. This designation is replaced by a structure when the C code is generated. Any terminating null is treated as part of the string, both when used as input and as output. For details, see Varying Character Data on page 96. Host Variable Declaration Use the following C type specifiers and declarations to define a host variable declaration: auto char double extern float int long short static struct (excluding tag type definitions) unsigned char The host variable defined as a long data type will be 4 bytes when compiled with the 32-bit compiler option and 8 bytes when compiled with the 64-bit compiler options on the Solaris, HP-UX, AIX or 64-bit Windows platforms. When generating SQLDA for the static SQL statement, the PP2 precompiler assigns: SQLTYPE to the INTEGER data type SQLLEN to sizeof(long) Teradata Preprocessor2 for Embedded SQL Programmer Guide 93

94 Chapter 3: Writing Embedded SQL Applications in C Host Variable Values The following C type specifiers and declarations cannot be used to declare a host variable: #define enum pointer designation (char *var1) register structure definition via tags typedef union unsigned integer types void C array dimensions must be specified by a numeric literal. Defined constants and/or numeric expressions are not allowed within a C array declaration. Host Variable Values The following sections detail variable assignments in these environments: Server to host Host to server Server to Host Assignment Conversion Rules Host variables are assigned during execution of a data retrieving statement (such as SELECT) or by a FETCH for cursors. The INTO clause identifies the host variables to receive the data. PP2 converts data from the server to the appropriate client format, provided the types are compatible. Numeric values may not be returned to character or byte strings. The only exception to this is DATE. DATE fields may be returned to character fields (not byte) if the length of the field can hold the conversion type requested by the DATE option. See DATE(D E I J U) -d D E I J U on page 58. BYTE and VARBYTE strings may be returned to any valid host variable type. The byte string is moved one byte at a time for the length of the receiving variable. No data conversion is performed and the application is responsible for handling the returned data. CHAR and VARCHAR strings are returned only to CHAR, VARCHAR or character string type variables. A CHAR host variable is defined as a one character char type (that is, char var1). VARCHAR is defined as a structure having a two byte length field and a character array data field. 94 Teradata Preprocessor2 for Embedded SQL Programmer Guide

95 Chapter 3: Writing Embedded SQL Applications in C Server to Host Assignment Byte String Assignment A character string is defined as an array of two or more elements of char type (that is, char var1[2]), which is terminated by a terminating null character ('\0'). DATE values may be returned to a numeric type (DECIMAL, NUMERIC, INTEGER, FLOAT, REAL, DOUBLE PRECISION), as long as the value is representable in the receiving type. DATE in its natural format (such as a DESCRIBE for a dynamic request) is equivalent to INTEGER. DATE also may be returned to a CHAR, VARCHAR or character string field, provided the length of the receiving field can hold the format requested. The character variable must be at least length 8 to receive the date in any of the allowable formats. The character string type variable must be at least length 9 (date plus the terminating null character of '\0') to receive the data. DECIMAL values may be returned to any numeric type (DECIMAL, NUMERIC, INTEGER, SMALLINT, BYTEINT, FLOAT, REAL, DOUBLE PRECISION), as long as the value is representable in the receiving type. C does not provide a natural DECIMAL data type. Memory may be allocated, however, to hold the value and the SQLDA set to reflect a DECIMAL type host variable. The application then is responsible for manipulation of the data. BYTEINT, SMALLINT and INTEGER values may be returned to any numeric type (DECIMAL, NUMERIC, INTEGER, SMALLINT, BYTEINT, FLOAT, REAL, DOUBLE PRECISION), as long as the value is representable in the receiving type. FLOAT values may be returned to any numeric type (DECIMAL, NUMERIC, INTEGER, SMALLINT, BYTEINT, FLOAT, REAL, DOUBLE PRECISION), as long as the value is representable in the receiving type. The Teradata SQL FLOAT, REAL and DOUBLE PRECISION types are equivalent to a DOUBLE PRECISION FLOAT. PP2 recognizes both SINGLE and DOUBLE PRECISION FLOAT host variable types. Fractional portions of the value may be lost in conversion to a type other than DOUBLE PRECISION FLOAT. Note: No host GRAPHIC-type variable declaration for the C language is recognized by PP2. Byte data is assigned to a host variable byte by byte. PP2 performs no conversion, leaving the application responsible for processing the value. Teradata Preprocessor2 for Embedded SQL Programmer Guide 95

96 Chapter 3: Writing Embedded SQL Applications in C Server to Host Assignment If the value is Shorter than the receiving field THEN the data is filled with nulls. Longer than the receiving field 1 truncated. 2 SQLWARN1 in the SQLCA area is set to W. 3 the indicator variable, if present, is set to the length of the returned data. The same length moved with no exception conditions. Character Assignment The C preprocessor recognizes three types of character fields into which non-numeric data may be returned: Single character Varying Character Character String Each type is discussed in the sections that follow: Single Character Data A character host variable is defined as a single character field with no terminating null character ('\0'). The C definition for such a field is the following: char var1; Brackets are not used when defining a single character field; their use invalidates the variable for use in a SQL statement. When data is returned to a single character field, one byte at most is returned (truncation occurs if the Teradata Database field is larger, warning flags are set and (if present) the indicator variable is set). No \0 is present, which is equivalent to a data type of 452 (453 if nullable), with a length of 1. DATE values may not be returned to this type of host variable because the field is not long enough. Varying Character Data The C language does not have a natural varying character data type. PP2 allows you to define a varying character field, however, using the special identifier, VARCHAR. 96 Teradata Preprocessor2 for Embedded SQL Programmer Guide

97 Chapter 3: Writing Embedded SQL Applications in C Server to Host Assignment PP2 converts this designation to a structure composed of two fields. VARCHAR var1[n]; becomes: struct { SQLInt16 len; char arr[n]; }var1; SQLInt16 is a defined constant equivalent to short and n is an integer value > 0 (n reflects the maximum length of the data to be sent or received: Do not add +1 for a terminating null). This type of field may contain characters or binary data, including \0 terminating null characters. Varying character fields do not contain a terminating null character ( \0 ). The len field contains the length of the data returned to the arr portion. Let M be the length of the returned data. IF THEN AND M = n M < n the data is moved to arr with no exception conditions M characters of data are moved to arr len is set to M M > n n characters are moved to arr len is set to n SQLWARN1 in SQLCA is set to W the indicator variable (if present) is set to M Varying character data has a type of 448 (449 if nullable), with a maximum length of n. DATE values may be returned to this type of field, provided the length is sufficient to hold the format chosen at precompile time. See DATE(D E I J U) -d D E I J U on page 58. Character String Data A character string host variable is defined as an array of characters with a terminating null character ('\0'). The C definition for such a variable is: char var1[n]; To define a character string variable, n must be a positive integer, value > 1. At most, n-1 bytes of data are returned to the host variable. One position is always reserved for the \0 terminating null character. Let M be the length of the returned data. Teradata Preprocessor2 for Embedded SQL Programmer Guide 97

98 Chapter 3: Writing Embedded SQL Applications in C Server to Host Assignment IF AND the TRANSACT mode is THEN AND M <= n-1 BTET COMMIT M characters are moved to the variable \0 is placed in the M+1 position of the variable 2PC ANSI the array is padded with blanks and \0 is placed in the M+1 position of the variable. M > n-1 any valid choice n-1 characters are moved to the variable position is set to \0 SQLWARN1 is set to W if the indicator variable is present, it is set to M SQLCODE is set to +902 (ANSI mode only) SQLSTATE is set to (ANSI mode only) This variable has a type of 460 (461 if nullable), with a maximum length of n-1. Actual length is determined by the position of the terminating null character ( \0 ). DATE values may be returned to this type of field, providing the format chosen at precompile time fits in n-1 bytes. See DATE(D E I J U) -d D E I J U on page 58. Character String Padding C strings are padded differently in the Teradata compatible and ANSI compatible environments. In this TRANSACT mode ANSI Teradata BTET COMMIT 2PC Strings are padded with this character blanks nulls For example, consider the following comparison in which the EBCDIC string ABCDE is fetched into a host variable defined as char[7]. 98 Teradata Preprocessor2 for Embedded SQL Programmer Guide

99 Chapter 3: Writing Embedded SQL Applications in C Server to Host Assignment In this TRANSACT mode ANSI Teradata The host variable contains this data X C1C2C3C4C54000 X C1C2C3C4C50000 BTET COMMIT 2PC The ANSI string is padded with blanks, while the non-ansi string is padded with nulls. The process is similar for ASCII strings. Character Truncation Character truncation is handled identically under all compatibility modes. For example, consider the EBCDIC string ABCDE is fetched into a host variable defined as char[4]. The host variable contains X C1C2C300, which is the three leftmost characters of the original string plus a terminating null. The process is similar for ASCII strings. If TRANSACT is set to ANSI, then truncation of any nonblank and nonzero character produces a warning SQLCODE (+902) and SQLSTATE (01004). Numeric Value Assignment Numeric values are converted as appropriate for the receiving field, provided the value may assume the requested format without losing leading digits. The following types are valid: DECIMAL NUMERIC FLOAT REAL DOUBLE PRECISION BYTEINT SMALLINT INTEGER The SQLCODE field in the SQLCA is set to -304 if the host variable cannot contain the returned data. Date Assignment Date values may be returned into any valid numeric host variable, following the same rules as for numeric assignment except when DATEFORM=ANSIDATE is set. Teradata Preprocessor2 for Embedded SQL Programmer Guide 99

100 Chapter 3: Writing Embedded SQL Applications in C Host to Server Assignment The following types are valid: DECIMAL NUMERIC FLOAT REAL DOUBLE PRECISION INTEGER Date values may also be returned into a character string or varying character variable. The host variable length depends upon the DATE option set or defaulted. See DATE(D E I J U) -d D E I J U on page 58. If a Teradata Database format is requested or defaulted, the receiving variable must be at least 8 bytes long. Surplus bytes are set to blanks. All other formats require at least 10 bytes. Bytes in excess of 10 are set to blanks. The SQLCODE in the SQLCA is set to -304 if the receiving field is too short. For ANSI DATE format, the receiving character variable must be at least 10 bytes long. Bytes in excess of 10 are set to blanks. Host to Server Assignment Assignment Rules Host variables may be used to pass column values to the server via the VALUES clause of the INSERT statement or the SET clause of the UPDATE statement. Except for character string data, PP2 performs no conversion before sending the data to the server, so the application must ensure that the host variable may pass the value to the server for conversion. Rules for assigning the Teradata Database variables are documented in SQL Reference: Stored Procedures and Embedded SQL. When a character string variable is used as input to the Teradata Database, the data is scanned for the first \0, which determines the length of the data. If No \0 is found The receiving Teradata Database field is a SQL CHAR field and the length of the data value is less than the length of the Teradata Database field The length is greater than that of the receiving field Then error code -302 is placed in the SQLCODE the Teradata Database field is blank padded. the data is truncated. 100 Teradata Preprocessor2 for Embedded SQL Programmer Guide

101 Chapter 3: Writing Embedded SQL Applications in C Host Variable Declaration If the receiving Teradata Database field is a SQL VARCHAR and the actual length of the data is greater than the maximum length of the Teradata Database field, the data is truncated; otherwise, the resulting length of the SQL field is the actual length of the data value. The data returned may be greater than the length of the data at input. This condition occurs when the Teradata Database field is a fixed character field (CHAR) and the length of the input data is less than the length of the Teradata Database field, causing blank padding. Trailing blanks are not stripped from the data when it is returned to the application. Host Variable Declaration PP2 does not recognize every possible C variable declaration as valid for use in a SQL statement. For those types that have no direct C declaration, runtime processing allows you to return data to one of the other types. Storage may be dynamically allocated for those data types not directly representable by a C declaration. This is useful when using dynamic SQLDA information returned by the Teradata Database. The following table is a list of the equivalent C definitions for the Teradata Database data types. Table 8: C Definitions for Teradata Database Data Types Data Type Declaration Notes BYTE No direct equivalent 1 VARBYTE No direct equivalent 1 CHAR or CHAR (1) char identifier; CHAR (m) char identifier [m+1]; 2 VARCHAR (m) VARCHAR identifier [m] 3 TIME char identifier 9 TIMESTAMP char identifier 10 DATE long [int] identifier; 4 DECIMAL (m, n) No direct equivalent 5 NUMERIC (m, n) No direct equivalent 5 FLOAT* REAL* DOUBLEPRECISION* FLOAT** REAL** float identifier; float identifier; float identifier; double identifier; double identifier; Teradata Preprocessor2 for Embedded SQL Programmer Guide 101

102 Chapter 3: Writing Embedded SQL Applications in C Host Variable Declaration Table 8: C Definitions for Teradata Database Data Types (continued) Data Type Declaration Notes DOUBLE PRECISION** double identifier; BYTEINT No direct equivalent 6 SMALLINT short [int] identifier; 7 INTEGER long [int] identifier; 8 *single precision **double precision Note: 1) Data may be returned to any valid host variable, although PP2 performs no data conversion. 2) The integer m must be positive, greater than one. 3) The integer m must be positive. PP2 generates a structure with name identifier comprised of a short (2 bytes) len field and a character array field arr of length m. No terminating null is expected or placed into the arr field. 4) The Teradata Database normally returns a DATE type field as integer. It is possible to return the value in character string format, as long as the length of the receiving field is sufficient. The DATEFORM=ANSIDATE format returns the DATE type field as CHAR (10). 5) Data may be returned to any valid numeric format provided the value fits into the field specified. It is possible to allocate sufficient storage dynamically to hold the decimal field. In this case, the application must provide for the data returned. 6) Data may be returned to any valid numeric format provided the value fits into the specified field. It is possible to allocate sufficient storage dynamically to hold the byteint field. In this case, the application must provide for the data returned. 7) PP2 allows specification of int identifier for a smallint on those systems where short and int are equivalent. For a variable and statement it knows about, PP2 issues a warning about the size of the int field on a particular platform. 8) PP2 allows specification of int identifier for an integer on those systems where long and int are equivalent. For a variable and statement it knows about, PP2 issues a warning about the size of the int field on a particular platform. 102 Teradata Preprocessor2 for Embedded SQL Programmer Guide

103 Chapter 3: Writing Embedded SQL Applications in C Indicator Variables Note: The host variable defined as a long data type will be 4 bytes when compiled with the 32-bit compiler option and 8 bytes when compiled with the 64-bit compiler options on the Solaris, HP-UX, AIX or 64-bit Windows platforms. When generating SQLDA for the static SQL statement, the PP2 precompiler assigns: SQLTYPE to the INTEGER data type SQLLEN to sizeof(long) 9) For TIME, the length of the char identifier should be ) For TIMESTAMP, the length of the char identifier should be 35. Indicator Variables Indicator variables may be used with main variables intended for I/O, although certain indicator variables may not be used for input. For more information on indicator variables see SQL Reference: Stored Procedures and Embedded SQL. PP2 uses indicator variables to handle nulls sent to or returned from the Teradata Database, as well as for truncation of a character or byte string when placed into the corresponding main variable. Rules for Indicator Variables An indicator variable containing A negative number (most commonly -1) Zero A positive number Specifies to the application that the associated input main variable is null, or that a null value was successfully returned. application that the associated input main variable is non-null or that a non-null value was successfully returned with no exception conditions applied. application that truncation has occurred when returning a character or byte string to the associated main variable. This value represents the original length of the string before truncation. An indicator variable is defined as a 2 byte integer (smallint). In C, this is declared as: short identifier; A host variable is recognized for use as an indicator only if the short characteristic is coded; int is not equivalent on any platform. Teradata Preprocessor2 for Embedded SQL Programmer Guide 103

104 Chapter 3: Writing Embedded SQL Applications in C Indicator Variables Indicator Variables and Input Use indicator variables: when the application requires the Teradata Database to set a column null, such as when executing an INSERT or UPDATE statement. within a WHERE clause condition with host variables to handle a null. If the indicator variable value is... negative zero or positive then... the value in the associated main variable is ignored and PP2 sends a null to the Teradata Database for the column. the host variable value is sent to the Teradata Database as the column value. For example: EXEC SQL INSERT table1 VALUES (:hostvar1 :indvar1); EXEC SQL UPDATE table1 SET col1 = :hostvar1 :indvar1 WHERE col1 = :hostvar2; Indicator Variables and Output Indicator variables may be associated with the output main variables used in the INTO clause of a data returning statement or cursor FETCH statement. IF the Teradata Database returns a Null for a column and no indicator variable exists Negative value Positive value THEN the SQLCODE in the SQLCA is set to -305 and the value of the receiving main variable remains unchanged. the field was returned to the main variable with no exception conditions. the returned byte or character string was truncated. This value represents the original length of the string before truncation. For example: EXEC SQL SELECT col1 INTO :hostvar1 :indvar1 FROM table1 WHERE col1 = :hostvar2; EXEC SQL FETCH cursor1 INTO :hostvar1 :indvar1; 104 Teradata Preprocessor2 for Embedded SQL Programmer Guide

105 Chapter 3: Writing Embedded SQL Applications in C SQL Error Return ANSI Mode Indicator Variables and Structures To facilitate use of indicator variables with host structures for output, PP2 accepts the definition of an array of small integers. For example: struct { char FIELD1[21]; long FIELD2; char FIELD3[7]; float FIELD4; } STRUCTURE1; short INDVAR[4]; EXEC SQL SELECT * INTO :STRUCTURE1 :INDVAR FROM table1 WHERE col1 = :hostvar2; EXEC SQL FETCH cursor1 INTO :STRUCTURE1 :INDVAR; In both examples, INDVAR[0] is associated with FIELD1, INDVAR[1] with FIELD2 and so forth. The host variable is not required to have an associated indicator variable. The INDVAR array above could have less than four elements. However, PP2 associates host variables and indicator variables one to one in order of occurrence. If there were two elements defined for the indicator variables in these examples, FIELD1 and FIELD2 would have associated indicators, while FIELD3 and FIELD4 would have not. Indicator arrays may be associated only with a structure. Use of an array with individual elements results in a PP2 error. SQL Error Return ANSI Mode SQLCODE Variable Error conditions arising during processing of a SQL request made in ANSI mode are returned to the application via the SQLCODE or SQLSTATE variables. The SQLSTATE and SQLCODE variables are documented in Result Code Variables in SQL Reference: Stored Procedures and Embedded SQL. If the SQLCODE variable is... negative positive then... an error condition has been reported. a warning has occurred. If no exception or error condition is encountered during processing, PP2 sets the SQLCODE variable to zero. Teradata Preprocessor2 for Embedded SQL Programmer Guide 105

106 Chapter 3: Writing Embedded SQL Applications in C SQL Error Return Teradata Mode SQLCODE is defined as a 32-bit signed integer variable: int SQLCODE; Some exception conditions are not reflected in the SQLCODE. Data truncation on assignment of a value to a host variable is returned in SQLCODE(+902). The application should always check the SQLCODE variable upon return from processing an executable statement. Use the WHENEVER statement as one method to accomplish SQLCODE checking. You can define both a SQLCODE and a SQLSTATE variable for the same compilation unit. Both contain valid result codes. For details, see SQL Reference: Stored Procedures and Embedded SQL. SQLSTATE Variable The SQLSTATE variable is an ANSI standard, 5 character string value logically divided into a 2 character class and a 3 character subclass. SQLSTATE is defined as a character variable: char SQLSTATE[6]; Note that SQLSTATE is defined as having six characters. The last character of the variable holds the null character \0 for C string termination. You can define both a SQLSTATE and a SQLCODE variable for the same compilation unit. Both contain valid result codes. For details on the ANSI SQLSTATE variable, see SQL Reference: Stored Procedures and Embedded SQL. Using PPRTEXT to Retrieve Return Codes PP2 provides a mechanism for retrieving the CLIv2, TDP, PP2 runtime or Teradata Database return codes, and the message text associated with the SQLCODE. When SQL Flagger warnings are found, only the first such warning for a particular statement is available through PPRTEXT. The application issues a call to PPRTEXT, passing four parameters as input to the routine. For additional information on PPRTEXT, see Messages. The four parameters are defined in SQL Error Return Teradata Mode on page 106, along with an example of how an application may call this routine. SQL Error Return Teradata Mode Error conditions arising during processing of a SQL request made in Teradata mode are returned to the application via the SQL Communications Area (SQLCA). 106 Teradata Preprocessor2 for Embedded SQL Programmer Guide

107 Chapter 3: Writing Embedded SQL Applications in C SQL Error Return Teradata Mode SQLCODE Field In particular, the SQLCODE field of the SQLCA contains a negative value when an error condition is reported. If no exception or error condition is encountered during processing, PP2 sets the SQLCODE field to zero. Some exception conditions, however, are not reflected in the SQLCODE. For example, data truncation on assignment of a value to a host variable or return of a null value are not reported directly. In these cases, the SQLWARN fields or any indicator variables associated with a host variable are set to indicate these conditions. The application should always check the SQLCODE field upon return from processing an executable statement. Use the WHENEVER statement, as illustrated below, as one method to accomplish SQLCODE checking. For details on the SQLCA fields, see SQL Reference: Stored Procedures and Embedded SQL. Using PPRTEXT to Retrieve Return Codes PP2 provides a mechanism for retrieving the CLIv2, TDP or Teradata Database return codes, and the message text associated with the SQLCODE. When SQL Flagger warnings are found, only the first such warning for a particular statement is available through PPRTEXT. The application issues a call to PPRTEXT, passing four parameters as input to the routine. For additional information on PPRTEXT, see Messages. The four parameters are defined below, along with an example of how an application may call this routine. In order, the four parameters PPRTEXT expects to receive are: 1 SQL_RDTRTCON Precompiler-generated field set by the code generated at precompile time. This data should never be altered by the application; it has a declaration of: char *SQL_RDTRTCON; 2 ERROR_CODE Application declares this field; the name is not important and the name shown is an example. PPRTEXT places the actual error code in this field and no initialization is necessary. Declare this field as: int ERROR_CODE; 3 ERROR_MSG application declares this field; the name is not important and the name shown is just an example. PPRTEXT places the message text and the length of the text returned in this field and no initialization by the application is necessary. Teradata Preprocessor2 for Embedded SQL Programmer Guide 107

108 Chapter 3: Writing Embedded SQL Applications in C Exception Conditions: WHENEVER Declare this field as follows: VARCHAR ERROR_MSG[255]; or struct { short len; char arr[255]; } ERROR_MSG; Note: The precompiler considers this field as varying-character. The ERROR_MSG field may be declared any size from one to 255. The VARCHAR form may be used if the variable definition is included in a declare section. The precompiler expands the definition to the ERROR_MSG structure, which should be coded if the definition is outside a declare section. PPRTEXT returns at most the number of bytes in the message and/or the value given in the next field (MAX_LENGTH). Remaining bytes are not filled with spaces. The application may initialize the ERROR_MSG.arr field to spaces prior to calling PPRTEXT. As with other varying character fields, no terminating null is placed at the end of the error message. The application should use the ERROR_MSG.len field to determine the size of the actual text returned. 4 MAX_LENGTH Application declares and initializes this field. The name is not important and the name given is just an example. PPRTEXT uses this field to determine the amount of text that may be placed in the text receiving field (ERROR_MSG.arr, above); the value may be less than the actual size of the text field. If the message text exceeds this value, the text is truncated; if the value of this field exceeds the size of the receiving field, unpredictable results may occur. Declare this field as follows: short MAX_LENGTH = 255; Note: Code the call to PPRTEXT as follows: PPRTEXT (&SQL_RDTRTCON, &ERROR_CODE, &ERROR_MSG, &MAX_LENGTH); Typical PPRTEXT usage is shown in the Dynamic Statement Example on page 110. Exception Conditions: WHENEVER The WHENEVER statement specifies the action to be taken when an exception condition occurs. See Embedded SQL in SQL Reference: Stored Procedures and Embedded SQL for more details. 108 Teradata Preprocessor2 for Embedded SQL Programmer Guide

109 Chapter 3: Writing Embedded SQL Applications in C Exception Conditions: WHENEVER Exception Conditions This condition Occurs when the SQLWARNING SQLWARN0 field in the SQLCA is W or SQLCODE > 0 SQLERROR SQLCODE field in the SQLCA is < 0 NOTFOUND SQLCODE field in the SQLCA is +100 For any condition, one of the following actions can be taken: With this action logic CONTINUE GOTO host label CALL function call Processing continues to the next executable statement in the application program (that is, the exception condition is ignored). at the specified location. with the specified function call. WHENEVER Is Declarative The WHENEVER statement itself is not executable. PP2 generates code for each executable SQL statement based on the WHENEVER conditions in effect at the time of the call. If no WHENEVER statement is specified, the default condition is CONTINUE. An explicit WHENEVER statement affects all subsequent SQL statements until another WHENEVER statement is encountered. This is a declarative; the WHENEVER statement is processed as it is sequenced in the source and not how it is executed at runtime. Rules for Using WHENEVER The WHENEVER statement must precede the SQL statement or statements for which the condition is to apply. When it is used, the host label object must follow C rules for the C goto instruction. The target of the goto is formed following the same rules as a variable name with a colon appended. When the CALL action is used, the function call object must be a valid C function call at every SQL statement to which the exception declaration applies. This translates to a regular C function call and follows the same rules. Teradata Preprocessor2 for Embedded SQL Programmer Guide 109

110 Chapter 3: Writing Embedded SQL Applications in C Dynamic Statement Example Dynamic Statement Example The EMPLOYEE table shown in Appendix C: Embedded SQL Examples. illustrates dynamic statements. It is a sample C program that selects multiple rows from a table called EMPLOYEE, inserts a row into that table, then deletes the row just inserted. This procedure is performed using the three dynamic mechanisms which are available. The program uses directly coded SQL statements, but could also read the statements from a terminal, from a file, or by some other method. A Caution When Using Dynamic SQL Exercise caution whenever character data is returned to host variables using dynamic SQL. When the PREPARE INTO or DESCRIBE statement is executed, the Teradata Database returns a data type code of 452 or 453 (fixed character) in the SQLTYPE field of the SQLDA or 448 or 449 (varying character), according to the SQL data type (CHAR or VARCHAR, respectively). When dynamic SQL statement text is stored in a varchar host variable, the statement text cannot be longer than 64k. If this SQLTYPE is not changed before the data is actually returned, no terminating null is appended. This means that the C string conventions are not desired; the appropriate host variable type is probably varying character. If the data is to be handled as a C string, the terminating null character is required; in this case, the program must alter the SQLTYPE field to 460 or 461 before the data is retrieved, and the appropriate host data type is character string, with a length of one greater than the length of the SQL data (found in the SQLLEN field of the SQLDA). 110 Teradata Preprocessor2 for Embedded SQL Programmer Guide

111 Chapter 3: Writing Embedded SQL Applications in C Dynamic Statement Example Sequence SELECT INSERT DELETE Descriptive Note The SELECT statement is a data returning statement (potentially). Thus the statement is executed using a dynamic cursor. The PREPARE readies the statement in the SQL string SQL_STATEMENT for execution. The DESCRIBE returns information about the data coming back into the user defined SQLDA (SQLDA). Notice that the program initializes the SqlDAID, SqlDABC and SqlN fields prior to executing the DESCRIBE request. SqlDABC is set by PP2 runtime, while SqlN indicates to the DESCRIBE the number of repeating element groups available to contain field information. The OPEN statement specifies the host variable whose value is to replace the null found in the SELECT statement. The OPEN executes the select, returning an indication of success or failure to the application, as well as the number of rows which are returned if the statement is successfully executed. The FETCH loop returns the data into the specified host variables (via the SQLDA structure) until no more data is found (+100 in the SQLCODE) or an error occurs (negative SQLCODE). The CLOSE terminates the cursor and performs the cleanup related to the select statement. The INSERT statement does not return data, nor does it require input host variables. This facility allows the statement to execute using an EXECUTE IMMEDIATE. The DELETE statement does not return data, but requires an input host variable, which requires an EXECUTE statement. The PREPARE readies the statement in the SQL string for execution. A DESCRIBE is not required for the delete since no data is returned. The EXECUTE submits the DELETE statement to the Teradata Database for processing, passing the value of the host variable indicated in the SQLDA (SQLDA) for the null. The success or failure of the transaction is reflected in the SQLCODE. The number of rows deleted, if any, appears in the first SQLERRD element. EXEC SQL BEGIN DECLARE SECTION; char LOGON_STRING[13]; long EMPNUM; long MANNUM; long DPTNUM; long JOBNUM; char LSTNAM[21]; char FSTNAM[31]; char HIRDAT[11]; char BRTDAT[11]; float SALARY; Teradata Preprocessor2 for Embedded SQL Programmer Guide 111

112 Chapter 3: Writing Embedded SQL Applications in C Dynamic Statement Example short EMPIND; short MANIND; short DPTIND; short JOBIND; short LSTIND; short FSTIND; short HIRIND; short BRTIND; short SALIND; VARCHAR SQL_STATEMENT[180]; EXEC SQL END DECLARE SECTION; int ERROR_CODE; struct { short len; char arr[255]; } ERROR_MSG; short MAX_LENGTH = 255; char REQUEST_TYPE[9]; struct { char SqlDAID[8]; int SqlDABC; short SqlN; short SqlD; struct { short SqlTYPE; short SqlLEN; char *SqlDATA; char *SqlIND; struct { short strlen; char str[30]; } SqlNAME; } SqlVAR[9]; } SQLDA; EXEC SQL INCLUDE SQLCA; EXEC SQL DECLARE EMPCUR CURSOR FOR EMPSTMT; /*******************************************************/ /********** ERROR CHECK */ /*******************************************************/ ERROR_CHECK () { if (SQLCODE! = 0) { PPRTEXT (&SQL_RDTRTCON, &ERROR_CODE, &ERROR_MSG, &MAX_LENGTH); ERROR_MSG.arr[ERROR_MSG.len] = \0 ; printf ( \n ); printf ( ERROR/WARNING DETECTED IN %s\n, REQUEST_TYPE); printf ( CODE: %d\n, ERROR_CODE); printf ( MSG : %s\n, ERROR_MSG.arr); } } /*******************************************************/ /********** FETCH */ 112 Teradata Preprocessor2 for Embedded SQL Programmer Guide

113 Chapter 3: Writing Embedded SQL Applications in C Dynamic Statement Example /*******************************************************/ FETCH_EMPCUR () { strcpy (REQUEST_TYPE, FETCH ); EXEC SQL FETCH EMPCUR USING DESCRIPTOR SQLDA; ERROR_CHECK (); if (SQLCODE == 0) { printf ( \n ); printf ( EMPLOYEE NUMBER : %ld\n, EMPNUM); printf ( MANAGER NUMBER : %ld\n, MANNUM); printf ( DEPARTMENT NUMBER : %ld\n, DPTNUM); printf ( JOB CODE : %ld\n, JOBNUM); printf ( LAST NAME : %s\n, LSTNAM); printf ( FIRST NAME : %s\n, FSTNAM); printf ( HIRE DATE : %s\n, HIRDAT); printf ( BIRTH DATE : %s\n, BRTDAT); printf ( SALARY : %lf\n, SALARY); } } /*******************************************************/ /********** LOGOFF */ /*******************************************************/ LOGOFF () { strcpy (REQUEST_TYPE, LOGOFF ); EXEC SQL LOGOFF; ERROR_CHECK (); } /*******************************************************/ /********** MAIN */ /*******************************************************/ main () { printf ( EXECUTING SAMPLE...\n\n ); /*******************************************************/ /********** LOGON */ /*******************************************************/ strcpy (REQUEST_TYPE, LOGON ); strcpy (LOGON_STRING, tdp/user,psw ); EXEC SQL LOGON :LOGON_STRING; ERROR_CHECK (); if (SQLCODE! = 0) return; /*******************************************************/ /********** PREPARE */ /*******************************************************/ strcpy (REQUEST_TYPE, PREPARE ); strcpy (SQL_STATEMENT.arr, SELECT EMPLOYEE_NUMBER, ); strcat (SQL_STATEMENT.arr, MANAGER_EMPLOYEE_NUMBER, ); strcat (SQL_STATEMENT.arr, DEPARTMENT_NUMBER, ); strcat (SQL_STATEMENT.arr, JOB_CODE, ); strcat (SQL_STATEMENT.arr, LAST_NAME, ); strcat (SQL_STATEMENT.arr, FIRST_NAME, ); strcat (SQL_STATEMENT.arr, HIRE_DATE, ); strcat (SQL_STATEMENT.arr, BIRTHDATE, ); Teradata Preprocessor2 for Embedded SQL Programmer Guide 113

114 Chapter 3: Writing Embedded SQL Applications in C Dynamic Statement Example strcat (SQL_STATEMENT.arr, SALARY_AMOUNT ); strcat (SQL_STATEMENT.arr, FROM EMPLOYEE ); strcat (SQL_STATEMENT.arr, WHERE EMPLOYEE_NUMBER =? ); SQL_STATEMENT.len = strlen (SQL_STATEMENT.arr); EXEC SQL PREPARE EMPSTMT FROM :SQL_STATEMENT; ERROR_CHECK (); if (SQLCODE!= 0) { LOGOFF (); return; } /*******************************************************/ /********** DESCRIBE */ /*******************************************************/ strcpy (REQUEST_TYPE, DESCRIBE ); strncpy (SQLDA.SqlDAID, SQLDA, 8); SQLDA.SqlDABC = 0; SQLDA.SqlN = 9; EXEC SQL DESCRIBE EMPSTMT INTO SQLDA; ERROR_CHECK (); if (SQLCODE!= 0) { LOGOFF (); return; } SQLDA.SqlVAR[0].SqlDATA = (char *) (&EMPNUM); SQLDA.SqlVAR[0].SqlIND = (short *) (&EMPIND); SQLDA.SqlVAR[1].SqlDATA = (char *) (&MANNUM); SQLDA.SqlVAR[1].SqlIND = (short *) (&MANIND); SQLDA.SqlVAR[2].SqlDATA = (char *) (&DPTNUM); SQLDA.SqlVAR[2].SqlIND = (short *) (&DPTIND); SQLDA.SqlVAR[3].SqlDATA = (char *) (&JOBNUM); SQLDA.SqlVAR[3].SqlIND = (short *) (&JOBIND); SQLDA.SqlVAR[4].SqlDATA = LSTNAM; SQLDA.SqlVAR[4].SqlIND = (short *) (&LSTIND); SQLDA.SqlVAR[5].SqlDATA = FSTNAM; SQLDA.SqlVAR[5].SqlIND = (short *)) (&FSTIND); SQLDA.SqlVAR[6].SqlDATA = HIRDAT; SQLDA.SqlVAR[6].SqlIND = (short *) (&HIRIND); SQLDA.SqlVAR[7].SqlDATA = BRTDAT; SQLDA.SqlVAR[7].SqlIND = (short *) (&BRTIND); SQLDA.SqlVAR[8].SqlDATA = (char *) (&SALARY); SQLDA.SqlVAR[8].SqlIND = (short *) (&SALIND); SQLDA.SqlVAR[4].SqlTYPE = 460; SQLDA.SqlVAR[5].SqlTYPE = 460; SQLDA.SqlVAR[6].SqlTYPE = 460; SQLDA.SqlVAR[6].SqlLEN = 10; SQLDA.SqlVAR[7].SqlTYPE = 460; SQLDA.SqlVAR[7].SqlLEN = 10; SQLDA.SqlVAR[8].SqlTYPE = 480; SQLDA.SqlVAR[8].SqlLEN = 4; /*******************************************************/ /********** OPEN */ /*******************************************************/ strcpy (REQUEST_TYPE, OPEN ); EMPNUM = 1001; EXEC SQL 114 Teradata Preprocessor2 for Embedded SQL Programmer Guide

115 Chapter 3: Writing Embedded SQL Applications in C Dynamic Statement Example OPEN EMPCUR USING :EMPNUM; ERROR_CHECK (); if (SQLCODE < 0) { LOGOFF (); return; } while (SQLCODE == 0) { FETCH_EMPCUR (); } /*******************************************************/ /********** CLOSE */ /*******************************************************/ strcpy (REQUEST_TYPE, CLOSE ); EXEC SQL CLOSE EMPCUR; ERROR_CHECK (); /*******************************************************/ /********** EXECUTE IMMEDIATE */ /*******************************************************/ strcpy (REQUEST_TYPE, EXECUTE ); strcpy (SQL_STATEMENT.arr, INSERT EMPLOYEE VALUES ( ); strcat (SQL_STATEMENT.arr, 2010,1003,2216,8201, JONES, ); strcat (SQL_STATEMENT.arr, FREDDY, 20/06/14, ); strcat (SQL_STATEMENT.arr, 19/05/26,200000) ); SQL_STATEMENT.len = strlen (SQL_STATEMENT.arr); EXEC SQL EXECUTE IMMEDIATE :SQL_STATEMENT; ERROR_CHECK () ; /*******************************************************/ /********** PREPARE */ /*******************************************************/ strcpy (REQUEST_TYPE, PREPARE ); strcpy (SQL_STATEMENT.arr, DELETE FROM EMPLOYEE ); strcat (SQL_STATEMENT.arr, WHERE EMPLOYEE_NUMBER =? ); SQL_STATEMENT.len = strlen (SQL_STATEMENT.arr); EXEC SQL PREPARE DELSTMT FROM :SQL_STATEMENT; ERROR_CHECK (); if (SQLCODE!= 0) { LOGOFF (); return; } /*******************************************************/ /********** EXECUTE */ /*******************************************************/ EMPNUM = 2010; SQLDA.SqlDABC = 60; SQLDA.SqlN = 1; SQLDA.SqlD = 1; SQLDA.SqlVAR[0].SqlTYPE = 496; SQLDA.SqlVAR[0].SqlLEN = 4; SQLDA.SqlVAR[0].SqlDATA = (char *) (&EMPNUM); SQLDA.SqlVAR[0].SqlIND = 0; strcpy (REQUEST_TYPE, EXECUTE ); EXEC SQL EXECUTE DELSTMT USING DESCRIPTOR SQLDA; Teradata Preprocessor2 for Embedded SQL Programmer Guide 115

116 Chapter 3: Writing Embedded SQL Applications in C Include SQLDA Example ERROR_CHECK (); LOGOFF (); } Include SQLDA Example EXEC SQL BEGIN DECLARE SECTION; static char LOGON_STRING[13]; static long EMPNUM static long MANNUM; static long DPTNUM; static long JOBNUM; static short EMPIND; static short MANIND; static short DPTIND; static short JOBIND; static VARCHAR SQL_STATEMENT[180]; static int ERROR_CODE; static VARCHAR ERROR_MSG[81]; static short MAX_LENGTH = 80; EXEC SQL END DECLARE SECTION; static char REQUEST_TYPE[9]; EXEC SQL INCLUDE SQLDA; static struct sqlda *SQLDA; EXEC SQL INCLUDE SqlCA; EXEC SQL DECLARE EMPCUR CURSOR FOR EMPSTMT; /*******************************************************/ /********** ERROR CHECK */ /*******************************************************/ static void ERROR_CHECK () { if (SqlCA.SqlCode!= 0) { PPRTEXT (&SQL_RDTRTCON, &ERROR_CODE, &ERROR_MSG, &MAX_LENGTH); ERROR_MSG.arr[ERROR_MSG.len] = \0 ; printf ( \n ); printf ( ERROR/WARNING DETECTED IN %s\n, REQUEST_TYPE); printf ( CODE: %d\n, ERROR_CODE); printf ( MSG : %s\n, ERROR_MSG.arr); } } /*******************************************************/ /********** FETCH */ /*******************************************************/ static void FETCH_EMPCUR () { strcpy (REQUEST_TYPE, FETCH ); EXEC SQL FETCH EMPCUR USING DESCRIPTOR *SQLDA; ERROR_CHECK (); if (SqlCA.SqlCode == 0) { printf ( \n ); 116 Teradata Preprocessor2 for Embedded SQL Programmer Guide

117 Chapter 3: Writing Embedded SQL Applications in C Include SQLDA Example printf ( EMPLOYEE NUMBER : %ld\n, EMPNUM); printf ( MANAGER NUMBER : %ld\n, MANNUM); printf ( DEPARTMENT NUMBER : %ld\n, DPTNUM); printf ( JOB CODE : %ld\n, JOBNUM); } } /*******************************************************/ /********** MAIN */ /*******************************************************/ main () { printf ( EXECUTING DYNAMIC SAMPLE...\n\n ); /*******************************************************/ /********** LOGON */ /*******************************************************/ strcpy (REQUEST_TYPE, LOGON ); strcpy (LOGON_STRING, TDP/USER,PWD ); EXEC SQL LOGON :LOGON_STRING; ERROR_CHECK (); if (SqlCA.SqlCode!= 0) return (1); /*******************************************************/ /********** PREPARE */ /*******************************************************/ strcpy (REQUEST_TYPE, PREPARE ); strcpy (SQL_STATEMENT.arr, SELECT EMPLOYEE_NUMBER, \ MANAGER_EMPLOYEE_NUMBER, DEPARTMENT_NUMBER, JOB_CODE \ FROM EMPLOYEE ORDER BY EMPLOYEE_NUMBER ); SQL_STATEMENT.len = strlen (SQL_STATEMENT.arr); EXEC SQL DECLARE EMPSTMT STATEMENT; ERROR_CHECK (); EXEC SQL PREPARE EMPSTMT FROM :SQL_STATEMENT; ERROR_CHECK (); /*******************************************************/ /********** DESCRIBE */ /*******************************************************/ strcpy (REQUEST_TYPE, DESCRIBE ); SQLDA = (struct sqlda *) malloc (SQLDASIZE(4)); if (SQLDA == NULL) { fprintf (stderr, Error: could not allocate SQLDA!\n ); return (1); } memcpy (SQLDA->sqldaid, SQLDA, 8); SQLDA->sqldabc = 0; SQLDA->sqln = 4; EXEC SQL DESCRIBE EMPSTMT INTO *SQLDA; ERROR_CHECK (); if (SqlCA.SqlCode == 0) { SQLDA->sqlvar[0].sqldata = (unsigned char *) (&EMPNUM); SQLDA->sqlvar[0].sqlind = &EMPIND; SQLDA->sqlvar[1].sqldata = (unsigned char *) (&MANNUM); SQLDA->sqlvar[1].sqlind = &MANIND; SQLDA->sqlvar[2].sqldata = (unsigned char *) (&DPTNUM); Teradata Preprocessor2 for Embedded SQL Programmer Guide 117

118 Chapter 3: Writing Embedded SQL Applications in C Multi-Session Programming SQLDA->sqlvar[2].sqlind = &DPTIND; SQLDA->sqlvar[3].sqldata = (unsigned char *) (&JOBNUM); SQLDA->sqlvar[3].sqlind = &JOBIND; } /*******************************************************/ /********** OPEN */ /*******************************************************/ strcpy (REQUEST_TYPE, OPEN ); EXEC SQL OPEN EMPCUR; ERROR_CHECK (); while (SqlCA.SqlCode == 0) FETCH_EMPCUR (); /*******************************************************/ /********** CLOSE */ /*******************************************************/ strcpy (REQUEST_TYPE, CLOSE ); EXEC SQL CLOSE EMPCUR; ERROR_CHECK (); /*******************************************************/ /********** LOGOFF */ /*******************************************************/ strcpy (REQUEST_TYPE, LOGOFF ); EXEC SQL LOGOFF; ERROR_CHECK (); return (0); } Multi-Session Programming Example This program demonstrates PP2's facilities for multi-session programming. Specifically, it tests the asynchronous processing of SQL requests useful when multiple DBS sessions are being used. The syntax for the asynchronous processing PP2 statement types (that is, ASYNC, TEST and WAIT) used in this program is: ASYNC (<async statement identifier>) TEST <async statement identifier> COMPLETION WAIT <async statement list> COMPLETION WAIT ALL COMPLETION #include <stdio.h> #include <string.h> EXEC SQL BEGIN DECLARE SECTION; char LOGON_STRING[30]; char USER[30]; 118 Teradata Preprocessor2 for Embedded SQL Programmer Guide

119 Chapter 3: Writing Embedded SQL Applications in C Multi-Session Programming char CNAME[30]; long EMPNUM; int SQLCODE; short int EMPIND; VARCHAR errmsg[81]; short USERIND; EXEC SQL END DECLARE SECTION; EXEC SQL INCLUDE sqlca; long errcode; short maxlen = 80; char REQUEST_TYPE[30]; /**************************************************************/ /* DECLARE CURSORS / **************************************************************/ EXEC SQL DECLARE EMPCUR1 CURSOR FOR SELECT EMPLOYEE_NUMBER FROM EMPLOYEE; EXEC SQL DECLARE EMPCUR2 CURSOR FOR SELECT EMPLOYEE_NUMBER FROM EMPLOYEE; EXEC SQL DECLARE EMPCUR3 CURSOR FOR SELECT EMPLOYEE_NUMBER FROM EMPLOYEE; /**************************************************************/ /*ERROR_CHECK - check the sqlcode from the last SQL request made*/ /* and print a message for any non-zero sqlcode */ /**************************************************************/ ERROR_CHECK(char *REQUEST_TYPE) { if (sqlca.sqlcode!= 0) { PPRTEXT(&SQL_RDTRTCON, &errcode, &errmsg, &maxlen); errmsg.arr[errmsg.len] = '\0'; printf("\n"); printf("error/warning DETECTED IN %s\n", REQUEST_TYPE); printf(" SQL CODE : %d\n", sqlca.sqlcode); printf(" ERROR CODE: %d\n", sqlca.sqlerrd[0]); printf(" MSG : %s\n", errmsg.arr); } } /**************************************************************/ /*LOGON_FUNC - logon to the DBS using the specified LOGON string*/ /* and connection name. */ /**************************************************************/ logon_func(char *string, char *conname) { strcpy(logon_string, string); strcpy(cname, conname); EXEC SQL LOGON :LOGON_STRING AS :CNAME; ERROR_CHECK("LOGON"); if (sqlca.sqlcode!= 0) return; } /**************************************************************/ /* SELECT_USER - get the name of this DBS user and store it. */ /**************************************************************/ SELECT_USER() { Teradata Preprocessor2 for Embedded SQL Programmer Guide 119

120 Chapter 3: Writing Embedded SQL Applications in C Multi-Session Programming EXEC SQL SELECT USER INTO :USER INDICATOR :USERIND; ERROR_CHECK("SELECT"); if (sqlca.sqlcode == 0) { USER[29] = '\0'; printf("\n"); printf("user : %s\n", USER); } } /**************************************************************/ /*SET_CONNECTION - the the programs's current session to the one*/ /* associated with the specified connection name */ /**************************************************************/ set_connection(char *conname) { strcpy(cname, conname); EXEC SQL SET CONNECTION :CNAME; ERROR_CHECK("SET CONNECTION"); if (sqlca.sqlcode!= 0) return; SELECT_USER(); } /**************************************************************/ /* MAIN PROGRAM */ /**************************************************************/ main(int argn, char **log) { /* Create 5 DBS sessions */ logon_func(log[1], "STV2A"); logon_func(log[1], "STV2B"); logon_func(log[1], "STV2C"); logon_func(log[1], "STV2D"); logon_func(log[1], "STV2E"); set_connection("stv2a"); /* Set the current session to STV2A */ /* Initiate the SQL SELECT associated with cursor EMPCUR1, */ /* labeling this asynchronous request SELECT1, but don't wait */ /* for the request to be completed. */ EXEC SQL ASYNC (SELECT1) OPEN EMPCUR1; ERROR_CHECK("OPEN EMPCUR1"); set_connection("stv2b"); /* Set the current session to STV2B */ /* Initiate the SQL SELECT associated with cursor EMPCUR2, */ /* labeling this asynchronous request SELECT2, but don't wait */ /* for the request to be completed. */ EXEC SQL ASYNC (SELECT2) OPEN EMPCUR2; ERROR_CHECK("OPEN EMPCUR2"); set_connection("stv2c"); /* Set the current session to STV2C */ /* Initiate the SQL SELECT associated with cursor EMPCUR3, */ /* labeling this asynchronous request SELECT3, but don't wait */ /* for the request to be completed. */ 120 Teradata Preprocessor2 for Embedded SQL Programmer Guide

121 Chapter 3: Writing Embedded SQL Applications in C Multi-Session Programming } EXEC SQL ASYNC (SELECT3) OPEN EMPCUR3; ERROR_CHECK("OPEN EMPCUR3"); /* Now, wait here for request SELECT1 to be completed. */ EXEC SQL WAIT SELECT1 COMPLETION; ERROR_CHECK("WAIT SELECT1"); if (sqlca.sqlcode == 0) { printf("\nwait FOR SELECT1 REQUEST COMPLETED. \n"); } /* Test for the completion of request SELECT1. */ EXEC SQL TEST SELECT1 COMPLETION; ERROR_CHECK("TEST FOR SELECT1"); set_connection("stv2a"); /* Reset the current session to STV2A */ while (sqlca.sqlcode == 0) /* Retrieve the rows from the SELECT */ { /* associated with cursor EMPCUR1 */ EXEC SQL FETCH EMPCUR1 INTO :EMPNUM INDICATOR :EMPIND; ERROR_CHECK("FETCH EMPCUR1"); if (sqlca.sqlcode == 0) { printf("\nemployee NUMBER : %ld\n", EMPNUM); } } /* Now, wait here for all other outstanding asynchronous */ /* requests to be completed (in this case SELECT2 & SELECT3). */ EXEC SQL WAIT ALL COMPLETION; ERROR_CHECK("WAIT ALL"); if (sqlca.sqlcode == 0) { printf("\nwait ALL COMPLETED. \n"); } /* Test for the completion of request SELECT2. */ EXEC SQL TEST SELECT2 COMPLETION; ERROR_CHECK("TEST FOR SELECT2"); set_connection("stv2b"); /* Set the current session to STV2B */ while (sqlca.sqlcode == 0) /* Retrieve the rows from the SELECT */ { /* associated with cursor EMPCUR2 */ EXEC SQL FETCH EMPCUR2 INTO :EMPNUM INDICATOR :EMPIND; ERROR_CHECK("FETCH EMPCUR2"); printf("employee NUMBER : %ld\n", EMPNUM); } /* Logoff from the DBS all (5) sessions created by this program */ EXEC SQL LOGOFF ALL; ERROR_CHECK("LOGOFF"); Teradata Preprocessor2 for Embedded SQL Programmer Guide 121

122 Chapter 3: Writing Embedded SQL Applications in C Online Archive Program Output After the following setup SQL is executed against the database: create table employee(employee_number integer); insert into employee(1); insert into employee sel employee_number+1 from employee; insert into employee sel employee_number+2 from employee; insert into employee sel employee_number+4 from employee; the output from this sample program is: USER : WEEKLY USER : WEEKLY USER : WEEKLY WAIT FOR SELECT1 REQUEST COMPLETED. USER : WEEKLY EMPLOYEE NUMBER : 2 EMPLOYEE NUMBER : 5 EMPLOYEE NUMBER : 9 EMPLOYEE NUMBER : 7 EMPLOYEE NUMBER : 4 EMPLOYEE NUMBER : 6 EMPLOYEE NUMBER : 8 EMPLOYEE NUMBER : 3 EMPLOYEE NUMBER : 1 ERROR/WARNING DETECTED IN FETCH EMPCUR1 SQL CODE : 100 ERROR CODE: 0 MSG : No (or no more) rows of data satisfy the request WAIT ALL COMPLETED. USER : WEEKLY EMPLOYEE NUMBER : 2 EMPLOYEE NUMBER : 5 EMPLOYEE NUMBER : 9 EMPLOYEE NUMBER : 7 EMPLOYEE NUMBER : 4 EMPLOYEE NUMBER : 6 EMPLOYEE NUMBER : 8 EMPLOYEE NUMBER : 3 EMPLOYEE NUMBER : 1 ERROR/WARNING DETECTED IN FETCH EMPCUR2 SQL CODE : 100 ERROR CODE: 0 MSG : No (or no more) rows of data satisfy the request EMPLOYEE NUMBER : 1 Online Archive Online archive is a process in which rows are archived from a table at the same time update, insert, or delete operations on the table are taking place. When an online archive is initiated on a table or a database, a log is created for the specified table or separate logs are created for each table in the specified database. The log, which contains all changes to the table, is saved as a part of the archive process. The changes recorded in the log can be applied to any changes to the table that occurred during the archive, such as a restore operation. 122 Teradata Preprocessor2 for Embedded SQL Programmer Guide

123 Chapter 3: Writing Embedded SQL Applications in C Performing a Stored Procedure Two new SQL statements start and stop the online archive process: LOGGING ONLINE ARCHIVE ON and LOGGING ONLINE ARCHIVE OFF. Example The following SQL statement initiates the online archive process for the database on a weekly basis: EXEC SQL LOGGING ONLINE ARCHIVE ON FOR WEEKLY; Example The following SQL statement stops the weekly online archive of the database: EXEC SQL LOGGING ONLINE ARCHIVE OFF FOR WEEKLY; Performing a Stored Procedure Stored Procedure This program illustrates the use of PP2's SQL CALL facility to execute a Teradata Database stored procedure from a program. The stored procedure being executed is named case1 and has been defined as: /* replace procedure case1(in ip integer, INOUT iop integer, OUT op integer) /* begin set op=ip+2; set iop=iop+ip; end; Example #include <stdio.h> #include <string.h> EXEC SQL BEGIN DECLARE SECTION; int H1; int H2; int H3; VARCHAR LOGON_STR[30]; VARCHAR errmsg[81]; EXEC SQL END DECLARE SECTION; EXEC SQL INCLUDE SQLCA; long errcode; long i; long count; short maxlen = 80; Teradata Preprocessor2 for Embedded SQL Programmer Guide 123

124 Chapter 3: Writing Embedded SQL Applications in C Performing a Stored Procedure char reqtype[40]; int ch; /**************************************************************/ /* error_check */ /**************************************************************/ void error_check() { if (SQLCODE!= 0) { PPRTEXT(&SQL_RDTRTCON, &errcode, &errmsg, &maxlen); errmsg.arr[errmsg.len] = '\0'; printf("\n"); printf("error/warning DETECTED IN %s\n", reqtype); printf(" CODE: %d\n", errcode); printf(" MSG : %s\n", errmsg.arr); } } /**************************************************************/ /* exec_request_001 */ /**************************************************************/ void exec_request_001() { strcpy(reqtype, "CALL PROCEDURE"); H1=1; EXEC SQL CALL case1(:h1, :H2, :H3); error_check(); if (SQLCODE == 0) { printf("h1 -%d\n",h1); printf("h2 -%d\n",h2); printf("h3 -%d\n",h3); printf("finished REQUEST001\n"); } return; } /**************************************************************/ /* exec_request_002 */ /**************************************************************/ void exec_request_002() { strcpy(reqtype, "CALL PROCEDURE"); H1=1; H2=2; EXEC SQL CALL case1(:h1, :H2, :H3); error_check(); if (SQLCODE == 0) { printf("h1 -%d\n",h1); printf("h2 -%d\n",h2); printf("h3 -%d\n",h3); printf("finished REQUEST002\n"); } return; } /**************************************************************/ /* exec_request_003 */ /**************************************************************/ void exec_request_003() 124 Teradata Preprocessor2 for Embedded SQL Programmer Guide

125 Chapter 3: Writing Embedded SQL Applications in C Performing a Stored Procedure { strcpy(reqtype, "CALL PROCEDURE"); EXEC SQL CALL case1(1, :H2, :H3); error_check(); if (SQLCODE == 0) { printf("h2 -%d\n",h2); printf("h3 -%d\n",h3); printf("finished REQUEST003\n"); } return; } /**************************************************************/ /* exec_request_004 */ /**************************************************************/ void exec_request_004() { strcpy (reqtype, "CALL PROCEDURE"); H1=2; EXEC SQL CALL case1(:h1*:h1, :H2, :H3); error_check(); if (SQLCODE == 0) { printf("h2 -%d\n",h2); printf("h3 -%d\n",h3); printf("finished REQUEST004\n"); } return; } /**************************************************************/ /* MAIN PROGRAM */ /**************************************************************/ main(argc, argv) int argc; char *argv[]; { int i; if (argc < 2) { printf("you must supply the LOGON STRING.\n"); exit(1); } printf ("Executing stored procedure 'case1'...\n\n"); strcpy(logon_str.arr, argv[1]); LOGON_STR.len = strlen(logon_str.arr); /* LOGON the DBS */ strcpy(reqtype, "LOGON"); EXEC SQL LOGON :LOGON_STR; error_check(); if (SQLCODE!= 0) exit(1); printf("logon SUCCESSFUL!\n"); /* Execute the 4 stored-procedure calling functions */ exec_request_001(); exec_request_002(); exec_request_003(); exec_request_004(); Teradata Preprocessor2 for Embedded SQL Programmer Guide 125

126 Chapter 3: Writing Embedded SQL Applications in C Using Stored Procedure Dynamic Result Sets } Program Output /* LOGOFF the DBS */ strcpy (reqtype, "LOGOFF"); EXEC SQL LOGOFF; error_check(); if (SQLCODE == 0) printf("logoff SUCCESSFUL!\n"); return; Executing stored procedure 'case1'... LOGON SUCCESSFUL! H1-1 H2-1 H3-3 FINISHED REQUEST001 H1-1 H2-3 H3-3 FINISHED REQUEST002 H2-4 H3-3 FINISHED REQUEST003 H2-8 H3-6 FINISHED REQUEST004 LOGOFF SUCCESSFUL! Using Stored Procedure Dynamic Result Sets Before stored procedure dynamic result sets, it was not possible to call a stored procedure and have the procedure produce a response spool. Instead, it was necessary to create a temporary table for the results, then gather the results by using a SELECT statement after the stored procedure CALL statement. Now, ANSI SQL allows stored procedures to return what are called dynamic result sets. The number of result sets are specified in the CREATE PROCEDURE statement. Each result set returns a result similar to the output of one multistatement request. The result sets are returned to PP2 using PP2 s client character set and response mode. When using stored procedure dynamic result sets, the application needs to be precompiled with SQLCHECK(FULL) and TRANSACT(BTET) options. This is required so that the variables receiving the OUTPUT or INOUT parameters can be passed from the precompiler to the runtime. When a stored procedure without dynamic result sets is called, SQLCHECK must be specified as FULL: -sc FULL for network environments SQLCHECK(FULL) if Mainframe 126 Teradata Preprocessor2 for Embedded SQL Programmer Guide

127 Chapter 3: Writing Embedded SQL Applications in C Using UPSERT in Embedded SQL For a stored procedure with dynamic result sets, a cursor is defined, and the transaction mode must be specified as BTET: -tr BTET for network environments TRANSACT(BTET) for mainframe environments If BTET is not specified, a 5497 SQLCODE occurs (CALL cannot be submitted in a multistatement request.) To declare a cursor to access a stored procedure, use the next example: EXEC SQL BEGIN DECLARE SECTION;... long H1; long H2; long M1; long M2; long M3;... EXEC SQL END DECLARE SECTION;... EXEC SQL DECLARE TESTCUR CURSOR FOR 'CALL TESTSP1(:H1, :H2)'; EXEC SQL OPEN TESTCUR; If the cursor is created properly and the stored procedure returns one or more rows, the SQLCODE is set to 3212, indicating that the stored procedure returned a result set. If the cursor is created properly but the stored procedure returns no rows, the SQLCODE is set to 0. if (SQLCODE == 3212) fetch_rows(); else if (SQLCODE!= 0) error_check(); Fetching rows from a cursor that is declared for a stored procedure is similar to fetching rows from a cursor defined as an SQL statement. void fetch_rows() do { EXEC SQL FETCH TESTCUR INTO :M1, :M2, :M3;... } while (SQLCODE == 0); Using UPSERT in Embedded SQL This program illustrates the use of the upsert SQL request (update, if target row exists, else insert new row) in a PP2 application program. Teradata Preprocessor2 for Embedded SQL Programmer Guide 127

128 Chapter 3: Writing Embedded SQL Applications in C Using UPSERT in Embedded SQL Example EXEC SQL BEGIN DECLARE SECTION; char LOGON_STRING[15]; long ITEMCOUNT; long ITEM; short EMPIND; EXEC SQL END DECLARE SECTION; EXEC SQL INCLUDE SqlCA; char REQUEST_TYPE[9]; /**************************************************************/ /* DECLARE CURSOR */ /**************************************************************/ EXEC SQL DECLARE EMPCUR CURSOR FOR SELECT itemcount, item FROM UPSTB; /**************************************************************/ /* ERROR CHECK */ /**************************************************************/ ERROR_CHECK() { if (SqlCA.SqlCode!= 0) { printf("\n"); printf("error/warning DETECTED IN %s\n", REQUEST_TYPE); printf(" SQL CODE : %d\n", SqlCA.SqlCode); printf(" ERROR CODE: %d\n", SqlCA.SqlErrd[0]); } } /**************************************************************/ /* FETCH_CURSOR */ /**************************************************************/ FETCH_CURSOR() { strcpy(request_type, "FETCH"); EXEC SQL FETCH EMPCUR INTO :ITEMCOUNT,ITEM; if (SqlCA.SqlCode!= 0) return; ERROR_CHECK(); if (SqlCA.SqlCode == 0) { printf("\n"); printf("upstb row : %ld %d\n",item,itemcount); } } 128 Teradata Preprocessor2 for Embedded SQL Programmer Guide

129 Chapter 3: Writing Embedded SQL Applications in C Using UPSERT in Embedded SQL /**************************************************************/ /* MAIN PROGRAM */ /**************************************************************/ main() { printf("executing \"upsert\" SQL: \n\n"); printf("update upstb set itemcount=11 where item=11 else\n"); printf("insert into upstb(11,11)...\n"); /* LOGON to the DBS */ strcpy(request_type, "LOGON"); strcpy(logon_string, "ssdb/weekly,weekly"); EXEC SQL LOGON :LOGON_STRING; ERROR_CHECK(); if (SqlCA.SqlCode!= 0) return; /* OPEN the cursor */ strcpy(request_type, "OPEN"); EXEC SQL OPEN EMPCUR; ERROR_CHECK(); if (SqlCA.SqlCode == 0) { printf("\n"); printf("before UPSERT: %d ROWS SELECTED\n", SqlCA.SqlErrd[2]); } /* Retrieve and display the rows before the "upsert" */ while (SqlCA.SqlCode == 0) { FETCH_CURSOR(); if (SqlCA.SqlCode!= 0) break; } /* CLOSE the cursor */ strcpy(request_type, "CLOSE"); EXEC SQL CLOSE EMPCUR; ERROR_CHECK(); /* Now, perform the SQL "upsert" operation */ strcpy(request_type, "update"); EXEC SQL update upstb set itemcount=11 where item=11 else insert into upstb(11,11); ERROR_CHECK(); /* ReOPEN the cursor */ strcpy(request_type, "OPEN"); Teradata Preprocessor2 for Embedded SQL Programmer Guide 129

130 Chapter 3: Writing Embedded SQL Applications in C Using UPSERT in Embedded SQL EXEC SQL OPEN EMPCUR; ERROR_CHECK(); if (SqlCA.SqlCode == 0) { printf("\n"); printf("after UPSERT: %d ROWS SELECTED\n", SqlCA.SqlErrd[2]); } /* Retrieve and display the rows after the "upsert" */ while (SqlCA.SqlCode == 0) { FETCH_CURSOR(); if (SqlCA.SqlCode!= 0) break; } /* CLOSE the cursor */ strcpy(request_type, "CLOSE"); EXEC SQL CLOSE EMPCUR; ERROR_CHECK(); /* LOGOFF the DBS */ strcpy(request_type, "LOGOFF"); EXEC SQL LOGOFF; } ERROR_CHECK(); Program Output After the following setup SQL is executed: CREATE TABLE upstb, FALLBACK (item integer, itemcount integer) PRIMARY INDEX (item); insert into upstb(1,1); insert into upstb(2,1); insert into upstb(3,1); insert into upstb(4,1); 130 Teradata Preprocessor2 for Embedded SQL Programmer Guide

131 Chapter 3: Writing Embedded SQL Applications in C Using UPSERT in Embedded SQL the sample program output is: EXECUTING "upsert" SQL: update upstb set itemcount=11 where item=11 else insert into upstb(11,11)... BEFORE UPSERT: 4 ROWS SELECTED UPSTB row : 2 1 UPSTB row : 3 1 UPSTB row : 4 1 UPSTB row : 1 1 AFTER UPSERT: 5 ROWS SELECTED UPSTB row : 2 1 UPSTB row : 3 1 UPSTB row : 4 1 UPSTB row : UPSTB row : 1 1 Teradata Preprocessor2 for Embedded SQL Programmer Guide 131

132 Chapter 3: Writing Embedded SQL Applications in C Using UPSERT in Embedded SQL 132 Teradata Preprocessor2 for Embedded SQL Programmer Guide

133 CHAPTER 4 Writing Embedded SQL Applications in COBOL This chapter discusses the COBOL-specific, language-dependent functions and features of PP2. Some non-language specific details are included for reference. COBOL Language Support For a list of supported PP2 COBOL dialects see Supported Operating Systems and Host Programming Languages on page 24. The COBOL statements generated by PP2 are accepted by the compilers for these environments. In addition, the COBOL statements generated by PP2 conform to these ANSI standard COBOL dialects: COBOL 1974 standard, X (COBOL 74) COBOL 1985 standard, X (COBOL 85) The only exception occurs when the HOST(COBOLII) precompiler option is specified. In this case, PP2 both recognizes and generates code that makes use of the COBOL extensions peculiar to VS COBOL II. Specify either of two types of output formatting with the MARGINS (n,m) option: ANSI Terminal style This document refers to standard COBOL as ANSI in discussing program format. The default format is ANSI, with the margins set to 8 and 72. The beginning column specification for MARGINS, n, must be either 1 or 8; any other value causes an error. By specifying MARGINS(1,m), PP2 follows terminal format rules and may be specified with a value up to 255. The COBOL precompiler is executed by invoking module PPBMAIN. For details, see Chapter 2: Connecting to the Database and Invoking PP2. For linkage details, see Appendix B: Sample Application Linkage Procedure. Teradata Preprocessor2 for Embedded SQL Programmer Guide 133

134 Chapter 4: Writing Embedded SQL Applications in COBOL COBOL Language Support COBOL Application Requirements Each COBOL program that requests Teradata Database services via embedded SQL statements requires a communications area. The different compatibility modes use incompatible data structures or variables to do this. Program Status Information Each time a SQL statement is executed, it returns a code to communicate whether the statement executed successfully or not. You must define an area to receive these codes. When you precompile your applications under Teradata-compatible mode by setting the TRANSACT option to BTET, COMMIT or 2PC, you define a communications area either by using the INCLUDE SQLCA statement or by declaring a SQLCA area in the WORKING STORAGE SECTION of the application. When you precompile your applications under ANSI compatible mode by defining the TRANSACT option as ANSI, you use variables named SQLCODE and SQLSTATE to receive feedback information. You cannot mix program status communication areas between Teradata and ANSI compatible modes. Teradata Mode Communications Area When writing COBOL programs for Teradata mode, define one SQLCA per program. For example, if an application consists of one main program and two subprograms, the main program and each of the subprograms must contain an SQLCA. Declare the SQLCA in the WORKING STORAGE SECTION of the program. Define the necessary SQLCA structure in one of two ways: Code an EXEC SQL INCLUDE SQLCA statement, which causes PP2 to generate the structure. Code the SQLCA directly into the application. The structure must be named SQLCA and must be unique. Declare an SQLCA structure in COBOL as: 01 SQLCA. 05 SQLCAID PIC X(8) VALUE SQLCA. 05 SQLCABC PIC S9(9) <comp> VALUE SQLCODE PIC S9(9) <comp>. 05 SQLERRM. 49 SQLERRML PIC S9(4) <comp>. 49 SQLERRMC PIC X(70). 05 SQLERRP PIC X(8). 05 SQLERRD OCCURS 6 TIMES PIC S9(9) <comp>. 05 SQLWARN. 10 SQLWARN0 PIC X(1). 10 SQLWARN1 PIC X(1). 10 SQLWARN2 PIC X(1). 10 SQLWARN3 PIC X(1). 10 SQLWARN4 PIC X(1). 134 Teradata Preprocessor2 for Embedded SQL Programmer Guide

135 Chapter 4: Writing Embedded SQL Applications in COBOL BIGINT Support 10 SQLWARN5 PIC X(1). 10 SQLWARN6 PIC X(1). 10 SQLWARN7 PIC X(1). 10 SQLWARN8 PIC X(1). 10 SQLWARN9 PIC X(1). 10 SQLWARNA PIC X(1). 05 SQLEXT PIC X(5). where <comp> is COMP-5 for MF COBOL and COMP for all other COBOL compilers. SQLCA is documented in SQL Reference: Stored Procedures and Embedded SQL. ANSI-Compatible Mode Communications Variables When writing COBOL programs for ANSI compatible mode, you must define a SQLCODE variable and may also define a SQLSTATE variable. If you define both variables, each contains valid error codes. The SQLSTATE and SQLCODE variables are documented in SQL Reference: Stored Procedures and Embedded SQL. BIGINT Support Beginning with PP2 9.2 and Teradata Database V2R6.2, there is increased byte support for integer operations. The limit has increased from 4 bytes (32 bits) to 8 bytes (64 bits). You can specify a 64 bit integer wherever integers are defined. Large Decimal Support Beginning with PP2 9.2 and Teradata Database V2R6.2, there is support for an increase from 18 digit decimals to 31 digit decimals for mainframe systems and 38 digit decimals for network systems. The default remains 18 digits, allowing full compatibility with existing programs. To change the default, specify the preprocessor option DECIMAL(nn) or -dec nn. Valid values for network systems are: -dec(38) -dec(18) -dec(0) If you specify dec(0), the option is ignored and the default of 18 digits remains. Valid values for mainframe systems are: DECIMAL(31) DECIMAL(18) DECIMAL(0) Teradata Preprocessor2 for Embedded SQL Programmer Guide 135

136 Chapter 4: Writing Embedded SQL Applications in COBOL COBOL Coding Considerations If you specify DECIMAL (0), the option is ignored and the default of 18 digits remains. Example In this example, the employee number is specified as a larger binary integer, and the salary is specified as a larger decimal value: 01 EMPLOYEE-RECORD. 02 EMPNUM PIC S9(18) COMP. 02 SALARY PIC S9(29)V99 COMP-3. COBOL Coding Considerations Array Support Embedded SQL statements must appear in the PROCEDURE DIVISION of the COBOL program, except for the DECLARE and INCLUDE statements (which may appear in WORKING STORAGE or the PROCEDURE DIVISION). When you are using Teradata mode, the INCLUDE SQLCA statement must appear in the WORKING STORAGE SECTION and may appear only once. When you are using ANSI compatibility mode, you must declare a SQLCODE variable to receive codes. You may also declare a SQLSTATE variable. The DML Array feature improves application performance by allowing iterative requests to be grouped together into a single step, resulting in a decrease of the step-processing overhead per request. Only single INSERT statements and references to arrays of variables are supported. References to arrays of structures are not supported. To accommodate this feature, the EXEC SQL statement is modified to: EXEC SQL FOR (<countval) <sql statement string>; where: FOR indicates that this is an array statement <countval> is a user defined integer variable or literal integer constant that must be less than or equal to the smallest defined dimension in the list of arrays Note: Ensure that <countval> does not exceed the smallest defined dimension in the list of arrays. An error is generated if this condition is violated and countval is specified as a literal. At precompile time, no check is made when countval is specified as a variable. <sql statement string> is a character string containing a legal SQL statement with references to host variables Literal integer constants that are embedded in the SQL string are not iterated; they are propagated in every inserted row. The same host variable can be specified for two or more fields. Any given iteration will obtain the same value. 136 Teradata Preprocessor2 for Embedded SQL Programmer Guide

137 Chapter 4: Writing Embedded SQL Applications in COBOL COBOL Coding Considerations Example 01 EMPTBL. 05 EMPNUM PIC S9(8) DISPLAY OCCURS 6 TIMES. 01 MGRTBL. 05 MGRNUM PIC S9(8) COMP OCCURS 6 TIMES. EXEC SQL PREPARE INSSTMT FROM :STMT-STRING END-EXEC. EXEC SQL FOR 6 EXECUTE INSSTMT USING :EMPNUM, :MGRNUM END-EXEC. Embedded SQL Statement Format The format for SQL statements embedded into a COBOL program is: EXEC SQL embedded-sql-statement END-EXEC [.] Each of the SQL statements embedded into a COBOL application must begin with the SQL prefix EXEC SQL, which identifies the statement as an embedded SQL statement. The complete SQL prefix must appear on one line and no character other than blank may appear between EXEC and SQL. The remainder of the statement may appear on the same line or on the next and subsequent lines. In addition, each embedded SQL statement must end with the SQL terminator END-EXEC. Do not include a semicolon before the END-EXEC. A period at the end of the statement is optional. The period causes PP2 to include an ending period on the last statement generated for the SQL statement. This punctuation is not always acceptable, especially if the SQL statement is within the scope of an IF... THEN... ELSE construct. Subject to charset restrictions, SQL statements are case insensitive, except for host variable references. When dynamic SQL statement text is stored in a varchar host variable, the statement text cannot be longer than 64k. Caution: Comments For the EXEC SQL INCLUDE statement, PP2 has the restriction that no text -- not even punctuation marks, such as a period -- is allowed to follow the SQL terminator (END-EXEC). Comments placed in Teradata SQL statements follow normal COBOL rules. Continuation for SQL Statements Line continuation rules for a SQL statement are the same as COBOL continuation rules within EXEC SQL blocks. Teradata Preprocessor2 for Embedded SQL Programmer Guide 137

138 Chapter 4: Writing Embedded SQL Applications in COBOL COBOL Coding Considerations Dynamic SQL If a string constant is continued from one line to the next, the first non-blank character in the next line must be a string delimiter. COBOL does not conveniently support dynamic SQL. Generally, a PL/I or C subroutine should be written to handle dynamic requests, if possible. Dynamic requests can be performed in COBOL by following the procedure outlined below. 1 The application must supply the necessary SQLDA structures. A sample SQLDA takes the following form: 01 SQLDA. 05 SQLDAID PIC X(8) VALUE SQLDA. 05 SQLDABC PIC S9(9) <comp> VALUE SQLN PIC S9(4) <comp> VALUE SQLD PIC S9(4) <comp> VALUE SQLTYP-001 PIC S9(4) <comp> VALUE SQLLEN-001 PIC S9(4) <comp> VALUE SQLDAT-001 PIC 9(9) <comp>. 05 SQLIND-001 PIC 9(9) <comp>. 05 SQLNAM-001 PIC X(32). 05 SQLTYP-002 PIC S9(4) <comp> VALUE SQLLEN-002 PIC S9(4) <comp> VALUE SQLDAT-002 PIC 9(9) <comp>. 05 SQLIND-002 PIC 9(9) <comp>. 05 SQLNAM-002 PIC X(32). where <comp> is COMP-5 for MF COBOL and COMP for all other COBOL compilers. SQL Reference: Stored Procedures and Embedded SQL describes the SQLDA and its fields. 2 The SQLDAT field of the SQLDA must contain the address of the host variable where data is to be obtained (input) or returned (output). The SQLIND field of the SQLDA must contain the address of the host variable, if any, where the indicator value is to be placed. Initialize the SQLIND field to X 00 (LOW-VALUES) if you do not use it. The Teradata Database supplies a routine via CLIv2 for setting the address of a field in COBOL. DBCHSAD places the address of a specified variable into a specified field. This routine requires three parameters, a 4 byte field to contain the return code of the routine, a 4 byte field to store the address and the variable whose address is desired. An example using the above SQLDA takes the following form CALL DBCHSAD return-code, SQLDAT-001, host-var The precompiler generates the field SQL-RETCODE, which can be used to receive the return code, or the application can define a different field for the return code. Declare the field as a PIC S9(9) COMP field. This field contains a value of 0 or 2 upon return from DBCHSAD. A 0 indicates successful completion, while 2 indicates an incorrect number of parameters has been passed. 3 The string expression used for the PREPARE or EXECUTE IMMEDIATE statements must be a SQL string (that is a VARCHAR structure). 138 Teradata Preprocessor2 for Embedded SQL Programmer Guide

139 Chapter 4: Writing Embedded SQL Applications in COBOL COBOL Coding Considerations Including Code See SQL Reference: Fundamentals for additional information on SQL strings. See SQL Strings on page 139 and Host Variable Declaration on page 151 for information on declaring VARCHAR fields. Use the SQL INCLUDE statement to incorporate those host variable definitions or SQL statements to be used by PP2 that come from an external copy file. PP2 does not recognize the normal COBOL INCLUDE statement, which causes an error when necessary host variable declarations in an INCLUDE file are unavailable to PP2. You can use the SQL INCLUDE anywhere a COBOL INCLUDE statement is legal. Margins The default precompiler margins are 8 and 72. This is standard ANSI formatted COBOL, which provides the following: Columns 1-6 are available for sequence numbering Column 7 is used to indicate: Comments (*) String continuation (-) Debug statements (D) Page eject lines (/) Margin A begins in column 8 Margin B begins in column 12 The EXEC SQL prefix must start in or after column 12 SQL statements are coded in columns 12 through 72 The programmer also has the option of specifying margins beginning in column 1. This specification selects terminal formatting, a less-restrictive form available in the networkattached environment. The format used with the network depends on the compiler installed; check the preferences for your installation regarding the proper format. Paragraph Names If a COBOL statement normally could be preceded by a paragraph name, an embedded SQL statement at the same place also may be preceded by a paragraph name. Sequence Numbers The precompiler does not generate sequence numbers in source statements. SQL Strings Apply these rules when using SQL strings in COBOL: Teradata Preprocessor2 for Embedded SQL Programmer Guide 139

140 Chapter 4: Writing Embedded SQL Applications in COBOL COBOL Coding Considerations String Delimiters Define the variable used as a SQL string as a varying character type. See Host Variable Declaration on page 151 for information on declaring VARCHAR fields. Meet these requirements for the host variable: The following statements require level 49 fields to have valid COBOL field names other than FILLER: CHECKPOINT DATABASE SET CHARSET For LPI COBOL, if you do not declare a varying character host variable at level 01, you must name the first level 49 field other than FILLER for use with any SQL statement. The following statements allow level 49 fields to have either a valid COBOL field name or the keyword FILLER, except in the LPI COBOL case as stated above: EXECUTE IMMEDIATE LOGON PREPARE The APOST/QUOTE and APOSTSQL/QUOTESQL options control COBOL string recognition and generation. The default values for COBOL are APOST and APOSTSQL; the precompiler generates code appropriate to the option specified. For details, see Chapter 2: Connecting to the Database and Invoking PP2. USE this option TO indicate that native COBOL strings are APOST enclosed by apostrophes ( ). The precompiler encloses all strings recognized by COBOL in apostrophes. QUOTE delimited by quotation marks ( ). If requesting this option, specify the COBOL compiler option QUOTE. APOSTSQL and QUOTESQL affect SQL string delimiters and escape characters. USE this option APOSTSQL QUOTESQL TO indicate that apostrophes delimit the strings embedded in a SQL statement and that the escape character is a quotation mark. indicate that quotes delimit the strings embedded in a SQL statement and that the escape character is an apostrophe. 140 Teradata Preprocessor2 for Embedded SQL Programmer Guide

141 Chapter 4: Writing Embedded SQL Applications in COBOL COBOL Coding Considerations The APOSTSQL/QUOTESQL option controls multi-statement request delimiting. Delimited Identifiers and Character String Literals Teradata SQL for Teradata Database and later extends ANSI-compliant Unicode delimited identifiers and character string literals. This enables the Data Dictionary to function the same, whether or not Japanese character set support is enabled or not. Additionally, object names with multi-byte character sets can be shared between sessions that have non-japanese character sets. The Unicode delimited identifier is U&" ". The Unicode character string literal is U&' '. These new identifiers and literals are produced where ' 'XN and ' 'XC notation is used. For example, prior to Teradata Database , the syntax to represent a Kanji string was: ELECT * FROM ' 'XN; /* This hexadecimal string represents the Kanji1 string using the KANJIEUC_0U character set*/ For Teradata Database and later, the syntax is: SELECT * FROM U&"\FF34\FF21\FF22\FF11"; /* for post V2R Unicode Data Dictionary, the internal hex is based on UNICODE hex for object name */ In the above example, backslash (\) is the escape character. The default escape character depends on the session charset, but will be backslash (\) or yen sign for all supported character sets. The above SQL can also be written as: SELECT * FROM U&"$FF34$FF21$FF22$FF11" UESCAPE('$'); where $ is the escape character. APOSTSQL Example QUOTESQL Example User Defined Functions EXEC SQL DECLARE cursor CURSOR FOR SELECT * FROM table - WHERE COL1 = ABCD ; - UPDATE table one SET COL2 = ABCD END-EXEC EXEC SQL DECLARE cursor CURSOR FOR SELECT * FROM table - WHERE COL1 = ABCD ; - UPDATE table one SET COL2 = ABCD END-EXEC You can use the User Defined Function (UDF) in the embedded SQL statements, but not CREATE or REPLACE FUNCTION in the PP2 applications. For further information see SQL Reference: Data Definition Statements. Teradata Preprocessor2 for Embedded SQL Programmer Guide 141

142 Chapter 4: Writing Embedded SQL Applications in COBOL Host Variables Multisession Programming Considerations Special Considerations The specific SQL statements used for multiprogramming are documented in Multisession Asynchronous Programming in SQL Reference: Stored Procedures and Embedded SQL. PP2 treats both debugging lines and page eject lines as comments. Host Variables SQL statements use COBOL variables both for sending input values to the Teradata Database and for receiving output values from the Teradata Database. Variables used in this manner are called host variables. Host variables allow an application to use the same statement in an iterative fashion, obtaining results based on the value of the variable when the statement is executed. Host variables are documented in SQL Reference: Stored Procedures and Embedded SQL. Using COBOL Structures as Output Host Variables You can use COBOL host structures to receive data from the Teradata Database. This capability is useful when you are retrieving many columns. A host structure is valid to receive data only if all fields of that structure are defined to PP2. This does not preclude the use of individual fields of a structure, as long as the fields follow proper PP2 definition rules. Using COBOL Structures as Input Host Variables The following rules apply to using host variables in a COBOL program: Use of the keyword FILLER in a structure other than in a varying character field invalidates the structure as a whole. However, you may still reference valid individual fields. Use host structures to insert data into Teradata Database managed databases. This feature is useful for an INSERT with a VALUES clause that inserts multiple fields into a table using host variables. A host structure as an entity is valid for input only if all fields of the structure are validly defined. Because all of the fields of the structure are passed to the Teradata Database, the application must ensure that the structure elements match the number of elements specified in the SQL statement. Do not use a structure reference as an input entity in a WHERE clause or any place where a single field is expected. 142 Teradata Preprocessor2 for Embedded SQL Programmer Guide

143 Chapter 4: Writing Embedded SQL Applications in COBOL Host Variables Example Overview You can use individual fields of a structure for input as long as the fields are defined following PP2 rules. PP2 supports structured host variables to a depth of two, following the same rules as SQL/ DS and DB2. Qualified references in embedded SQL statements are expressed using PL/I syntax; that is, with a dot separating the levels of qualification. A typical host structure definition takes the following form: 01 STRUCTURE1. 02 FIELD1 PIC X(20). 02 FIELD2 PIC S9(9) <comp>. 02 FIELD3 PIC X(6). 02 FIELD4 PIC S9(11)V99 COMP-3. where <comp> is COMP-5 for MF COBOL and COMP for all other COBOL compilers. This is one of several ways to declare a structure. You may follow other forms as long as they are allowed. See Host Variable Declaration on page 151. The structure level can go deeper than the two levels shown, but the items, if individually referenced, must be uniquely identifiable with a qualification depth of no more than two. Examples of referencing a structure for output based on the above structure follow. Assume the following table resides on a Teradata Database: CREATE TABLE TABLE1, NO FALLBACK, NO BEFORE JOURNAL, NO AFTER JOURNAL (FIELD1 CHAR(20), FIELD2 INTEGER, FIELD3 CHAR(6), FIELD4 DECIMAL(13,2)) UNIQUE PRIMARY INDEX (FIELD1) Example: Single Row SELECT EXEC SQL END-EXEC Example: Multiple Row SELECT EXEC SQL END-EXEC EXEC SQL OPEN C1 END-EXEC SELECT * INTO :STRUCTURE1 FROM TABLE1 WHERE FIELD3 = ABCDEF DECLARE C1 CURSOR FOR SELECT * FROM TABLE1 Teradata Preprocessor2 for Embedded SQL Programmer Guide 143

144 Chapter 4: Writing Embedded SQL Applications in COBOL Host Variables EXEC SQL EXEC SQL END-EXEC FETCH C1 INTO :STRUCTURE1 (loop for FETCH) END-EXEC CLOSE C1 Example: Single Row SELECT That Returns Only Some Columns EXEC SQL END-EXEC SELECT FIELD1, FIELD3 INTO :FIELD1, :FIELD3 FROM TABLE1 WHERE FIELD2 = 99 Example: Single Row SELECT Using Qualified Variable References EXEC SQL END-EXEC SELECT FIELD1, FIELD3 INTO :STRUCTURE1.FIELD1, :STRUCTURE1.FIELD3 FROM TABLE1 WHERE FIELD2 = 99 Example: Single Row INSERT Using a Structure for Field Values Caution: EXEC SQL END-EXEC INSERT INTO TABLE1 VALUES (:STRUCTURE1) The field in the table would receive the following assignments: TABLE1.FIELD1 <- FIELD1 of STRUCTURE1 TABLE1.FIELD2 <- FIELD2 of STRUCTURE1 TABLE1.FIELD3 <- FIELD3 of STRUCTURE1 TABLE1.FIELD4 <- FIELD4 of STRUCTURE1 The precompiler uses the elementary items as sending/receiving variables whenever you use a host structure name. If you had defined the above structure as: 01 STRUCTURE1. 02 FIELD1 PIC X(20). 02 FIELD2 PIC S9(9) <comp>. 02 FIELD3. 03 FIELD3A PIC X(2). 03 FIELD3B PIC X(2). 03 FIELD3C PIC X(2). 02 FIELD4 PIC S9(11)V99 COMP-3. where <comp> is COMP-5 for MF COBOL and COMP for all other COBOL compilers) and had specified the following single row SELECT statement: 144 Teradata Preprocessor2 for Embedded SQL Programmer Guide

145 Chapter 4: Writing Embedded SQL Applications in COBOL Requirements for Host Variables EXEC SQL SELECT * INTO :STRUCTURE1 FROM TABLE1 WHERE FIELD3 = ABCDEF END-EXEC the precompiler would generate code such that COBOL would attempt these assignments: TABLE1.FIELD1 -> FIELD1 of STRUCTURE1 TABLE1.FIELD2 -> FIELD2 of STRUCTURE1 TABLE1.FIELD3 -> FIELD3A of STRUCTURE1 TABLE1.FIELD4 -> FIELD3B of STRUCTURE1 Data moved into FIELD3A is truncated, while moving data into FIELD3B causes an error. Requirements for Host Variables COBOL and Host Variables This section lists the requirements and limits for using host variables in a COBOL program. You can use any valid COBOL host variable in a SQL statement. However, this does not mean that you can use all variables. Host variables must meet certain requirements before PP2 can accept them as usable in SQL statements. See Host Variable Declaration on page 151. Define host variables outside a structure at level 01 or 77. Host variables within a structure may be level 02 through 48. Level 49 is reserved for varying character fields. Level 66 and 88 items are ignored. You can use any valid COBOL variable name as a host variable name, including names with embedded hyphens. Precede with a colon all host variable names that begin with a number when you use them for input in instances where the Teradata Database expects a numeric constant. The USAGE IS DISPLAY clause is accepted only for a host variable of character type (PIC X(n)). The following clauses invalidate a host variable definition for use in an embedded SQL statement: BLANK WHEN ZERO JUSTIFIED SIGN Host variables which are not SQL strings are used only to represent data values. They cannot be used to represent database, table, view, macro or column names. Declare host variables either in the WORKING STORAGE SECTION or the LINKAGE SECTION of the COBOL program. Teradata Preprocessor2 for Embedded SQL Programmer Guide 145

146 Chapter 4: Writing Embedded SQL Applications in COBOL Requirements for Host Variables SQL and Host Variables Variables declared elsewhere are not valid. BEGIN DECLARE and END DECLARE are documented in SQL Reference: Stored Procedures and Embedded SQL. You must code a SQL string as a varying character field. If you are using the SQL string as the database name variable for a SQL DATABASE statement, or as the checkpoint label variable for a SQL CHECKPOINT statement, you must name the level 49 fields, not refer to them as FILLER. For LPI COBOL, name the first level 49 field if the varying character field is defined within a structure. In all other cases, you can code the level 49 fields as FILLER. Use FILLER only where reference to the individual portions of the varying character field is not necessary. An OCCURS clause in the definition of a SQL string is valid only when a REDEFINES clause precedes the OCCURS clause. Restrictions on variable type do not apply. The REDEFINES and the OCCURS clause can appear anywhere in the SQL string. The REDEFINES clause causes the remaining portion of the 49 level definition to be ignored. Individual level 49 fields (LENGTH1, LENREDEF, STRING1 in the following example) are not valid as separate entities in SQL requests. 01 WS-SQL-STRING. 49 LENGTH1 PIC S9(4) <comp>. 49 LENREDEF REDEFINES LENGTH1 PIC X OCCURS 2 TIMES. 49 STRING1 PIC X(5). 49 STRING2 PIC X(5). 49 STRING3 PIC X(5). 49 STRING4 PIC X(5). 49 STRING5 PIC X(5). 49 STRING6 PIC X(5). 49 NAME REDEFINES STRING6 PIC X OCCURS 5 TIMES. 49 FILLER PIC X(100). where <comp> is COMP-5 for MF COBOL and COMP for all other COBOL compilers. PP2 ignores the REDEFINES clause. You can reference the variable in a SQL statement, provided the definition for the variable is valid for PP2. In the example below, STRUCTURE1 and FIELD1 could not be used in a SQL request (FIELD1 has an invalid PP2 definition; STRUCTURE1 is invalid because a subfield in the structure is invalid). FIELD2 could be used in a SQL request. 01 STRUCTURE1. 02 FIELD1 PIC -(15) Teradata Preprocessor2 for Embedded SQL Programmer Guide

147 Chapter 4: Writing Embedded SQL Applications in COBOL Host Variable Values 02 FIELD2 REDEFINES FIELD1 PIC X(16). Code a varying character field as a structure consisting of a structure name followed by at least two level 49 entries. The first entry must conform to a signed or unsigned small integer type (PIC S9(4) <comp> or PIC 9(4) <comp>). The second and subsequent level 49 fields must be of character type (PIC X(n)). To declare a varying character field of maximum length 255, you might code the variable as: 01 VARCHAR1. 49 FILLER PIC S9(4) <comp> VALUE FILLER PIC X(255). or 01 VARCHAR1. 49 FILLER PIC S9(4) <comp> VALUE FILLER PIC X(100). 49 FILLER PIC X(100). 49 FILLER PIC X(55). where <comp> is COMP-5 for MF COBOL and COMP for all other COBOL compilers. The use of FILLER and multiple level 49 entries is an extension over DB2 provisions. All DB2 conforming declarations are valid for PP2. PP2 accepts the OCCURS clause only to define an indicator array. See Indicator Variables on page 155. The SYNCHRONIZED clause is ignored by PP2. The variable may be referenced in a SQL statement, provided the definition for the variable is valid to PP2. PP2 ignores the VALUE clause. You may reference the variable in a SQL statement, provided the definition for the variable is valid to PP2. PP2 Issues PP2 recognizes the COBOL reserved word FILLER as valid only for use in varying character fields. Host Variable Values The next sections detail variable assignments in server to host, and host to server environments. Teradata Preprocessor2 for Embedded SQL Programmer Guide 147

148 Chapter 4: Writing Embedded SQL Applications in COBOL Host Variable Values Server to Host Assignment Host variables are assigned during execution of a data retrieving statement (such as SELECT) or by a FETCH for cursors. The INTO clause identifies the host variables which are to receive the data. PP2 converts data from the server format to the appropriate format, provided they are compatible types. Conversion Rules Numeric values may not be returned to character or byte strings. The only exception to this is DATE. DATE fields may be returned to character fields (not byte) if the length of the field can hold the conversion type requested by the DATE option. See DATE(D E I J U) -d D E I J U on page 58. BYTE and VARBYTE strings may be returned to any valid host variable types. The byte string is moved one byte at a time for the length of the receiving variable. No data conversion is performed, and the application is responsible for handling the returned data. CHAR and VARCHAR strings are returned only to CHAR or VARCHAR type variables. DATE values may be returned to any numeric type (DECIMAL, NUMERIC, ZONED DECIMAL, INTEGER, FLOAT, REAL, DOUBLE PRECISION), as long as the value is representable in the receiving type. DATE in its natural format (such as a DESCRIBE for a dynamic request) is equivalent to INTEGER. DATE may also be returned to a CHAR or VARCHAR field, provided the length of the receiving field can hold the format requested. The character variable must be at least length 8 or 10, depending on the DATE PP2 option, to receive the date in any of the allowable formats. DECIMAL values may be returned to any numeric type (DECIMAL, NUMERIC, ZONED DECIMAL, INTEGER, SMALLINT, BYTEINT, FLOAT, REAL, DOUBLE PRECISION), as long as the value is representable in the receiving type. BYTEINT, SMALLINT and INTEGER values may be returned to any numeric type (DECIMAL, NUMERIC, ZONED DECIMAL, INTEGER, SMALLINT, BYTEINT, FLOAT, REAL, DOUBLE PRECISION), as long as the value is representable in the receiving type. FLOAT values may be returned to any numeric type (DECIMAL, NUMERIC, ZONED DECIMAL, INTEGER, SMALLINT, BYTEINT, FLOAT, REAL, DOUBLE PRECISION), as long as the value is representable in the receiving type. The Teradata RDBMS FLOAT type is equivalent to a DOUBLE PRECISION FLOAT. PP2 recognizes both SINGLE and DOUBLE PRECISION FLOAT host variable types. Fractional portions of the value may be lost in conversion to a type other than DOUBLE PRECISION FLOAT. GRAPHIC and VARGRAPHIC strings may only be returned to GRAPHIC or VARGRAPHIC type variables. 148 Teradata Preprocessor2 for Embedded SQL Programmer Guide

149 Chapter 4: Writing Embedded SQL Applications in COBOL Host Variable Values Byte String Assignment Byte data is assigned to the host variable byte by byte. PP2 does not perform any conversion, leaving the application responsible for processing the value. IF the value is Shorter than the receiving field THEN the field is NULL (X 00 ) filled Longer than the receiving field the data is truncated SQLWARN1 in the SQLCA is set to W the indicator variable, if present, is set to the length of the returned data. The same length as the field the data is moved with no exception conditions. Character String Assignment Character string data is assigned to a host variable one character at a time. IF the value is Shorter than the receiving field THEN the field is blank filled. Longer than the receiving field the data is truncated. SQLWARN1 in the SQLCA is set to W. the indicator variable, if present, is set to the length of the returned data. SQLCODE is set to +902 (ANSI mode only). SQLSTATE is set to (ANSI mode only). The same length as the field the data is moved with no exception conditions. If TRANSACT is set for ANSI, then truncation of any nonblank and nonzero character produces a warning SQLCODE (+902) and SQLSTATE (01004). Numeric Value Assignment Numeric values are converted as appropriate for the receiving field (DECIMAL, NUMERIC, ZONED DECIMAL, FLOAT, REAL, DOUBLE PRECISION, BYTEINT, SMALLINT, INTEGER), provided the value may assume the requested format without losing leading digits. The SQLCODE field in the SQLCA is set to -304 if the host variable cannot contain the returned data. Date Assignment Date values may be returned into any valid numeric host variable (DECIMAL, NUMERIC, ZONED DECIMAL, FLOAT, REAL, DOUBLE PRECISION, INTEGER), following the same Teradata Preprocessor2 for Embedded SQL Programmer Guide 149

150 Chapter 4: Writing Embedded SQL Applications in COBOL Host Variable Values rules as a numeric assignment except when DATEFORM=ANSIDATE is set. Date values also may be returned into a character string variable. The host variable length depends on the DATE option set or defaulted. For details, see Chapter 2: Connecting to the Database and Invoking PP2. IF this format is requested Teradata Database Anything else The receiving variable must be at least 8 bytes long. Surplus bytes are set to blanks. 10 bytes long. Surplus bytes are set to blanks. Host to Server Assignment The SQLCODE in the SQLCA is set to -304 if the receiving field is too short. For ANSIDATE format, the receiving character variable must be at least 10 bytes long. Bytes in excess of 10 are set to blanks. Host variables can be used to pass column values to the server via the VALUES clause of the INSERT statement or the SET clause of the UPDATE statement. PP2 does not perform any conversion before sending the data to the server, so the application must ensure that the host variable may pass the value to the server for conversion. Assignment Rules SQL Reference: Stored Procedures and Embedded SQL describes the rules for assigning Teradata Database variables. Graphic Literals for Multibyte Characters The precompiler recognizes GRAPHIC-type literals in the COBOLII language in the following form: G <###> WHERE this character G Means this The string is graphic data. Single byte character. < Shift-Out meta character. > Shift-In meta character. ### Quoted multibyte character string in a valid Kanji EBCDIC ideogram. 150 Teradata Preprocessor2 for Embedded SQL Programmer Guide

151 Chapter 4: Writing Embedded SQL Applications in COBOL Host Variable Declaration For more information on graphic literals (or constants), see SQL Reference: Data Types and Literals. Host Variable Declaration PP2 does not recognize every possible COBOL variable declaration as valid for use in a SQL statement. The table that follows lists the equivalent COBOL definitions for Teradata Database data types. For those types which have no direct COBOL declaration, runtime processing allows you to return data to one of the other types. Level numbers are only examples. The COBOL repetition factor syntax is used for the picture specification characters in the examples (that is, X(m), 9(x)), but the actual number of characters also may be used (for example, X(3) = XXX). With COBOL, host variables may start with a numeric, but when referenced, require a colon in front. This provides a distinction between a numeric constant and the host variable name. Table 9: COBOL Definitions for Teradata Database Data Types Data Type Declaration Compiler(s) Notes (following table) BYTE No direct equivalent All 1 VARBYTE No direct equivalent All 1 CHAR(m) 01 identifier PIC X(m). All 2 VARCHAR(m) 01 identifier 49 identifier PIC [S]9(4). [USAGE [IS]] COMP[UTATIONAL]. 49 identifier PIC X(m) 01 identifier 49 identifier PIC [S]9(4) [USAGE [IS]] COMP[UTATIONAL] identifier PIC X(m) 01 identifier 49 identifier PIC [S]9(4). [USAGE [IS]] COMP[UTATIONAL] identifier PIC X(m) 01 identifier 49 identifier PIC [S]9(4) BINARY. 49 identifier PIC X(m) All except MF1 and MF2 2, 3, 11 All but MF1, MF2, and LPI MF1 and MF2 All except MF1 and MF2 TIME 01 identifier PIC X(m) 15 TIMESTAMP 01 identifier PIC X(m) 16 Teradata Preprocessor2 for Embedded SQL Programmer Guide 151

152 Chapter 4: Writing Embedded SQL Applications in COBOL Host Variable Declaration Table 9: COBOL Definitions for Teradata Database Data Types (continued) Data Type Declaration Compiler(s) Notes (following table) DATE DECIMAL(m,n) NUMERIC(m,n) 01 identifier PIC S9(m) [USAGE [IS]] COMP[UTATIONAL]. 01 identifier PIC S9(m) [USAGE [IS]] COMP[UTATIONAL] identifier PIC S9(m) [USAGE [IS]] COMP[UTATIONAL] identifier PIC S9(m) [USAGE [IS]] BINARY. 01 identifier PIC S9(m-n)V9(n) [USAGE [IS]] COMP[UTATIONAL] identifier PIC S9(m-n)V9(n) [USAGE [IS]] PACKED-DECIMAL. 01 identifier PIC S9(m-n)V9(n) [USAGE [IS]] COMP[UTATIONAL] identifier PIC S9(m-n)V9(n) [USAGE [IS]] PACKED-DECIMAL. All 4, 5 All except LPI MF1 and MF2 All All 2, 6 All All 2,6 All FLOAT* 01 identifier [USAGE [IS]] COMP[UTATIONAL]-1. All except MF1 and MF2 7 REAL* DOUBLE PRECISION* 01 identifier [USAGE [IS]] COMP[UTATIONAL] identifier [USAGE [IS]] COMP[UTATIONAL]-1. All except MF1 and MF2 7 All except MF1 and MF2 7 FLOAT** 01 identifier [USAGE [IS]] COMP[UTATIONAL]-2. All except MF1 and MF2 7 REAL** DOUBLE PRECISION** BYTEINT 01 identifier [USAGE [IS]] COMP[UTATIONAL] identifier [USAGE [IS]] COMP[UTATIONAL] identifier PIC S9(m)[v9(n)] [USAGE [IS]] COMP[UTATIONAL]. 01 identifier PIC S9(m)[v9(n)] [USAGE [IS]] COMP[UTATIONAL] identifier PIC S9(m)[v9(n)] [USAGE [IS]] COMP[UTATIONAL] identifier PIC S9(m)[v9(n)] [USAGE [IS]] BINARY. All except MF1 and MF2 7 All except MF1 and MF2 7 All 8 All except LPI MF1 and MF2 All 152 Teradata Preprocessor2 for Embedded SQL Programmer Guide

153 Chapter 4: Writing Embedded SQL Applications in COBOL Host Variable Declaration Table 9: COBOL Definitions for Teradata Database Data Types (continued) Data Type Declaration Compiler(s) Notes (following table) SMALLINT INTEGER GRAPHIC(m) VARGRAPHIC (m) ZONED DECIMAL (m,n) * single precision ** double precision 01 identifier PIC S9(m)[v9(n)] [USAGE [IS]] COMP[UTATIONAL]. 01 identifier PIC S9(m)[v9(n)] [USAGE [IS]] COMP[UTATIONAL] identifier PIC S9(m)[v9(n)] [USAGE [IS]] COMP[UTATIONAL] identifier PIC S9(m)[v9(n)] [USAGE [IS]] BINARY. 01 identifier PIC S9(m)[v9(n)] [USAGE [IS]] COMP[UTATIONAL]. 01 identifier PIC S9(m)[v9(n)] [USAGE [IS]] COMP[UTATIONAL] identifier PIC S9(m)[v9(n)] [USAGE [IS]] COMP[UTATIONAL] identifier PIC S9(m)[v9(n)] [USAGE [IS]] BINARY. 01 identifier PIC G(m) [USAGE [IS] ] DISPLAY-1 01 identifier. 49 identifier PIC S9(4) <comp> 49 identifier PIC G(m) [USAGE [IS] ] DISPLAY-1 01 identifier PIC S9(m-n)V9(n) [USAGE [IS]] DISPLAY 01 identifier PIC S9(m-n)V9(n) [USAGE [IS]] DISPLAY SIGN LEADING 01 identifier PIC S9(m-n)V9(n) [USAGE [IS]] DISPLAY SIGN TRAILING 01 identifier PIC S9(m-n)V9(n) [USAGE [IS]] DISPLAY SIGN LEADING SEPARATE 01 identifier PIC S9(m-n) V9(n) [USAGE [IS]] DISPLAY SIGN TRAILING SEPARATE All 9 All except LPI MF1 and MF2 All All 10 All except LPI MF1 and MF2 All All 12 All 12, 13 All 14 All All All All Teradata Preprocessor2 for Embedded SQL Programmer Guide 153

154 Chapter 4: Writing Embedded SQL Applications in COBOL Host Variable Declaration Note: 1) Data may be returned to any valid host variable, although PP2 performs no data conversion. 2) The integer m must be positive. 3) Multiple PIC X(m) fields may be declared following the COMP field; COMP field should be set to the length used, not to exceed the total length of the PIC X fields. Level 49 identifiers may be coded as FILLER. 4) For MF1, the integer m must be positive such that 7 m 9. Otherwise, the integer m must be positive such that 5 m 9. 5) The Teradata Database normally returns a DATE type field as an integer. It is possible to return the value in character string format, as long as the length of the receiving field is sufficient. The DATEFORM=ANSIDATE format returns the DATE type field as CHAR (10). 6) Integer n must be positive; if n is zero, the V9(n) portion may be omitted. 7) A PICTURE clause may be included in the definition. PP2 ignores the PICTURE clause. 8) m and n are positive integers such that 1 (m+n) 2. The value is treated as BYTEINT without scalar for MF1 and SMALLINT without scalar for all other COBOL compilers. 9) m and n are positive integers such that 3 (m+n) 4. The value is treated as SMALLINT without scalar. For COBOL II applications that must assign a value greater than 9999 to a SMALL INTEGER, PP2 provides an assembler routine, PPRMVHW, to move the value. The routine expects two parameters as input: The field to contain the value and an integer field which contains the value to assign. As an example, 77 Field1 PIC S9(4) COMP. 77 FIELD2 PIC S9(9) COMP VALUE CALL PPRMVHW USING FIELD1, FIELD2. FIELD1 receives the value upon return from PPRMVHW. 10) For MF1, the integer m must be positive such that 7 m 9. Otherwise, the integer m must be positive such that 5 m 9. The value is treated as INTEGER without scalar. 154 Teradata Preprocessor2 for Embedded SQL Programmer Guide

155 Chapter 4: Writing Embedded SQL Applications in COBOL Indicator Variables 11 ) For LPI, the first level 49 field (length subfield) must be named if the varying character host variable is defined within a structure. 12) The integer m is the number of graphic characters (not bytes) and must be positive. If m is not specified, a default of GRAPHIC(1) is used. 13) Multiple PIC G(m) fields may be declared following the COMP field; the COMP field should be set to the length used, not to exceed the total length of the PIC G(m) fields. Level 49 identifiers may be coded as FILLER 14) The integers m and n must be positive, and m must be greater than n. This is a COBOL specific host data type, described here for documentation purposes only. If n is 0, you may omit the V9(n) portion. 15) For TIME, the length of the char identifier should be ) For TIMESTAMP, the length of the char identifier should be 35. Indicator Variables Indicator variables can be used with main variables intended for I/O, although certain indicator variables cannot be used for input (for example, in a WHERE clause). PP2 uses indicator variables to show nullness of a field sent to or returned by the Teradata Database, as well as truncation of a character or byte string when placed into the corresponding main variable. Indicator variables are documented in SQL Reference: Stored Procedures and Embedded SQL. Rules for Indicator Variables An indicator variable containing A negative number (most commonly -1) Zero A positive number Specifies to the precompiler that the associated input main variable is to be treated as a null. Alternatively, it means the Teradata Database returned a null for the associated column. precompiler that the associated input main variable is nonnull or that a non-null value was successfully returned with no exception conditions applied. application that truncation has occurred when returning a character or byte string to the associated main variable. This value represents the original length of the string before truncation. An indicator variable is defined as a 2 byte integer (smallint) or by a 4 digit signed zoned decimal. Teradata Preprocessor2 for Embedded SQL Programmer Guide 155

156 Chapter 4: Writing Embedded SQL Applications in COBOL Indicator Variables In COBOL, the smallint form is declared as: PIC S9(n) <comp> where the value for n is 3 or 4 and <comp> is COMP-5 for MF COBOL and COMP for all other COBOL compilers. The zoned decimal form is declared as: PIC S9(4) <zoned decimal type> where <zoned decimal type> is DISPLAY [SIGN {LEADING TRAILING} [SEPARATE]] Indicator Variables and Input Indicator variables are used when the application requires the Teradata Database to set a column value to null, such as when executing an INSERT or UPDATE statement. Indicator variables can be used within a WHERE clause with host variables to indicate a null. A negative value indicates the value in the associated main variable is to be ignored and PP2 is to send a null to the Teradata Database for the column. A zero or positive value specifies the host variable value is to be sent to the Teradata Database as the column value. EXEC SQL INSERT table1 VALUES (:hostvar1 :indvar1) END-EXEC EXEC SQL UPDATE table1 SET col1 = :hostvar1 :indvar1 WHERE col1 = :hostvar2 END-EXEC Indicator Variables and Output Indicator variables may be associated with the output main variables used in the INTO clause of a data returning statement or cursor FETCH statement. IF the Teradata Database returns a Null for a column and no indicator variable exists Negative value Positive value THEN the SQLCODE in the SQLCA is set to -305 and the value of the receiving main variable remains unchanged. the field was returned to the main variable with no exception conditions. the returned byte or character string was truncated. EXEC SQL SELECT col1 INTO :hostvar1 :indvar1 FROM table1 WHERE col1 = :hostvar2 156 Teradata Preprocessor2 for Embedded SQL Programmer Guide

157 Chapter 4: Writing Embedded SQL Applications in COBOL Indicator Variables END-EXEC EXEC SQL FETCH cursor1 INTO :hostvar1 :indvar1 END-EXEC Indicator Variables and Structures To facilitate use of indicator variables with host structures for output, PP2 accepts the definition of an array of small integers. Teradata Preprocessor2 for Embedded SQL Programmer Guide 157

158 Chapter 4: Writing Embedded SQL Applications in COBOL SQL Error Return ANSI Mode As an example, consider the following: 01 STRUCTURE1. 02 FIELD1 PIC X(20). 02 FIELD2 PIC S9(9) <comp>. 02 FIELD3 PIC X(6). 02 FIELD4 PIC S9(11)V99 COMP INDSTRUCT. 05 INDVAR OCCURS 4 TIMES PIC S9(4) <comp>. EXEC SQL SELECT * INTO :STRUCTURE1 :INDVAR FROM table1 WHERE col1 = :hostvar2 END-EXEC EXEC SQL FETCH cursor1 INTO :STRUCTURE1 :INDVAR END-EXEC Where <comp> is COMP-5 for MF COBOL and COMP for all other COBOL compilers. Note the use of INDVAR rather than INDSTRUCT to identify the indicator array. The variable name which contains the OCCURS clause is always used to identify the indicator array to the precompiler. In both examples, INDVAR(1) is associated with FIELD1, INDVAR(2) with FIELD2 and so on. The host variable is not required to have an associated indicator variable. The INDVAR array above could have had two elements rather than four. PP2, however, associates host variables and indicator variables one to one in order of occurrence. In these examples, FIELD1 and FIELD2 would have associated indicators, while FIELD3 and FIELD4 would have no indicators (assuming the array is defined with two elements). Indicator arrays may be associated only with a structure. Use of an array with individual elements results in a precompiler error. SQL Error Return ANSI Mode SQLCODE Variable Error conditions arising during processing of a SQL request made in ANSI mode are returned to the application via the SQLCODE or SQLSTATE variables. The SQLCODE variable contains a negative value when an error condition is reported. A positive value indicates that a warning has occurred. If no exception or error condition is encountered during processing, PP2 sets the SQLCODE variable to zero. 158 Teradata Preprocessor2 for Embedded SQL Programmer Guide

159 Chapter 4: Writing Embedded SQL Applications in COBOL SQL Error Return Teradata Mode SQLCODE is defined as: Definition: 01 SQLCODE PIC S9(9) <comp>; Where <comp> is COMP-5 for MF COBOL and COMP for all other COBOL compilers. Some exception conditions are not reflected in the SQLCODE. Data truncation on assignment of a value to a host variable is returned in SQLCODE(+902). The application should always check the SQLCODE variable upon return from processing an executable statement. Use the WHENEVER statement as one method to accomplish SQLCODE checking. You can define both a SQLCODE and a SQLSTATE variable for the same compilation unit. Both contain valid result codes. SQLSTATE Variable The SQLSTATE and SQLCODE variables are documented in SQL Reference: Data Manipulation Statements. The SQLSTATE variable is an ANSI standard, 5 character string value logically divided into a 2 character class and a 3 character subclass. SQLSTATE is defined as: Definition: 01 SQLSTATE PIC X(5); You can define both a SQLSTATE and a SQLCODE variable for the same compilation unit. Both contain valid result codes. Using PPRTEXT to Retrieve Return Codes PP2 provides a mechanism for retrieving the CLIv2, TDP, PP2 runtime or Teradata Database return codes; and the message text associated with the SQLCODE. When SQL Flagger warnings are found, only the first such warning for a particular statement is available through PPRTEXT. The application issues a call to PPRTEXT, passing four parameters as input to the routine. Typical PPRTEXT usage is shown in the Dynamic Statement Example on page 163. For additional information on PPRTEXT, see Messages. The four parameters are defined in SQL Error Return Teradata Mode, along with an example of how an application may call this routine. SQL Error Return Teradata Mode Error conditions arising during processing of a SQL request are returned to the application via the SQL Communications Area (SQLCA). Teradata Preprocessor2 for Embedded SQL Programmer Guide 159

160 Chapter 4: Writing Embedded SQL Applications in COBOL SQL Error Return Teradata Mode SQLCODE Field In particular, the SQLCODE field of the SQLCA contains a negative value when an error condition is reported. If no exception or error condition is encountered during processing, PP2 sets the SQLCODE field to zero. Some exception conditions, however, are not reflected in the SQLCODE. For example, data truncation on assignment of a value to a host variable or return of a null value are not reported directly. In such cases, the SQLWARN fields or any indicator variables associated with a host variable are set to indicate these conditions. The application should always check the SQLCODE field upon return from processing an executable statement. Use the WHENEVER statement, as illustrated below, as one method to accomplish SQLCODE checking. For details on the SQLCA fields, see SQL Reference: Stored Procedures and Embedded SQL. Using PPRTEXT to Retrieve Return Codes PP2 provides a mechanism for retrieving the CLIv2, TDP, PP2 runtime or Teradata Database return codes; and the message text associated with the SQLCODE. When SQL Flagger warnings are found, only the first such warning for a particular statement is available through PPRTEXT. The application issues a call to PPRTEXT, passing four parameters as input to the routine. Typical PPRTEXT usage is shown in the Dynamic Statement Example on page 163. For additional information on PPRTEXT, see Messages. The four parameters are defined below, along with an example of how an application may call this routine. In order, the four parameters PPRTEXT expects to receive are: 1 SQL-RDTRTCON precompiler-generated field set by the code generated at precompile time. This data should never be altered by the application; it has a declaration of: 01 SQL-RDTRTCON PIC S9(9) <comp>. Where <comp> is COMP-5 for MF COBOL and COMP for all other COBOL compilers. 2 ERROR-CODE application declares this field; the name is not important and the name shown is an example. PPRTEXT places the actual error code in this field and no initialization is necessary. Declare this field as: 01 ERROR-CODE PIC S9(9) <comp>. Where <comp> is COMP-5 for MF COBOL and COMP for all other COBOL compilers. 3 ERROR-MSG application declares this field; the name is not important and the name shown is just an example; PPRTEXT places the message text and the length of the text returned in this field and no initialization by the application is necessary. Declare this field as: 160 Teradata Preprocessor2 for Embedded SQL Programmer Guide

161 Chapter 4: Writing Embedded SQL Applications in COBOL Exception Conditions: WHENEVER 01 ERROR-MSG. 49 ERROR-LEN PIC S9(4) <comp>. 49 ERROR-TXT PIC X(255). Where <comp> is COMP-5 for MF COBOL and COMP for all other COBOL compilers. Note: The precompiler considers this field as varying-character. The ERROR-MSG field may be declared any size from one to 255. PPRTEXT returns at most the number of bytes in the message and/or the value given in the next field (MAX-LENGTH). Remaining bytes are not filled with spaces. The application may initialize the ERROR-TXT field to spaces prior to calling PPRTEXT. The application should use the ERROR-LEN field to determine the size of the actual text returned. 4 MAX-LENGTH application declares and initializes this field. The name is not important and the name given is just an example. PPRTEXT uses this field to determine the amount of text that may be placed in the text receiving field (ERROR-MSG, above); the value may be less than the actual size of the text field. If the message text exceeds this value, the text is truncated; if the value of this field exceeds the size of the receiving field, unpredictable results may occur. Declare this field as: 01 MAX-LENGTH PIC S9(4) <comp> Where <comp> is COMP-5 for MF COBOL and COMP for all other COBOL compilers. Note: The +255 is the maximum length that may returned based on the declaration of ERROR-MSG in this example. Code the call to PPRTEXT as: CALL PPRTEXT USING SQL-RDTRTCON, ERROR-CODE, ERROR-MSG, MAX-LENGTH Typical PPRTEXT usage is shown in the Dynamic Statement Example on page 163. Exception Conditions: WHENEVER The WHENEVER statement specifies the action to be taken when an exception condition occurs. Teradata Preprocessor2 for Embedded SQL Programmer Guide 161

162 Chapter 4: Writing Embedded SQL Applications in COBOL Exception Conditions: WHENEVER Exception Conditions Condition SQLWARNING Occurs when the SQLWARN0 field in the SQLCA is W or SQLCODE > 0 SQLERROR SQLCODE field in the SQLCA is < 0 NOTFOUND SQLCODE field in the SQLCA is +100 For any condition, one of four actions can be taken: With this action logic CONTINUE GOTO host-label PERFORM code CALL function call Processing continues to the next executable statement in the application program (that is, the exception condition is ignored). at the specified location. with the specified PERFORM statement. with a call to the specified CALL statement. WHENEVER Is Declarative The WHENEVER statement itself is not executable. PP2 generates code for each executable SQL statement based on the WHENEVER conditions in effect at the time of the call. If no WHENEVER statement is specified, the default condition is CONTINUE. An explicit WHENEVER statement affects all following SQL statements until another WHENEVER statement is encountered. This is a declarative; the WHENEVER statement is processed as it is sequenced in the source and not how it is executed at runtime. Rules for Using WHENEVER The WHENEVER statement must precede the SQL statement or statements for which the condition is to apply. When it is used, the host label object must be a section name or an unqualified paragraph name. When a PERFORM or CALL action is used, the PERFORM code object and the CALL function call must be such that PERFORM code or CALL function call is valid at every SQL statement to which that exception declaration applies. 162 Teradata Preprocessor2 for Embedded SQL Programmer Guide

163 Chapter 4: Writing Embedded SQL Applications in COBOL Dynamic Statement Example Dynamic Statement Example A sample COBOL program at the end of this section selects multiple rows from a table called EMPLOYEE, inserts a row into that table, then deletes the row just inserted. The example is intended to illustrate dynamic statements, using the three dynamic mechanisms that are available. In the example, SQL statements are coded directly into working storage. The application could also read the statements from a terminal, from a file, or by some other method. The SQLDA used for the delete statement has been partially assigned values in the WORKING STORAGE SECTION. SQLDA field assignments also may be made in the PROCEDURE DIVISION. The EMPLOYEE table is shown in Appendix C: Embedded SQL Examples. Note the following about the example: 1 SELECT The select statement is a data returning statement (potentially). Thus the statement is executed using a dynamic cursor. The PREPARE readies the statement in the SQL string SEL-STMT for execution. Notice that the program initializes the SqlDAID, SqlDABC and SqlN fields prior to executing the DESCRIBE request. SqlDABC is set by PP2 runtime, while SqlN indicates to the DESCRIBE the number of repeating element groups available to contain field information. The DESCRIBE returns information about the data coming back into the user-defined SQLDA (SQLDA). The OPEN statement specifies the host variable whose value will replace the question mark found in the select statement. The OPEN executes the select, returning an indication of success or failure to the application, as well as the number of rows which are returned if the statement is successfully executed. The FETCH loop returns the data into the specified host variables via the SQLDA structure until no more data is found (+100 in the SQLCODE) or an error occurs (negative SQLCODE). The CLOSE terminates the cursor and performs the cleanup related to the select statement. 2 INSERT The insert statement does not return data, nor does it require input host variables. This facility allows the statement to execute using an EXECUTE IMMEDIATE. 3 DELETE The delete statement does not return data, but requires an input host variable. This process requires the EXECUTE statement. The PREPARE readies the statement in the SQL string for execution. A DESCRIBE is not required for the delete since no data is returned. Teradata Preprocessor2 for Embedded SQL Programmer Guide 163

164 Chapter 4: Writing Embedded SQL Applications in COBOL Dynamic Statement Example The EXECUTE submits the delete to the Teradata Database for processing, passing the value of the host variable indicated in the SQLDA (DELSQLDA) for null. The success or failure of the transaction is reflected in the SQLCODE. The number of rows deleted, if any, appears in the first SQLERRD element. Note: The <comp> specification in the following example is COMP-5 for MF COBOL and COMP for all other COBOL compilers. IDENTIFICATION DIVISION. PROGRAM-ID. LAB8. AUTHOR. WHR. ENVIRONMENT DIVISION. DATA DIVISION. ******************************************************* WORKING-STORAGE SECTION ******************************************************* 01 LOGON-STRING. 49 FILLER PIC S9(4) <comp> VALUE FILLER PIC X(12) VALUE tdp/user,psw. 01 EMPLOYEE-RECORD. 02 EMPNUM PIC S9(9) <comp>. 02 MANNUM PIC S9(9) <comp>. 01 EMPOUT PIC -(15)9. 01 MANOUT PIC -(15)9. 01 EMPIND PIC S9(4) <comp>. 01 MANIND PIC S9(4) <comp>. 01 SQL-STATEMENT. 49 STMT-LEN PIC S9(4) <comp> VALUE FILLER PIC X(24) VALUE SELECT EMPLOYEE_NUMBER,. 49 FILLER PIC X(24) VALUE MANAGER_EMPLOYEE_NUMBER. 49 FILLER PIC X(14) VALUE FROM EMPLOYEE. 49 FILLER PIC X(25) VALUE WHERE EMPLOYEE_NUMBER =?. 01 INS-STATEMENT. 49 STMT-LEN PIC S9(4) <comp> VALUE FILLER PIC X(24) VALUE INSERT EMPLOYEE VALUES (. 49 FILLER PIC X(37) VALUE 2010,1003,2216,8201, JONES, FREDDY,. 49 FILLER PIC X(29) VALUE 20/06/14, 19/05/26,200000). 01 DEL-STATEMENT. 49 STMT-LEN PIC S9(4) <comp> VALUE FILLER PIC X(46) VALUE DELETE FROM EMPLOYEE WHERE EMPLOYEE_NUMBER =?. 01 SQLDA. 02 SQLDAID PIC X(8) VALUE SQLDA. 02 SQLDABC PIC S9(9) <comp> VALUE SQLN PIC S9(4) <comp> VALUE SQLD PIC S9(4) <comp>. 02 SQLVAR OCCURS 2 TIMES. 03 SQLTYPE PIC S9(4) <comp>. 03 SQLLEN PIC S9(4) <comp>. 03 SQLDATA PIC X(4). 164 Teradata Preprocessor2 for Embedded SQL Programmer Guide

165 Chapter 4: Writing Embedded SQL Applications in COBOL Dynamic Statement Example 03 SQLIND PIC X(4). 03 SQLNAME PIC X(32). 01 DELSQLDA. 02 DELDAID PIC X(8). 02 DELDABC PIC S9(9) <comp> VALUE DELN PIC S9(4) <comp> VALUE DELD PIC S9(4) <comp> VALUE DELVAR. 03 DELTYPE PIC S9(4) <comp> VALUE DELLEN PIC S9(4) <comp> VALUE DELDATA PIC X(4). 03 DELIND PIC X(4). 03 DELNAME PIC X(32). 01 ERROR-MSG. 49 FILLER PIC S9(4) <comp>. 49 ERROR-TXT PIC X(255). 01 ERROR-CODE PIC S9(9) <comp>. 01 MAX-LENGTH PIC S9(4) <comp> VALUE OUT-CODE PIC -(15)9. 01 REQUEST-TYPE PIC X(8). EXEC SQL INCLUDE SQLCA END-EXEC. EXEC SQL DECLARE EMPCUR CURSOR FOR EMPSTMT END-EXEC. ******************************************************* PROCEDURE DIVISION ******************************************************* DISPLAY EXECUTING SAMPLE.... DISPLAY. ******************************************************* ***** LOGON ******************************************************* MOVE LOGON TO REQUEST-TYPE. EXEC SQL LOGON :LOGON-STRING END-EXEC. PERFORM ERROR-CHECK. IF (SQLCODE NOT = 0) THEN GOBACK. ******************************************************* ***** PREPARE ******************************************************* MOVE PREPARE TO REQUEST-TYPE. EXEC SQL PREPARE EMPSTMT FROM :SQL-STATEMENT END-EXEC. PERFORM ERROR-CHECK. IF (SQLCODE < 0) THEN PERFORM LOGOFF. ******************************************************* ***** DESCRIBE ******************************************************* MOVE DESCRIBE TO REQUEST-TYPE. EXEC SQL DESCRIBE EMPSTMT INTO SQLDA END-EXEC. PERFORM ERROR-CHECK. Teradata Preprocessor2 for Embedded SQL Programmer Guide 165

166 Chapter 4: Writing Embedded SQL Applications in COBOL Dynamic Statement Example IF (SQLCODE = 0) THEN CALL DBCHSAD USING CALL DBCHSAD USING CALL DBCHSAD USING CALL DBCHSAD USING SQL-RETCODE, SQLDATA(1), EMPNUM SQL-RETCODE, SQLIND(1), EMPIND SQL-RETCODE, SQLDATA(2), MANNUM SQL-RETCODE, SQLIND(2), MANIND. IF (SQLCODE < 0) THEN PERFORM LOGOFF. ******************************************************* ***** OPEN ******************************************************* MOVE OPEN TO REQUEST-TYPE. MOVE 1001 TO EMPNUM. EXEC SQL OPEN EMPCUR USING :EMPNUM END-EXEC. PERFORM ERROR-CHECK. IF (SQLCODE = 0) THEN PERFORM FETCH-EMPCUR UNTIL SQLCODE NOT = 0. ******************************************************* ***** CLOSE ******************************************************* MOVE CLOSE TO REQUEST-TYPE. EXEC SQL CLOSE EMPCUR END-EXEC. PERFORM ERROR-CHECK. ******************************************************* ***** EXECUTE IMMEDIATE ******************************************************* MOVE EXECUTE TO REQUEST-TYPE. EXEC SQL EXECUTE IMMEDIATE :INS-STATEMENT END-EXEC. PERFORM ERROR-CHECK. ******************************************************* ***** PREPARE ******************************************************* MOVE PREPARE TO REQUEST-TYPE. EXEC SQL PREPARE DELSTMT FROM :DEL-STATEMENT END-EXEC. PERFORM ERROR-CHECK. IF (SQLCODE < 0) THEN PERFORM LOGOFF. ******************************************************* ***** EXECUTE 166 Teradata Preprocessor2 for Embedded SQL Programmer Guide

167 Chapter 4: Writing Embedded SQL Applications in COBOL Dynamic Statement Example ******************************************************* MOVE EXECUTE TO REQUEST-TYPE. CALL DBCHSAD USING SQL-RETCODE, DELDATA, EMPNUM. MOVE TO EMPNUM. MOVE LOW-VALUES TO DELIND. EXEC SQL EXECUTE DELSTMT USING DESCRIPTOR DELSQLDA END-EXEC. PERFORM ERROR-CHECK. ******************************************************* ***** LOGOFF ******************************************************* LOGOFF. MOVE LOGOFF TO REQUEST-TYPE. EXEC SQL LOGOFF END-EXEC. PERFORM ERROR-CHECK. GOBACK. ******************************************************* ***** FETCH ******************************************************* FETCH-EMPCUR. MOVE FETCH TO REQUEST-TYPE. EXEC SQL FETCH EMPCUR USING DESCRIPTOR SQLDA END-EXEC. PERFORM ERROR-CHECK. IF (SQLCODE = 0) THEN MOVE EMPNUM TO EMPOUT MOVE MANNUM TO MANOUT DISPLAY DISPLAY EMPLOYEE NUMBER :, EMPOUT DISPLAY MANAGER NUMBER :, MANOUT. ******************************************************* ***** ERROR CHECK ******************************************************* ERROR-CHECK. IF (SQLCODE NOT = 0) THEN MOVE SPACES TO ERROR-TXT CALL PPRTEXT USING SQL-RDTRTCON, ERROR-CODE, ERROR-MSG, MAX-LENGTH MOVE ERROR-CODE TO OUT-CODE DISPLAY DISPLAY ERROR/WARNING DETECTED IN, REQUEST-TYPE DISPLAY CODE:, OUT-CODE DISPLAY MSG :, ERROR-TXT. Teradata Preprocessor2 for Embedded SQL Programmer Guide 167

168 Chapter 4: Writing Embedded SQL Applications in COBOL Online Archive Online Archive Online archive is a process in which rows are archived from a table at the same time update, insert, or delete operations on the table are taking place. When an online archive is initiated on a table or a database, a log is created for the specified table or separate logs are created for each table in the specified database. The log, which contains all changes to the table, is saved as a part of the archive process. The changes recorded in the log can be applied to any changes to the table that occurred during the archive, such as a restore operation. Two new SQL statements start and stop the online archive process: LOGGING ONLINE ARCHIVE ON and LOGGING ONLINE ARCHIVE OFF. Example Example The following SQL statement initiates the online archive process for the database on a weekly basis: EXEC SQL LOGGING ONLINE ARCHIVE ON FOR WEEKLY; The following SQL statement stops the weekly online archive of the database: EXEC SQL LOGGING ONLINE ARCHIVE OFF FOR WEEKLY; 168 Teradata Preprocessor2 for Embedded SQL Programmer Guide

169 CHAPTER 5 Writing Embedded SQL Applications in PL/I This chapter discusses the PL/I-specific, language- dependent functions and features of PP2. Some non-language specific details are included for reference. PL/I Language Support PP2 supports the use of PL/I in these IBM mainframe environments: z/os z/vm CMS The PL/I statements generated by the precompiler, when run in one of these environments, are acceptable to the compilers for those environments. In addition, the PL/I statements generated by the precompiler conform to the ANSI PL/I 1976 standard, X Execute the PL/I precompiler by invoking module PPIMAIN. For details, see Chapter 2: Connecting to the Database and Invoking PP2. For linkage details, see Appendix B: Sample Application Linkage Procedure. PL/I Application Requirements Every PL/I program that requests Teradata Database services via embedded SQL statements requires a communications area. The different compatibility modes use incompatible data structures to do this. Program Status Information Each time a SQL statement is executed, it returns a code to communicate whether the statement executed successfully or not. You must define an area to receive these codes. When you precompile your applications under Teradata mode by setting the TRANSACT option to BTET, COMMIT or 2PC, define a communications area using the INCLUDE SQLCA statement. When you precompile your applications under ANSI compatible mode by defining TRANSACT as ANSI, use the SQLCODE and SQLSTATE variables to receive feedback information. Teradata Preprocessor2 for Embedded SQL Programmer Guide 169

170 Chapter 5: Writing Embedded SQL Applications in PL/I PL/I Language Support Do not mix program status communication areas between Teradata and ANSI compatible modes. Teradata Mode Communications Area Each application must include one SQLCA within the scope of all executable SQL statements. SQLCA is documented in the SQL Reference: Stored Procedures and Embedded SQL. Define the necessary SQLCA structure in one of two ways: Code an EXEC SQL INCLUDE SQLCA statement, which causes PP2 to generate the structure. Code the SQLCA directly into the program. The structure must be named SQLCA and must be unique. Generate an SQLCA structure for a PL/I application as follows: DCL 1 SQLCA, 2 SQLCAID CHAR(8) INIT( SQLCA ), 2 SQLCABC FIXED BIN(31) INIT(136), 2 SQLCODE FIXED BIN(31), 2 SQLERRM CHAR(70) VAR, 2 SQLERRP CHAR(8), 2 SQLERRD(6)FIXED BINARY(31), 2 SQLWARN, 3 SQLWARN0 CHAR(1), 3 SQLWARN1 CHAR(1), 3 SQLWARN2 CHAR(1), 3 SQLWARN3 CHAR(1), 3 SQLWARN4 CHAR(1), 3 SQLWARN5 CHAR(1), 3 SQLWARN6 CHAR(1), 3 SQLWARN7 CHAR(1), 3 SQLWARN8 CHAR(1), 3 SQLWARN9 CHAR(1), 3 SQLWARNA CHAR(1), 2 SQLEXT CHAR(5); ANSI-Compatible Mode Communications Variables When writing PL/I programs for ANSI-compatible mode, you must define a SQLCODE variable and may also define a SQLSTATE variable. If you define both variables, each contains valid error codes. The SQLSTATE and SQLCODE variables are documented in SQL Reference: Stored Procedures and Embedded SQL. 170 Teradata Preprocessor2 for Embedded SQL Programmer Guide

171 Chapter 5: Writing Embedded SQL Applications in PL/I BIGINT Support BIGINT Support Beginning with PP2 9.2 and Teradata Database V2R6.2, there is increased byte support for integer operations. The limit has increased from 4 bytes (32 bits) to 8 bytes (64 bits). Specify a 64 bit integer wherever integers are defined. Large Decimal Support Beginning with PP2 9.2 and Teradata Database V2R6.2, there is support for an increase from 18 digit decimals to 31 digit decimals for mainframe systems and 38 digit decimals for network systems. The default remains 18 digits, allowing full compatibility with existing programs. To change the default, specify the preprocessor option DECIMAL(nn) or -dec nn. Valid values for network systems are: -dec(38) -dec(18) -dec(0) If dec(0)is specified, the option is ignored and the default of 18 digits remains. Valid values for mainframe systems are: DECIMAL(31) DECIMAL(18) DECIMAL(0) If DECIMAL(0)is specified, the option is ignored and the default of 18 digits remains. Example In this example, the employee number is specified as a larger binary integer, and the salary is specified as a larger decimal value: DCL 01 EMPLOYEE_RECORD, 02 EMPNUM BIN FIXED(64), 02 SALARY DEC FIXED(29,2); PL/I Coding Considerations SQL statements can be enabled into an application program wherever a PL/I executable statement can be located. The format of an embedded SQL statement in a PL/I program is: EXEC SQL embedded-sql-statement; Teradata Preprocessor2 for Embedded SQL Programmer Guide 171

172 Chapter 5: Writing Embedded SQL Applications in PL/I PL/I Coding Considerations Array Support The DML Array feature improves application performance by allowing iterative requests to be grouped together into a single step, resulting in a decrease of the step-processing overhead per request. Only single INSERT statements and references to arrays of variables are supported. References to arrays of structures are not supported. To accommodate this feature, the EXEC SQL statement is modified to: EXEC SQL FOR (<countval) <sql statement string>; where: FOR indicates that this is an array statement <countval> is a user defined integer variable or literal integer constant that must be less than or equal to the smallest defined dimension in the list of arrays. Note: Ensure that <countval> does not exceed the smallest defined dimension in the list of arrays. An error is generated if this condition is violated and countval is specified as a literal. At precompile time, no check is made when countval is specified as a variable. <sql statement string> is a character string containing a legal SQL statement with references to host variables Literal integer constants that are embedded in the SQL string are not iterated; they are propagated in every inserted row. The same host variable can be specified for two or more fields. Any given iteration will obtain the same value. Example DCL EMPNUM(6) BIN FIXED(31); DCL MGRNUM (6) BIN FIXED(31); EXEC SQL PREPARE EXINSERT01 FROM INSERT INTO EMPLOYEE VALUES (?,?,?); EXEC SQL FOR 2 EXECUTE INSSTMT USING :EMPNUM, :MGRNUM; Embedded SQL Statement Format Each embedded SQL statement must begin with the SQL prefix EXEC SQL, which identifies the statement as an embedded SQL statement. The complete SQL prefix must appear on one line and is not case specific; no character other than blank may appear between EXEC and SQL.The remainder of the statement may appear on the same line or on the next and subsequent lines. Subject to charset restrictions, SQL statements are case insensitive, with lower case variable definitions and references identical to their upper case equivalents. Each embedded SQL statement must end with a semicolon, the SQL terminator. The embedded SQL statement text should not be over 64.K 172 Teradata Preprocessor2 for Embedded SQL Programmer Guide

173 Chapter 5: Writing Embedded SQL Applications in PL/I PL/I Coding Considerations Comments You can place PL/I comments within Teradata SQL statements wherever a blank is allowed, except between EXEC and SQL. For details on Teradata SQL statement comments, see SQL Reference: Fundamentals. Continuation for SQL Statements Dynamic SQL Including Code Line continuation rules for a SQL statement are the same as normal line continuation rules for PL/I, with these exceptions: You must specify the EXEC SQL prefix on one line. A SQL statement can be split wherever a blank can occur. If a line ends with a nonblank character in the right margin and the next line begins with a nonblank character in the left margin, the two lines are considered as one. Dynamic SQL is supported in PL/I, and the application must code the necessary SQL Descriptor Area (SQLDA) structures. For details on the SQLDA and its fields, see SQL Reference: Stored Procedures and Embedded SQL. Define the necessary SQLDA structure in one of two ways: Embed an EXEC SQL INCLUDE SQLDA statement into the application, which causes PP2 to generate the structure. Code the SQLDA directly into the program. Use any name for the structure. The generated SQLDA structure for a PL/I program is: DCL 1 SQLDA BASED(SQLDAPTR), 2 SQLDAID CHAR(8) INIT( SQLDA ), 2 SQLDABC FIXED BIN(31), 2 SQLN FIXED BIN(15), 2 SQLD FIXED BIN(15), 2 SQLVAR(SQLSIZE REFER(SQLN)), 3 SQLTYPE FIXED BIN(15), 3 SQLLEN FIXED BIN(15), 3 SQLDATA PTR, 3 SQLIND PTR, 3 SQLNAME CHAR(30) VAR; DCL SQLSIZE FIXED BIN(15); DCL SQLDAPTR PTR; Use the SQL INCLUDE statement to incorporate those host variable definitions or SQL statements to be used by the precompiler which come from an external copy file. The precompiler does not recognize the normal PL/I %include statement, which would cause an error if the necessary host variable declarations in an include file were unavailable to PP2. You can use the SQL INCLUDE anywhere a PL/I %include statement is legal. Teradata Preprocessor2 for Embedded SQL Programmer Guide 173

174 Chapter 5: Writing Embedded SQL Applications in PL/I PL/I Coding Considerations Macro Processor Run the PL/I macro processor prior to executing the PL/I precompiler. Margins Code SQL statements between columns 2 and 256, depending on the MARGINS option specified or defaulted. All code generated by the precompiler is contained in columns 2 through 72. The EXEC SQL prefix must start at or after the left margin, or the statement is not recognized by the precompiler. Sequence Numbers The precompiler does not generate sequence numbers in source statements. SQL Strings Define variables used for SQL strings as either fixed or varying character. See Host Variable Declaration on page 183. Statement Labels String Delimiters Specify statement labels for executable SQL statements following the rules of normal PL/I statements. The APOST/QUOTE and APOSTSQL/QUOTESQL options control PL/I string recognition and generation, and the precompiler generates code appropriate for PL/I string usage. The only values permitted for PL/I are APOST and APOSTSQL. USE this option TO indicate that APOST native PL/I strings are enclosed by apostrophes ( ). The precompiler encloses all strings recognized by PL/I in apostrophes. APOSTSQL SQL strings are delimited by apostrophes ( ). The escape character is quotation marks ( ). These options are described in Chapter 2: Connecting to the Database and Invoking PP2. The APOSTSQL option controls multistatement request delimiting. As an example, with APOST/APOSTSQL, the application is the following: EXEC SQL DECLARE cursor CURSOR FOR SELECT * FROM table WHERE COL1 = ABCD ; UPDATE table one SET COL2 = ABCD ; 174 Teradata Preprocessor2 for Embedded SQL Programmer Guide

175 Chapter 5: Writing Embedded SQL Applications in PL/I PL/I Coding Considerations Delimited Identifiers and Character String Literals Teradata SQL for Teradata Database and later extends ANSI-compliant Unicode delimited identifiers and character string literals. This enables the Data Dictionary to function the same, whether or not Japanese character set support is enabled or not. Additionally, object names with multi-byte character sets can be shared between sessions that have non-japanese character sets. The Unicode delimited identifier is U&" ". The Unicode character string literal is U&' '. These new identifiers and literals are produced where ' 'XN and ' 'XC notation is used. For example, prior to Teradata Database , the syntax to represent a Kanji string was: ELECT * FROM ' 'XN; /* This hexadecimal string represents the Kanji1 string using the KANJIEUC_0U character set*/ For Teradata Database and later, the syntax is: SELECT * FROM U&"\FF34\FF21\FF22\FF11"; /* for post V2R Unicode Data Dictionary, the internal hex is based on UNICODE hex for object name */ In the above example, backslash (\) is the escape character. The default escape character depends on the session charset, but will be backslash (\) or yen sign for all supported character sets. The above SQL can also be written as: SELECT * FROM U&"$FF34$FF21$FF22$FF11" UESCAPE('$'); where $ is the escape character. User Defined Functions You can use the User Defined Function (UDF) in the embedded SQL statements, but not CREATE or REPLACE FUNCTION in the PP2 applications. For further information, see SQL Reference: Data Definition Statements. Multi-Session Programming Considerations Special Considerations The specific SQL statements used for multiprogramming are documented in Multisession Asynchronous Programming in SQL Reference: Stored Procedures and Embedded SQL. The comments generated from the SQL statements usually contain a semicolon. The PL/I compiler returns message IEL0239, which you can ignore. The generated code in a PL/I declaration can contain the ADDR function of a varying character field. The PL/I compiler returns message IEL0872, which you can ignore. You can use PL/I string functions to complete SQL requests (such as PREPARE or EXECUTE IMMEDIATE), providing the results of the functions yield valid strings. Teradata Preprocessor2 for Embedded SQL Programmer Guide 175

176 Chapter 5: Writing Embedded SQL Applications in PL/I Host Variables Host Variables Host variables are PL/I variables in SQL statements that are used to send input values to and receive output values from the Teradata Database. Host variables allow an application to use the same statement in an iterative fashion, obtaining results based on the value of the variable when the statement is executed. Host variables are documented in SQL Reference: Stored Procedures and Embedded SQL. Using PL/I Structures as Output Host Variables PL/I host structures can receive data from the Teradata Database, a capability that is useful for retrieving many columns. A host structure is valid to receive data if and only if all fields of that structure are valid definitions to the precompiler. This does not preclude the use of the individual fields of the structure, as long as the field follows proper precompiler definition rules. Using PL/I Structures as Input Host Variables The following rules apply to using PL/I structures as input host variables. Use host structures to enter data into the Teradata Database. This is useful for an INSERT with a VALUES clause that inserts multiple fields into a table using host variables. A host structure as an entity is valid for input only if all fields of the structure are validly defined to the precompiler. Because all of the fields of the structure are passed to the Teradata Database, the application must ensure that the structure elements match the number of elements specified in the SQL statement. Do not use a structure reference as an input entity in a WHERE clause or any place where a single field is expected. You can use individual fields of a structure for input as long as the fields are defined following precompiler rules. PP2 supports structured host variables to a depth of two, following the same rules as SQL/ DS and DB2. Qualified references in embedded SQL statements are expressed using PL/I syntax; that is, with a dot separating the levels of qualification. A typical host structure definition takes the following form: DCL 01 STRUCTURE1, 02 FIELD1 CHAR(20), 02 FIELD2 FIXED BIN(31), 02 FIELD3 CHAR(6), 02 FIELD4 FIXED DEC(13,2); You may follow other forms as long as they are allowed. See Host Variable Declaration on page 183. The structure level may go deeper than the two levels shown, but the items, if individually referenced, must be uniquely identifiable with a qualification depth of no more than two. 176 Teradata Preprocessor2 for Embedded SQL Programmer Guide

177 Chapter 5: Writing Embedded SQL Applications in PL/I Host Variables Example Overview The examples in this section show referencing a structure for output. Assume the following table resides in a Teradata Database: CREATE TABLE TABLE1, NO FALLBACK, NO BEFORE JOURNAL, NO AFTER JOURNAL (FIELD1 CHAR(20), FIELD2 INTEGER, FIELD3 CHAR(6), FIELD4 DECIMAL(13,2)) UNIQUE PRIMARY INDEX (FIELD1) Example: Single Row SELECT EXEC SQL SELECT * INTO :STRUCTURE1 FROM TABLE1 WHERE FIELD3 = ABCDEF ; Example: Multiple Row SELECT EXEC SQL DECLARE C1 CURSOR FOR SELECT * FROM TABLE1; EXEC SQL OPEN C1; EXEC SQL FETCH C1 INTO :STRUCTURE1; (loop for FETCH) EXEC SQL CLOSE C1; Example: Single Row SELECT That Returns Only Some Columns EXEC SQL SELECT INTO FIELD1, FIELD3 :FIELD1, :FIELD3 FROM TABLE1 WHERE FIELD2 = 99; Example: Single Row SELECT Using Qualified Variable References EXEC SQL SELECT FIELD1, FIELD3 INTO :STRUCTURE1.FIELD1, :STRUCTURE1.FIELD3 FROM TABLE1 WHERE FIELD2 = 99; Teradata Preprocessor2 for Embedded SQL Programmer Guide 177

178 Chapter 5: Writing Embedded SQL Applications in PL/I Requirements for PL/I Host Variables Example: Single Row INSERT Using a Structure for Field Values Caution: EXEC SQL INSERT INTO TABLE1 VALUES (:STRUCTURE1) END-EXEC The fields in the table would receive the following assignments: TABLE1.FIELD1 <- FIELD1 of STRUCTURE1 TABLE1.FIELD2 <- FIELD2 of STRUCTURE1 TABLE1.FIELD3 <- FIELD3 of STRUCTURE1 TABLE1.FIELD4 <- FIELD4 of STRUCTURE1 The precompiler uses the elementary items as sending/receiving variables whenever a host structure name is used. If you define the above structure as: DCL 01 STRUCTURE1, 02 FIELD1 CHAR(20), 02 FIELD2 FIXED BIN(31), 02 FIELD3, 03 FIELD3A CHAR(2), 03 FIELD3B CHAR(2), 03 FIELD3C CHAR(2), 02 FIELD4 FIXED DEC(13,2); and specify the following single row SELECT statement: EXEC SQL SELECT * INTO :STRUCTURE1 FROM TABLE1 WHERE FIELD3 = ABCDEF ; the precompiler generates code such that PL/I attempts these assignments: TABLE1.FIELD1 -> FIELD1 of STRUCTURE1 TABLE1.FIELD2 -> FIELD2 of STRUCTURE1 TABLE1.FIELD3 -> FIELD3A of STRUCTURE1 TABLE1.FIELD4 -> FIELD3B of STRUCTURE1 Data moved into FIELD3A is truncated, and moving data into FIELD3B causes an error. Requirements for PL/I Host Variables Any valid PL/I host variable may be used in a SQL statement. This does not mean that all variables may be used, however. Host variables must meet certain requirements before PP2 can accept them as usable in SQL statements. See Host Variable Declaration on page 183. You can use any valid PL/I variable name as a host variable name, including names with embedded underscores ( _ ). Variable names must be unique within an application, even if they are within different blocks or procedures. PP2 does not recognize the PL/I scope concept rules and thus uses the first variable definition it encounters. A warning is issued when the same variable name is used more than once, if it cannot be qualified by a structure name. 178 Teradata Preprocessor2 for Embedded SQL Programmer Guide

179 Chapter 5: Writing Embedded SQL Applications in PL/I Requirements for PL/I Host Variables If a base level variable is declared and the name is also declared in a structure, but the referenced field is not qualified, the precompiler uses the base level variable declaration. With the following structure: DCL FIELD1 CHAR(6); DCL 01 STRUCTURE1, 02 FIELD1 CHAR(10), 02 FIELD2 CHAR(3); EXEC SQL SELECT FIELDA INTO :FIELD1 FROM TABLE1 WHERE FIELDB = ABC ; The precompiler uses the address and definition of FIELD1, length 6, to receive the data. Qualify the reference to FIELD1 in the SELECT to STRUCTURE1.FIELD1 if that is the intended field. This is the only instance where the duplicate field name is not considered ambiguous. The order of declaration makes no difference as to the variable used. Host variables which are not SQL strings can represent data values only. Do not use them to represent database, table, view, macro or column names. Specify host variable attributes in any order that is acceptable to the PL/I compiler. You can use legal PL/I abbreviations for attributes in the attribute specifications. A host variable reference used in a SQL statement must be within the scope of the variable. PP2 does not enforce this rule, as no scope checking is performed. At compilation/ execution time, however, if the reference is not within the scope, unexpected results may occur. Each host variable declaration must begin with the keyword DECLARE or DCL. The exceptions are structure definitions where subsequent variables are a part of the structure, or in specifying multiple variables with a single declare (that is, DCL VAR1 CHAR(6), VAR2 CHAR(3);). The only arrays recognized by PP2 are indicator arrays. Host variables may be AUTOMATIC, BASED, CONTROLLED or STATIC. PICTURE clauses are not considered valid definitions for variables used in SQL statements. Host variables having the same attributes may be declared using a list format (that is, DCL (VAR1,VAR2,VAR3) CHAR(6) ; ). The DEFINES clause is valid for a variable declaration only if: The variable is an 01 level The variable name is valid The variable definition is valid (that is, the PIC clause) The variable is not an array Teradata Preprocessor2 for Embedded SQL Programmer Guide 179

180 Chapter 5: Writing Embedded SQL Applications in PL/I Server to Host Assignment Server to Host Assignment Conversion Rules Host variables are assigned during execution of a data retrieving statement (such as SELECT) or by a FETCH for cursors. The INTO clause identifies the host variables to receive the data. PP2 converts data from the server to the appropriate format, provided they are compatible types. Numeric values may not be returned to character or byte strings. The only exception to this is DATE. DATE fields may be returned to character fields (not byte) if the length of the field can hold the conversion type requested by the precompiler DATE option. See DATE(D E I J U) -d D E I J U on page 58. BYTE and VARBYTE strings may be returned to any valid host variable types. The byte string is moved one byte at a time for the length of the receiving variable. No data conversion is performed and the application is responsible for handling the returned data. CHAR and VARCHAR strings may only be returned to CHAR or VARCHAR type variables. DATE values may be returned to any numeric type (DECIMAL, NUMERIC, INTEGER, FLOAT, REAL, DOUBLE PRECISION) as long as the value is representable in the receiving type. DATE in its natural format (such as a DESCRIBE for a dynamic request) is equivalent to INTEGER. DATE may also be returned to CHAR or VARCHAR fields, provided the length of the receiving field can hold the format requested. The character variable must be at least length 8 to receive the date in any of the allowable formats. DECIMAL values may be returned to any numeric type (DECIMAL, NUMERIC, INTEGER,SMALLINT, BYTEINT, FLOAT, REAL, DOUBLE PRECISION) as long as the value is representable in the receiving type. BYTEINT, SMALLINT and INTEGER values may be returned to any numeric type (DECIMAL, NUMERIC, INTEGER, SMALLINT, BYTEINT, FLOAT, REAL, DOUBLE PRECISION) as long as the value is representable in the receiving type. FLOAT values may be returned to any numeric type (DECIMAL,NUMERIC, INTEGER, SMALLINT, BYTEINT, FLOAT, REAL, DOUBLE PRECISION) as long as the value is representable in the receiving type. The Teradata SQL FLOAT, REAL and DOUBLE PRECISION types are equivalent to a DOUBLE PRECISION FLOAT. PP2 recognizes both SINGLE and DOUBLE PRECISION FLOAT host variable types. Fractional portions of the value may be lost in conversion to a type other than DOUBLE PRECISION FLOAT. GRAPHIC and VARGRAPHIC strings may only be returned to GRAPHIC or VARGRAPHIC type variables. 180 Teradata Preprocessor2 for Embedded SQL Programmer Guide

181 Chapter 5: Writing Embedded SQL Applications in PL/I Server to Host Assignment Byte String Assignment Byte data is assigned to a host variable byte by byte. PP2 does not perform any conversion, leaving the application responsible for processing the value. IF the value is Shorter than the receiving field THEN the data is X 00 filled. Longer than the receiving field 1 truncated. 2 SQLWARN1 in the SQLCA area is set to W. 3 the indicator variable, if present, is set to the actual length of the returned data. 4 ANSI SQLCODE =+902, SQLSTATE The same length moved with no exception conditions. Character String Assignment Character string data is assigned to a host variable one character at a time. IF the value is Shorter than the receiving field THEN the data is Blank filled. Longer than the receiving field 1 truncated. 2 SQLWARN1 in the SQLCA area is set to W. 3 the indicator variable, if present, is set to the length of the returned data. 4 in ANSI mode, SQLCODE is set to in ANSI mode, SQLSTATE is set to The same length moved with no exception conditions. String Truncation If compatibility is set to the ANSI option, then truncation of any nonblank and nonzero character produces a warning SQLCODE and SQLSTATE. Numeric Value Assignment Numeric values are converted as appropriate for the receiving field, provided the value may assume the requested format without losing leading digits. These types are valid: DECIMAL NUMERIC FLOAT REAL Teradata Preprocessor2 for Embedded SQL Programmer Guide 181

182 Chapter 5: Writing Embedded SQL Applications in PL/I Host to Server Assignment Date Assignment DOUBLE PRECISION BYTEINT SMALLINT INTEGER The SQLCODE field in the SQLCA is set to -304 if the host variable cannot contain the returned data. Date values can be returned into any valid numeric host variable, according to the same rules that apply to numeric assignments, except when DATEFORM=ANSIDATE is set. These types are valid: DECIMAL NUMERIC FLOAT REAL DOUBLE PRECISION INTEGER Date values can also be returned into a character string variable. The host variable length depends on the DATE option set or defaulted. See DATE(D E I J U) -d D E I J U on page 58. If Teradata Database format is requested or defaulted, the receiving variable must be at least 8 bytes long. Surplus bytes are set to blanks. All other formats require at least 10 bytes. Bytes in excess are set to blanks. The SQLCODE in the SQLCA is set to -304 if the receiving field is too short. For ANSIDATE format, the receiving character variable must be at least 10 bytes long. Bytes in excess of 10 are set to blanks. Host to Server Assignment Host variables can be used to pass column values to the server via the VALUES clause of the INSERT statement or the SET clause of the UPDATE statement. PP2 does not perform any conversion before sending the data to the server, so the application must ensure that the host variable may pass the value to the server for conversion. For rules for assigning the Teradata Database variables, see SQL Reference: Stored Procedures and Embedded SQL. 182 Teradata Preprocessor2 for Embedded SQL Programmer Guide

183 Chapter 5: Writing Embedded SQL Applications in PL/I Host Variable Declaration Graphic Literals for Multibyte Characters The precompiler recognizes GRAPHIC type literals in the PL/I language in the following form: < ### G>, where the letter G is the multi-byte character set Latin capital G, each (single quotation mark) is a single byte character, < is the Shift-Out metacharacter, > is the Shift-In metacharacter, and ### is the quoted MBC string of valid kanji EBCDIC ideograms. Note: For more information on graphic literals (or constants), see SQL Reference: Data Types and Literals. Host Variable Declaration PP2 does not recognize every possible PL/I variable declaration as valid for use in a SQL statement. The following table is a list of the equivalent PL/I definitions for the Teradata Database. For those types which have no direct PL/I declaration, the runtime processing allows returning data to one of the other types. BEGIN DECLARE and END DECLARE are documented in SQL Reference: Stored Procedures and Embedded SQL. Teradata Preprocessor2 for Embedded SQL Programmer Guide 183

184 Chapter 5: Writing Embedded SQL Applications in PL/I Host Variable Declaration Table 10: PL/I Definitions for Teradata Database Data Types Data Type Declaration Notes BYTE No direct equivalent Data can be returned to any valid host VARBYTE No direct equivalent variable, however PP2 does not convert the data. CHAR(m) DCL identifier CHAR[(m)]; The integer m must be positive. If m is not VARCHAR(m) DCL identifier CHAR[(m)] VAR[YING]; specified, a default of CHAR(1) is used. TIME DCL identifier CHAR[(m)] The length of the char identifier must be 15. TIMESTAMP DCL identifier CHAR [(m)] The length of the char identifier must be 35. DATE DCL identifier FIXED BIN[ARY] (m); The integer m must be positive, such that 16 m 31. The Teradata Database normally returns a DATE type field as integer. It is possible to return the value in character string format, as long as the length of the receiving field is sufficient. The DATEFORM=ANSIDATE format returns the DATE type field as CHAR (10). DECIMAL(m,n) DCL identifier FIXED DEC[IMAL] [(m[,n])]; NUMERIC(m,n) DCL identifier FIXED DEC[IMAL][(m[,n])]; The precision and scale integers (m,n) must be positive such that m 15 and 0 n m. n set to zero is equivalent to specifying m alone. If no precision and scalar attributes are specified, a default of FIXED DEC(15) is used. FLOAT* DCL identifier or DCL identifier FLOAT BIN[ARY] (m); FLOAT DEC[IMAL] (n); Integer m must be positive, such that 1 m 21; integer n must be positive such that 1 n 6. REAL* DCL identifier or FLOAT BIN[ARY] (:m); FLOAT DEC[IMAL](n); DCL identifier DOUBLE PRECISION* DCL identifier or FLOAT BIN[ary](m); FLOAT DEC[IMAL](n); DCL identifier 184 Teradata Preprocessor2 for Embedded SQL Programmer Guide

185 Chapter 5: Writing Embedded SQL Applications in PL/I Indicator Variables Table 10: PL/I Definitions for Teradata Database Data Types (continued) Data Type Declaration Notes FLOAT** DCL identifier or DCL identifier FLOAT BIN[ARY] (m); FLOAT DEC[IMAL] (n); Integer m must be positive, such that 22 m 53; integer n must be positive such that 7 n 16. REAL** DCl identifier or FLOAT BIN[ARY](m); FLOAT DEC[IMAL](n); DCL identifier DOUBLE PRECISION** DCL identifier or FLOAT BIN[ARY(m); FLOAT DEC[IMAL](n); DCL identifier BYTEINT No direct equivalent Data can be returned to any valid numeric format if the value fits into the field specified. SMALLINT DCL identifier FIXED BIN[ARY] [(m[,n])]; INTEGER DCL identifier FIXED BIN[ARY] (m[,n]); Integer m must be positive, such that 1 m 15. n is normally zero for integer values, but if specified, PP2 ignores the value. If m is not specified, a default of FIXED BINARY(15) is used. Integer m must be positive, such that 16 m 31. n is normally zero for integer values, but if specified, PP2 ignores the value. GRAPHIC(m) DCL identifier GRAPHIC[(m)]; The integer m is the number of graphic characters (not bytes) and must be positive. VARGRAPHIC(m) DCL identifier GRAPHIC[(m)] If m is not specified, a default of VAR[YING]; GRAPHIC(1) is used. * single precision ** double precision Indicator Variables You can use indicator variables with main variables intended for I/O, although you cannot use certain indicator variables for input (for example, those appearing in a WHERE clause). PP2 uses indicator variables to handle nulls sent to or returned from the Teradata Database or truncation of a character or byte string when placed into the corresponding main variable. Indicator variables are documented in SQL Reference: Stored Procedures and Embedded SQL. Teradata Preprocessor2 for Embedded SQL Programmer Guide 185

186 Chapter 5: Writing Embedded SQL Applications in PL/I Indicator Variables Rules for Indicator Variables An indicator variable containing A negative number (most commonly -1) Zero A positive number Specifies to the application that the associated input main variable is to be treated as a null. Alternatively, it means the Teradata Database returned a null for the associated column. the associated input main variable is non-null or that a non-null value was successfully returned with no exception conditions applied. truncation has occurred when returning a character or byte string to the associated main variable. This value represents the original length of the string before truncation. An indicator variable is defined as a two byte integer (smallint). In PL/I, this is declared as: DCL identifier FIXED BIN[ARY][(n)]; With this declaration, integer n must be positive, such that 1 <= n <= 15. If n is not specified, a default of 15 is used. Indicator Variables and Input You can use indicator variables when the application requires the Teradata Database to set a column value to null, such as when executing an INSERT or UPDATE statement. Indicator variables can be used within a WHERE clause condition with host variables to indicate a null. A negative value indicates the value in the associated main variable is to be ignored and PP2 is to send a null to the Teradata Database for the column. A zero or positive value specifies the main variable value is to be sent to the Teradata Database as the column value. EXEC SQL INSERT table1 VALUES (:hostvar1 :indvar1); EXEC SQL UPDATE table1 SET col1 = :hostvar1 :indvar1 WHERE col1 = :hostvar2; 186 Teradata Preprocessor2 for Embedded SQL Programmer Guide

187 Chapter 5: Writing Embedded SQL Applications in PL/I Indicator Variables Indicator Variables and Output Indicator variables can be associated with the output main variables used in the INTO clause of a data returning statement or cursor FETCH statement. If the Teradata Database returns a Null for a column and no indicator variable exists Negative value Positive value THEN the SQLCODE in the SQLCA is set to -305 and the value of the receiving main variable remains unchanged. the field is returned to the main variable with no exception conditions. the returned byte or character string is truncated. EXEC SQL SELECT col1 INTO :hostvar1 :indvar1 FROM table1 WHERE col1 = :hostvar2; EXEC SQL FETCH cursor1 INTO :hostvar1 :indvar1; Indicator Variables and Structures To facilitate use of indicator variables with host structures for output, PP2 accepts the definition of an array of small integers. As an example, consider: DCL 1 STRUCTURE1, 2 FIELD1 CHAR(20), 2 FIELD2 FIXED BIN(31), 2 FIELD3 CHAR(6), 2 FIELD4 FIXED DEC(13,2); DCL INDVAR(4) FIXED BIN(15); EXEC SQL SELECT * INTO :STRUCTURE1 :INDVAR FROM table1 WHERE col1 = :hostvar2; EXEC SQL FETCH cursor1 INTO :STRUCTURE1 :INDVAR; In both examples, INDVAR(1) is associated with FIELD1, INDVAR(2) with FIELD2, and so forth. The host variable is not required to have an associated indicator variable. The INDVAR array above could have had two elements rather than four. PP2, however, associates host variables and indicator variables one-to-one, in order of occurrence. In these examples, FIELD1 and FIELD2 would have associated indicators, while FIELD3 and FIELD4 would have no indicators (assuming the array is defined with two elements). Indicator arrays may be associated only with a structure. Use of an array with individual elements results in a precompiler error. Teradata Preprocessor2 for Embedded SQL Programmer Guide 187

188 Chapter 5: Writing Embedded SQL Applications in PL/I SQL Error Return ANSI Mode SQL Error Return ANSI Mode Error conditions arising during processing of a SQL request made in ANSI mode are returned to the application via the SQLCODE or SQLSTATE variables. The SQLSTATE and SQLCODE variables are documented in SQL Reference: Stored Procedures and Embedded SQL. SQLCODE Variable The SQLCODE variable contains a negative value when an error condition is reported. A positive value indicates that a warning has occurred. If no exception or error condition is encountered during processing, PP2 sets the SQLCODE variable to zero. SQLCODE is defined as a long integer variable as follows: DCL SQLCODE FIXED BIN(31); Some exception conditions are not reflected in the SQLCODE. Data truncation on assignment of a value to a host variable is returned in SQLCODE(+902). In these cases, the SQLWARN fields or any indicator variables associated with a host variable are set to indicate these conditions. The application must always check the SQLCODE variable upon return from processing an executable statement. Use the WHENEVER statement as one method to accomplish SQLCODE checking. You can define both a SQLCODE and a SQLSTATE variable for the same compilation unit. Both contain valid result codes. For details on the ANSI SQLCODE variable, see SQL Reference: Stored Procedures and Embedded SQL. SQLSTATE Variable The SQLSTATE variable is an ANSI standard, 5 character string value logically divided into a 2 character class and a 3 character subclass. SQLSTATE is defined as a character variable as follows: Definition: DCL SQLSTATE CHAR(5)]; You can define both a SQLSTATE and a SQLCODE variable for the same compilation unit. Both contain valid result codes. Using PPRTEXT to Retrieve Return Codes PP2 provides a mechanism for retrieving the CLIv2, TDP, PP2 runtime or Teradata Database return codes; and the message text associated with the SQLCODE. 188 Teradata Preprocessor2 for Embedded SQL Programmer Guide

189 Chapter 5: Writing Embedded SQL Applications in PL/I SQL Error Return Teradata Mode When SQL Flagger warnings are found, only the first such warning for a particular statement is available through PPRTEXT. The application issues a call to PPRTEXT, passing four parameters as input to the routine. For additional information on PPRTEXT, see Messages. The four parameters are defined in SQL Error Return Teradata Mode on page 189, along with an example of how an application may call this routine. SQL Error Return Teradata Mode SQLCODE Field Error conditions arising during the processing of a SQL request are returned to the application via the SQL Communications Area (SQLCA). In particular, the SQLCODE field of the SQLCA contains a negative number when an error condition is reported. If no exception or error condition is encountered during processing, PP2 sets the SQLCODE field to zero. Some exception conditions, however, are not reflected in the SQLCODE. For example, data truncation on assignment of a value to a host variable or return of a null value is not reported directly. In these cases, the SQLWARN fields or any indicator variables associated with a host variable are set to indicate these conditions. The application must always check the SQLCODE field upon return from processing an executable statement. The WHENEVER statement, illustrated below, is one method to perform SQLCODE checking. For details on the SQLCA fields, see SQL Reference: Stored Procedures and Embedded SQL. Using PPRTEXT to Retrieve Return Codes PP2 provides a mechanism for retrieving the CLIv2, TDP, PP2 runtime or Teradata Database return codes; and the message text associated with the SQLCODE. When SQL Flagger warnings are found, only the first such warning for a particular statement is available through PPRTEXT. The application issues a call to PPRTEXT, passing four parameters as input to the routine. For additional information on PPRTEXT, see Messages. The four parameters are defined below, along with an example as to how an application may call this routine. In order, the four parameters PPRTEXT expects to receive are: 1 SQL_RDTRTCON Precompiler-generated field set by the code generated at precompile time. This data should never be altered by the application; it has a declaration of: DCL SQL_RDTRTCON FIXED BIN(31); 2 ERROR_CODE Application declares this field; the name is not important and the name shown is an example. Teradata Preprocessor2 for Embedded SQL Programmer Guide 189

190 Chapter 5: Writing Embedded SQL Applications in PL/I Exception Conditions: WHENEVER PPRTEXT places the actual error code in this field and no initialization is necessary. Declare this field as: DCL ERROR_CODE FIXED BIN(31); 3 ERROR_MSG Application declares this field; the name is not important and the name shown is just an example; PPRTEXT places the message text and the length of the text returned in this field and no initialization by the application is necessary. Declare this field as follows: DCL ERROR_MSG CHAR(255) VAR; Note: The precompiler considers this field as varying character. The ERROR_MSG field may be declared any size from one to 255. PPRTEXT returns at most the number of bytes in the message and/or the value given in the next field (MAX_LENGTH). Remaining bytes are not filled with spaces. The application may initialize the ERROR_MSG.arr field to spaces prior to calling PPRTEXT. 4 MAX_LENGTH Application declares and initializes this field. The name is not important and the name given is just an example. PPRTEXT uses this field to determine the amount of text that may be placed in the text receiving field (ERROR_MSG, above); the value may be less than the actual size of the text field. If the message text exceeds this value, the text is truncated; if the value of this field exceeds the size of the receiving field, unpredictable results may occur. Declare this field as follows: DCL MAX_LENGTH FIXED BIN(15) INIT(255); Note: The +255 is the maximum length that may returned based on the declaration of ERROR_MSG in this example. Code the call to PPRTEXT as follows: CALL PPRTEXT (SQL_RDTRTCON, ERROR_CODE, ERROR_MSG, MAX_LENGTH); Typical PPRTEXT usage is shown in the Dynamic Statement Example on page 191. Exception Conditions: WHENEVER The WHENEVER statement specifies the action to be taken when an exception condition occurs. 190 Teradata Preprocessor2 for Embedded SQL Programmer Guide

191 Chapter 5: Writing Embedded SQL Applications in PL/I Dynamic Statement Example Exception Conditions Condition SQLWARNING Occurs when the SQLWARN0 field in the SQLCA is W SQLERROR SQLCODE field in the SQLCA is < 0 NOTFOUND SQLCODE field in the SQLCA is +100 For any condition, one of the following actions can be taken: With this action logic CONTINUE GOTO host label CALL function call Processing continues to the next executable statement in the application program (that is, the exception condition is ignored). at the specified location. with the specified function call. WHENEVER Is Declarative The WHENEVER statement itself is not executable. PP2 generates code for each executable SQL statement based on the WHENEVER conditions in effect at the time of the call. If no WHENEVER statement is specified, the default condition is CONTINUE. An explicit WHENEVER statement affects all following SQL statements until another WHENEVER statement is encountered. This is a declarative; the WHENEVER statement is processed as it is sequenced in the source and not how it is executed at runtime. Rules for Using WHENEVER The WHENEVER statement must precede the SQL statement or statements for which the condition is to apply. The host label object must follow PL/I rules for labels. When the CALL action is used, the code object must be such that the CALL function call statement is valid at every SQL statement to which the exception declaration applies. Dynamic Statement Example A sample PL/I program follows that selects multiple rows from a table called EMPLOYEE, inserts a row into that table, then deletes the row just inserted. This procedure is performed using the three dynamic mechanisms which are available. This example is intended to illustrate dynamic statements. Teradata Preprocessor2 for Embedded SQL Programmer Guide 191

192 Chapter 5: Writing Embedded SQL Applications in PL/I Dynamic Statement Example The program has the SQL statements coded directly. The application could also read the statements from a terminal, a file or by some other method. The EMPLOYEE table is shown in Appendix C: Embedded SQL Examples. Sequence SELECT Descriptive Note The SELECT statement is a data returning statement. Thus the statement is executed using a dynamic cursor. The PREPARE readies the statement in the SQL string SQL_STATEMENT for execution. The DESCRIBE returns information about the data coming back into the user defined SQLDA (SQLDA). The program initializes the SqlDAID, SqlDABC and SqlN fields prior to executing the DESCRIBE request. SqlDABC is set by PP2 runtime, while SqlN indicates to the DESCRIBE the number of repeating element groups available to contain field information. The OPEN statement specifies the host variable whose value replaces the null found in the SELECT statement. The OPEN executes the select, returning an indication of success or failure to the application, as well as the number of rows which are returned if the statement is successfully executed. The FETCH loop returns the data into the specified host variables (via the SQLDA structure) until no more data is found (+100 in the SQLCODE) or an error occurs (negative SQLCODE). The CLOSE terminates the cursor and performs the cleanup related to the select statement. INSERT DELETE The insert statement does not return data, nor does it require input host variables. This facility allows the statement to execute using an EXECUTE IMMEDIATE. The delete statement does not return data, but requires an input host variable, which requires an EXECUTE statement. The PREPARE readies the statement in the SQL string for execution. A DESCRIBE is not required for the delete since no data is returned. The EXECUTE submits the delete to the Teradata Database for processing, passing the value of the host variable indicated in the SQLDA (SQLDA) for the null. The success or failure of the transaction is reflected in the SQLCODE. The number of rows deleted, if any, appears in the first SQLERRD element. SAMPLE:PROC OPTIONS (MAIN); /* DECLARATIONS OF BUILTIN FUNCTIONS */ DCL PPRTEXT EXTERNAL ENTRY OPTIONS (ASM INTER); DCL ADDR BUILTIN; DCL NULL BUILTIN; /* DECLARATION OF VARIABLES */ DCL LOGON_STRING CHAR(12) INIT ( tdp/user,psw ); DCL 01 EMPLOYEE_RECORD, 02 EMPNUM BIN FIXED(31), 192 Teradata Preprocessor2 for Embedded SQL Programmer Guide

193 Chapter 5: Writing Embedded SQL Applications in PL/I Dynamic Statement Example 02 MANNUM BIN FIXED(31), 02 DPTNUM BIN FIXED(31), 02 JOBNUM BIN FIXED(31), 02 LSTNAM CHAR(20), 02 FSTNAM CHAR(30) VAR, 02 HIRDAT BIN FIXED(31), 02 BRTDAT BIN FIXED(31), 02 SALARY DEC FIXED(15,2); DCL EMPIND BIN FIXED(15); DCL MANIND BIN FIXED(15); DCL DPTIND BIN FIXED(15); DCL JOBIND BIN FIXED(15); DCL LSTIND BIN FIXED(15); DCL FSTIND BIN FIXED(15); DCL HIRIND BIN FIXED(15); DCL BRTIND BIN FIXED(15); DCL SALIND BIN FIXED(15); DCL SQL_STATEMENT CHAR(176) VAR INIT ( SELECT EMPLOYEE_NUMBER, MANAGER_EMPLOYEE_N UMBER, DEPARTMENT_NUMBER, JOB_CODE, LAST_NAME, FIRST_NA ME, HIRE_DATE, BIRTHDATE, SALARY_AMOUNT FROM EMPLOYEE W HERE EMPLOYEE_NUMBER =? ); DCL INS_STATEMENT CHAR(91) VAR INIT ( INSERT EMPLOYEE VALUES (2010,1003,2216,820 1, JONES, FREDDY, 20/06/14, 19/05/26, ) ); DCL 01 SQLDA BASED(SQLDAPTR), 02 SQLDAID CHAR(8), 02 SQLDABC BIN FIXED(31), 02 SQLN BIN FIXED(15), 02 SQLD BIN FIXED(15), 02 SQLVAR (SQLSIZE REFER(SQLN)), 03 SQLTYPE BIN FIXED(15), 03 SQLLEN BIN FIXED(15), 03 SQLDATA PTR, 03 SQLIND PTR, 03 SQLNAME CHAR(30) VAR; DCL SQLSIZE BIN FIXED(15); DCL SQLDAPTR PTR; DCL 01 DELSQLDA, 02 DELDAID CHAR(8), 02 DELDABC BIN FIXED(31) INIT(60), 02 DELN BIN FIXED(15) INIT(1), 02 DELD BIN FIXED(15) INIT(1), 02 DELVAR, 03 DELTYPE BIN FIXED(15) INIT(496), 03 DELLEN BIN FIXED(15) INIT(4), 03 DELDATA PTR INIT(ADDR(EMPNUM)), 03 DELIND PTR INIT(NULL), 03 DELNAME CHAR(30) VAR; DCL ERROR_MSG CHAR(255) VAR; DCL ERROR_CODE BIN FIXED(31); DCL MAX_LENGTH BIN FIXED(15) INIT (255); DCL REQUEST_TYPE CHAR(8); EXEC SQL INCLUDE SQLCA; EXEC SQL DECLARE EMPCUR CURSOR FOR EMPSTMT; PUT SKIP EDIT( EXECUTING SAMPLE... ) (A); PUT SKIP EDIT( ) (A); Teradata Preprocessor2 for Embedded SQL Programmer Guide 193

194 Chapter 5: Writing Embedded SQL Applications in PL/I Dynamic Statement Example /*******************************************************/ /********** LOGON */ /*******************************************************/ REQUEST_TYPE = LOGON ; EXEC SQL LOGON :LOGON_STRING; CALL ERROR_CHECK (); IF SQLCODE = 0 THEN STOP; /*******************************************************/ /********** PREPARE */ /*******************************************************/ REQUEST_TYPE = PREPARE ; EXEC SQL PREPARE EMPSTMT FROM :SQL_STATEMENT; CALL ERROR_CHECK (); IF SQLCODE < 0 THEN CALL LOGOFF; /*******************************************************/ /********** DESCRIBE */ /*******************************************************/ REQUEST_TYPE = DESCRIBE ; SQLSIZE = 9; ALLOCATE SQLDA SET(SQLDAPTR); SQLDAID = SQLDA ; SQLDABC = 0. EXEC SQL DESCRIBE EMPSTMT INTO SQLSQLDA; CALL ERROR_CHECK (); IF SQLCODE = 0 THEN DO; SQLDATA(1) = ADDR(EMPNUM); SQLIND(1) = ADDR(EMPIND); SQLDATA(2) = ADDR(MANNUM); SQLIND(2) = ADDR(MANIND); SQLDATA(3) = ADDR(DPTNUM); SQLIND(3) = ADDR(DPTIND); SQLDATA(4) = ADDR(JOBNUM); SQLIND(4) = ADDR(JOBIND); SQLDATA(5) = ADDR(LSTNAM); SQLIND(5) = ADDR(LSTIND); SQLDATA(6) = ADDR(FSTNAM); SQLIND(6) = ADDR(FSTIND); SQLDATA(7) = ADDR(HIRDAT); SQLIND(7) = ADDR(HIRIND); SQLDATA(8) = ADDR(BRTDAT); SQLIND(8) = ADDR(BRTIND); SQLDATA(9) = ADDR(SALARY); SQLIND(9) = ADDR(SALIND); SQLTYPE(7) = 496; SQLTYPE(8) = 496; SQLLEN(9) = 3842; END; IF SQLCODE < 0 THEN CALL LOGOFF; /*******************************************************/ 194 Teradata Preprocessor2 for Embedded SQL Programmer Guide

195 Chapter 5: Writing Embedded SQL Applications in PL/I Dynamic Statement Example /********** OPEN */ /*******************************************************/ REQUEST_TYPE = OPEN ; EMPNUM = 1001; EXEC SQL OPEN EMPCUR USING :EMPNUM; CALL ERROR_CHECK (); IF SQLCODE = 0 THEN DO UNTIL (SQLCODE = 0); CALL FETCH_EMPCUR (); END; /*******************************************************/ /********** CLOSE */ /*******************************************************/ REQUEST_TYPE = CLOSE ; EXEC SQL CLOSE EMPCUR; CALL ERROR_CHECK (); /*******************************************************/ /********** EXECUTE IMMEDIATE */ /*******************************************************/ REQUEST_TYPE = EXECUTE ; EXEC SQL EXECUTE IMMEDIATE :INS_STATEMENT; CALL ERROR_CHECK (); /*******************************************************/ /********** PREPARE */ /*******************************************************/ REQUEST_TYPE = PREPARE ; EXEC SQL PREPARE DELSTMT FROM :DEL_STATEMENT; CALL ERROR_CHECK (); IF SQLCODE < 0 THEN CALL LOGOFF; /*******************************************************/ /********** EXECUTE */ /*******************************************************/ REQUEST_TYPE = EXECUTE ; EMPNUM = 2010; EXEC SQL EXECUTE DELSTMT USING DESCRIPTOR DELSQLDA; CALL ERROR_CHECK (); CALL LOGOFF; /*******************************************************/ /********** LOGOFF */ /*******************************************************/ LOGOFF:PROC; REQUEST_TYPE = LOGOFF ; EXEC SQL LOGOFF; CALL ERROR_CHECK (); END LOGOFF; /*******************************************************/ /********** FETCH CURSOR */ /*******************************************************/ FETCH_EMPCUR:PROC; REQUEST_TYPE = FETCH ; EXEC SQL Teradata Preprocessor2 for Embedded SQL Programmer Guide 195

196 Chapter 5: Writing Embedded SQL Applications in PL/I Online Archive FETCH EMPCUR USING DESCRIPTOR SQLDA; CALL ERROR_CHECK (); IF SQLCODE = 0 THEN DO; PUT SKIP EDIT ( ) (A); PUT SKIP EDIT ( EMPLOYEE NUMBER :,EMPNUM) (A, F(15)); PUT SKIP EDIT ( MANAGER NUMBER :,MANNUM) (A, F(15)); PUT SKIP EDIT ( DEPARTMENT NUMBER :,DPTNUM) (A, F(15)); PUT SKIP EDIT ( JOB CODE :,JOBNUM) (A, F(15)); PUT SKIP EDIT ( LAST NAME :,LSTNAM) (A, A); PUT SKIP EDIT ( FIRST NAME :,FSTNAM) (A, A); PUT SKIP EDIT ( HIRE DATE :,HIRDAT) (A, P 99/99/99 ); PUT SKIP EDIT ( BIRTH DATE :,BRTDAT) (A, P 99/99/99 ); PUT SKIP EDIT ( SALARY AMOUNT :,SALARY) (A, F(15,2)); END; END FETCH_EMPCUR; ERROR_CHECK:PROC; /*******************************************************/ /********** ERROR CHECK */ /*******************************************************/ IF SQLCODE = 0 THEN DO; ERROR_MSG = ; CALL PPRTEXT (SQL_RDTRTCON, ERROR_CODE, ERROR_MSG, MAX_LENGTH); PUT SKIP EDIT ( ) (A); PUT SKIP EDIT ( ERROR/WARNING DETECTED IN, REQUEST_TYPE) (A, A); PUT SKIP EDIT ( CODE:, ERROR_CODE) (A, F(9)); PUT SKIP EDIT ( MSG :, ERROR_MSG) (A, A); END; END ERROR_CHECK; END SAMPLE;* Online Archive Online archive is a process in which rows are archived from a table at the same time update, insert, or delete operations on the table are taking place. When an online archive is initiated on a table or a database, a log is created for the specified table or separate logs are created for each table in the specified database. The log, which contains all changes to the table, is saved as 196 Teradata Preprocessor2 for Embedded SQL Programmer Guide

197 Chapter 5: Writing Embedded SQL Applications in PL/I Online Archive a part of the archive process. The changes recorded in the log can be applied to any changes to the table that occurred during the archive, such as a restore operation. Two new SQL statements start and stop the online archive process: LOGGING ONLINE ARCHIVE ON and LOGGING ONLINE ARCHIVE OFF. Example Example The following SQL statement initiates the online archive process for the database on a weekly basis: EXEC SQL LOGGING ONLINE ARCHIVE ON FOR WEEKLY; The following SQL statement stops the weekly online archive of the database: EXEC SQL LOGGING ONLINE ARCHIVE OFF FOR WEEKLY; Teradata Preprocessor2 for Embedded SQL Programmer Guide 197

198 Chapter 5: Writing Embedded SQL Applications in PL/I Online Archive 198 Teradata Preprocessor2 for Embedded SQL Programmer Guide

199 APPENDIX A SQL Data Type Codes PP2 uses data type codes for both input and output SQL Descriptor Area (SQLDA) structures generated by the precompiler and recognized at execution. The Teradata Database returns data type code values to the SQLDA specified by the application using a PREPARE or DESCRIBE statement. The data type is in the two byte SQLTYPE integer field of the SQLDA. Use the following guidelines in interpreting the tables in the next sections: IF the code is Even-numbered Odd-numbered THEN the variable cannot be null (no indicator variables are allowed). can be null (indicator variables are allowed). Data Type Codes Table 11: SQL Data Type Codes Code Data Type 400 BLOB 404 BLOB AS DEFERRED 408 BLOB AS LOCATOR 416 CLOB 420 CLOB AS DEFERRED 424 CLOB AS LOCATOR CHAR LONG CHAR VARGRAPHIC Teradata Preprocessor2 for Embedded SQL Programmer Guide 199

200 Appendix A: SQL Data Type Codes Data Type Codes Table 11: SQL Data Type Codes (continued) Code Data Type GRAPHIC LONG GRAPHIC FLOAT DECIMAL VARCHAR INTEGER SMALLINT BIGINT VARBYTE BYTE LONG VARBYTE Teradata Database DATE BYTEINT 200 Teradata Preprocessor2 for Embedded SQL Programmer Guide

201 Appendix A: SQL Data Type Codes Unused/Internal Data Type Codes Unused/Internal Data Type Codes Currently, the following codes are unused or are for only internal use: Code Data Type IBM DATE ZONED DECIMAL (sign trailing) ZONED DECIMAL (sign trailing separate) ZONED DECIMAL (sign leading) ZONED DECIMAL (sign leading separate) CHAR (array) INTEGER (byte flipped) SMALLINT (byte flipped) Teradata Preprocessor2 for Embedded SQL Programmer Guide 201

202 Appendix A: SQL Data Type Codes Unused/Internal Data Type Codes 202 Teradata Preprocessor2 for Embedded SQL Programmer Guide

203 APPENDIX B Sample Application Linkage Procedure This appendix gives general guidelines for linking the libraries required by PP2 application programs. Modify the procedures in this section to accommodate individual installation requirements. You can link applications in a number of ways; the examples in this section show one possible method. Overview To prepare a Teradata SQL program for execution: 1 Preprocess the application. 2 Compile or assemble the result. 3 Link the necessary libraries. 4 Store the resulting load module for later execution. 64-Bit Platform Linking Concerns The following applies to linking applications to runtime libraries: This PP2 Application... Using this Precompiler... Can Link to this Runtime Library bit 32-bit 32-bit 64-bit 64-bit 64-bit The 32-bit user s PP2 applications can only link to the 32-bit PP2 and CLI libraries. The 64-bit user s PP2 applications can only link to 64-bit PP2 and CLI libraries. Cross linking is not supported. Teradata Preprocessor2 for Embedded SQL Programmer Guide 203

204 Appendix B: Sample Application Linkage Procedure Application Linking for z/os Application Linking for z/os Linkage Job Control Language //LINKJOB JOB job statement information) //LINK EXEC PGM=IEWL,REGION=320K,PARM= XREF,LIST //SYSPRINT DD SYSOUT=*,DCB=(LRECL=121, BLKSIZE=3630,RECFM=FBA) //SYSLMOD DD DSN=customer.load.library,DISP=SHR 1 //SYSLIB DD DSN=language.load.library,DISP=SHR //SYSUT1 DD UNIT=SYSDA,SPACE=(TRK,(5,2)) //OBJ DD DSN=application.object.module,DISP=OLD 2 //TDLIBS DD DSN=TERADATA.APPLOAD,DISP=SHR 3 //SYSLIN DD * INCLUDE OBJ INCLUDE TDLIBS(TDARDI) // JCL Notes Usage Notes 1 The SYSLIB data set contains the language-specific load modules. For example, VSCLLIB for COBOL or PLIBASE for PL/I. Include multiple load modules here as required by the application. 2 The TDLIBS data set contains the PP2 runtime and CLIv2 modules for batch execution. 3 The SYSLIN data set contains the linking control statements. Link TDARDI to the application program. If you use PPRTEXT in the application, link it to the application program. The linkage editor may include the CLIv2 stub automatically with COBOL programs; this stub inclusion is related to the use of DBCHSAD. Including only the TDARDI module in the link: Minimizes the size of the application program. Makes re-linking required if changes are made to the application or to the Teradata Database stubs (CLIv2 or PP2). The TERADATA.APPLOAD library should be made available when the application is executed. Re-linking is required only if changes are made to the application or the Teradata CLIv2 or PP2 stubs. 204 Teradata Preprocessor2 for Embedded SQL Programmer Guide

205 Appendix B: Sample Application Linkage Procedure Application Linking for CICS Application Linking for CICS Linkage Job Control Language //LINKJOB JOB (job statement information) //LINK EXEC PGM=IEWL,REGION=320K,PARM= XREF,LIST //SYSPRINT DD SYSOUT=*,DCB=(LRECL=121, BLKSIZE=3630,RECFM=FBA) //SYSLMOD DD DSN=customer.load.library,DISP=SHR 1 //SYSLIB DD DSN=CICS.load.library,DISP=SHR // DD DSN=language.load.library,DISP=SHR //SYSUT1 DD UNIT=SYSDA,SPACE=(TRK,(5,2)) //OBJ DD DSN=application.object.module,DISP=OLD 2 //TDLIBS DD DSN=TERADATA.CSILOAD,DISP=SHR 3 //SYSLIN DD * INCLUDE OBJ INCLUDE TDLIBS(TDARDI) // JCL Notes Usage Notes 1 The SYSLIB data set contains the CICS and language-specific load modules. For example, VSCLLIB for COBOL or PLIBASE for PL/I. Include multiple load modules here as required by the application. 2 The TDLIBS data set contains PP2 runtime and CLIv2 modules for CICS linkage. 3 The SYSLIN data set contains the linkage control statements. Link TDARDI to the application program. If you use PPRTEXT in the application, link it to the application program. The linkage editor can include the CLIv2 stub automatically with COBOL programs; this stub inclusion is related to the use of DBCHSAD. Including only the TDARDI module in the link: Minimizes the size of the application program. Makes re-linking required if changes are made to the application or to the Teradata Database stubs (CLIv2 or PP2). The TERADATA.CXILOAD library must be in the CICS startup JCL. Re-linking is required if changes are made to the application. the Teradata CLIv2 stub, or the PP2 stub. Teradata Preprocessor2 for Embedded SQL Programmer Guide 205

206 Appendix B: Sample Application Linkage Procedure Application Linking for IMS Application Linking for IMS Linkage Job Control Language //LINKJOB JOB (job statement information) //LINK EXEC PGM=IEWL,REGION=320K, PARM= XREF,LIST //SYSPRINT DD SYSOUT=*,DCB=(LRECL=121, BLKSIZE=3630,RECFM=FBA) //SYSLMOD DD DSN=customer.load.library,DISP=SHR 1 //SYSLIB DD DSN=IMS.load.library,DISP=SHR // DD DSN=language.load.library,DISP=SHR //SYSUT1 DD UNIT=SYSDA,SPACE=(TRK,(5,2)) //OBJ DD DSN=application.object.module,DISP=OLD 2 //TDLIBS DD DSN=TERADATA.APPLOAD,DISP=SHR 3 //SYSLIN DD * INCLUDE OBJ INCLUDE TDLIBS(TDARDI) // JCL Notes Usage Notes 1 The SYSLIB data set contains the IMS and language specific load modules. For example, VSCLLIB for COBOL or PLIBASE for PL/I. Include multiple load modules here as required by the application. 2 The TDLIBS data set contains the PP2 runtime and CLIv2 modules for IMS execution. 3 The SYSLIN data set contains the linkage control statements. Link TDARDI to the application program. If you use PPRTEXT in the application, link it to the application program. The linkage editor can include the CLIv2 stub automatically with COBOL programs; this stub inclusion is related to the use of DBCHSAD. Including only the TDARDI module in the link: Minimizes the size of the application program. Makes re-linking required if changes are made to the application or to the Teradata Database stubs (CLIv2 or PP2). Include the TERADATA.APPLOAD library in the IMS startup JCL. 206 Teradata Preprocessor2 for Embedded SQL Programmer Guide

207 Appendix B: Sample Application Linkage Procedure Application Linking for z/vm CMS Application Linking for z/vm CMS Linkage Exec 1 GLOBAL TXTLIB langtxtlib PPR CLI LOAD txtfile (NOINV 2 INCLUDE TDARDI GENMOD modfile JCL Notes Usage Notes 1 The GLOBAL TXTLIB statement makes all necessary text files available to the linkage editor. langtxtlib contains the language-specific texts. PPR refers to the PP2 runtime txtlib. CLI is the CLIv2 txtlib. 2 Link TDARDI to the application program. The linkage editor can include the CLIv2 stub automatically with COBOL programs; this stub inclusion is related to the use of DBCHSAD. Including only the TDARDI module in the link: Minimizes the size of the application program. Makes re-linking required if changes are made to the application or to the Teradata Database stubs (CLIv2 or PP2). PPRTEXT can also be included implicitly in the load module if the application has made use of it and no explicit include appears in the linkage control statements. PPR and CLI libraries must be made global before executing the application. Re-linking is required only if changes are made to the application or the Teradata CLIv2 or PP2 stubs. Teradata Preprocessor2 for Embedded SQL Programmer Guide 207

208 Appendix B: Sample Application Linkage Procedure Application Linking for C on UNIX Application Linking for C on UNIX Linkage Script for a 32-Bit Application on AIX cc -brtl <sourcefile.c> -o <executablename> -lppruntim -ltdusr -lcliv2 -lnsl -licuuctd - licudatatd Linkage Script for a 64-Bit Application on AIX cc -qalign=packed -q64 -brtl <sourcefile.c> -o <executablename> -lppruntim -ltdusr -lcliv2 -lnsl -licuuctd -licudatatd Linkage Script for a 32- Bit Application on HP-UX cc <sourcefile.c> -Wl,+s,+b/usr/lib -o <executablename> -lppruntim -ltdusr -lcliv2 -lnsl -licuuctd -licudatatd Linkage Script for a 64- Bit Application on HP-UX cc <sourcefile.c> +DD64 -Wl,+s,+b/use/lib/pa20_64 -o <executablename> -lppruntim -ltdusr -lcliv2 -lnsl -licuuctd -licudatatd Linkage Script for a 64- Bit Application on Itanium HP-UX cc <sourcefile.c> +DD64 -Wl,+s,+b/use/lib/hpux64 -o <executablename> -lppruntim -ltdusr - lcliv2 -lnsl -licuuctd -licudatatd Linkage Script for a 32-Bit Application on MP-RAS cc <sourcefile.c> -o <executablename> -lppruntim -ltdusr -lcliv2 -lnsl -lsocket -licuuctd -licudatatd Linkage Script for a 32-Bit Application on 32-Bit Red Hat Linux cc <sourcefile.c> -o <executablename> -lppruntim -ltdusr -lcliv2 -lnsl -licudatatd - licuuctd Note: Red Hat Linux 3.0 A compilation error occurs if: you attempt to compile a PP2 application on Red Hat Linux 3.0 have built PPCMain on Red Hat Linux Teradata Preprocessor2 for Embedded SQL Programmer Guide

209 Appendix B: Sample Application Linkage Procedure Application Linking for C on UNIX To fix the compilation error: 1 Add this code to the.pc file: ===================================================================== #include <ctype.h> const unsigned short int * ctype_b; const int32_t * ctype_tolower; const int32_t * ctype_toupper; void ctsetup() { ctype_b = *( ctype_b_loc()); } ===================================================================== 2 Call ctsetup from main() as first statement. Linkage Script for a 32-Bit Application on 64-Bit Linux (RH/SUSE) cc <sourcefile.c> -o <executablename> -L/usr/lib -lppruntim -ltdusr -lcliv2 -lnsl - licudatatd -licuuctd Linkage Script for a 64-Bit Application on 64-Bit Linux EM64T (RH/SUSE) cc <sourcefile.c> -o <executablename> -L/usr/lib64 -lppruntim -ltdusr -lcliv2 -lnsl - licudatatd -licuuctd Linkage Script for a 64-Bit Application on 64-Bit Itanium RH cc <sourcefile.c> -o <executablename> -L/usr/lib64 -lppruntim -ltdusr -lcliv2 -lnsl - licudatatd -licuuctd Linkage Script for a 32-Bit Application on Opteron Solaris cc <sourcefile.c> -o <executablename> -L/usr/lib/ -lppruntim -lnsl -lsocket -lcliv2 - ltdusr -licudatatd -licuuctd Linkage Script for a 64-Bit Application on Opteron Solaris cc <sourcefile.c> -o <executablename> -L/usr/lib/amd64 -lppruntim -lnsl -lsocket -lcliv2 -ltdusr -licudatatd -licuuctd Linkage Script for a 32-Bit Application on Solaris SPARC cc <sourcefile.c> -o <executablename> -lppruntim -ltdusr -lcliv2 -lnsl -licuuctd - licudatatd Linkage Script for a 64-Bit Application on Solaris SPARC cc -xarch=v9 <sourcefile.c> -o <executablename> -L/usr/lib/sparcv9 -lppruntim -ltdusr - lcliv2 -lnsl -licuuctd -licudatatd Teradata Preprocessor2 for Embedded SQL Programmer Guide 209

210 Appendix B: Sample Application Linkage Procedure Application Linking for Micro Focus COBOL on UNIX Script Notes Where: -lppruntim is the PP2 runtime library -ltdusr is the CLIv2 library -lcliv2 is the CLIv2 library -licuuctd is the ICU library -licudatatd is the ICU library -brtl is used to accept both.so and.a library file types Application Linking for Micro Focus COBOL on UNIX Linkage Script for a 32-Bit Application on AIX cob -x <sourcefile.cob> -lppruntim -ltdusr -lcliv2 -lnsl -licuuctd -licudatatd -L/usr/ccs/lib -lmw lcc Linkage Script for a 64-Bit Application on AIX cob -x <sourcefile.cob> -L/usr/lib/lib_64 -lppruntim -ltdusr -lcliv2 -lnsl -licuuctd -licudatatd Linkage Script for a 32-Bit Application on HP-UX cob -x <sourcefile.cob> -L/usr/lib -lppruntim -ltdusr -lcliv2 -lnsl -licuuctd -licudatatd Linkage Script for a 32-Bit Application on MP-RAS cob <sourcefile.cob> -x -C <IBMCOMP NOIBMCOMP> -o <executable_name> -lppruntim -ltdusr -lcliv2 -lnsl -lsocket -licuuctd -licudatatd -L/usr/ccs/lib -lmw lcc Script Notes Where: -lppruntim is the PP2 runtime library -ltdusr is the CLIv2 library -lcliv2 is the CLIv2 library -licuuctd is the ICU library -licudatatd is the ICU library 210 Teradata Preprocessor2 for Embedded SQL Programmer Guide

211 Appendix B: Sample Application Linkage Procedure Application Linking for LPI COBOL on MP-RAS To compile the COBOL program in this mode... Byte-storage Word-storage Use this compiler option... -C NOIBMCOMP -C IBMCOMP Application Linking for LPI COBOL on MP-RAS Linkage Script for a LPI COBOL Application on MP-RAS ldcobol <sourcefile.o> -o <executable_name> -lnsl -lsocket -ltdusr -lcliv2 -lppruntim - licuuctd licudatatd -L/usr/ccs/lib -lmw lcc Script Notes Used with NCR UNIX, where: -lppruntim is the PP2 runtime library -ltdusr is the CLIv2 library -lcliv2 is the CLIv2 library -licuuctd is the ICU library -licudatatd is the ICU library Application Linking for Visual C++ on Windows Linkage Script for a Visual C++.NET Bit Application on Windows CL <sourcefile.c> /Fe<executablename> ppruntim.lib Linkage Script for a Visual C++.NET Bit Application on Windows CL <sourcefile.c> <path of ppruntim.lib> Script Notes Where: ppruntim.lib is the PP2 runtime library Note: ppruntim.dll must be available when the application is executed. Teradata Preprocessor2 for Embedded SQL Programmer Guide 211

212 Appendix B: Sample Application Linkage Procedure Application Linking for Visual C++ on Windows 212 Teradata Preprocessor2 for Embedded SQL Programmer Guide

213 APPENDIX C Embedded SQL Examples With this software release, there are embedded SQL examples for: C COBOL PL/I About the Examples The examples, called LABs, are a series of nine programs that use a new EMPLOYEE table to load on your database. The examples start with simple syntax statements and progress through more complex operations. Note: The EMPLOYEE table used in the examples is not the same as the default EMPLOYEE table in the PERSONNEL database supplied with your Teradata Database. See EMPLOYEE Table on page 220 for sample data from the EMPLOYEE table. This LAB LAB1 LAB2 LAB3 LAB4 LAB5 LAB6 LAB7 LAB8 LAB9 Demonstrates the LOGON and LOGOFF statements. a static SELECT statement. static SELECT, INSERT, UPDATE and DELETE statements. a multiple row return SELECT statement using cursors. a multiple statement request using cursors. a static EXEC for a macro. This example produces results similar to LAB2, employing a macro. the use of a cursor for a macro. This example produces the same result as LAB5. the use of dynamic SQL with PREPARE, DESCRIBE, and EXECUTE. This run is the dynamic equivalent of LAB2. the use of dynamic SQL, especially the EXECUTE IMMEDIATE construct. This run is the dynamic equivalent of LAB3. Teradata Preprocessor2 for Embedded SQL Programmer Guide 213

214 Appendix C: Embedded SQL Examples Setting Up the Examples LAB Files Not all embedded SQL examples are available on all operating systems. The following table shows language support by operating system: Operating System C COBOL PL/I z/os X X* X Network-attached X z/vm X X* X Note: *NCR system 5100 also supports COBOL. Each LAB file has a different name based on the supported language. LAB COBOL PL/I C LAB1 PPCOBLB1 PPPLILB1 PPCLB1 LAB2 PPCOBLB2 PPPLILB2 PPCLB2 LAB3 PPCOBLB3 PPPLILB3 PPCLB3 LAB4 PPCOBLB4 PPPLILB4 PPCLB4 LAB5 PPCOBLB5 PPPLILB5 PPCLB5 LAB6 PPCOBLB6 PPPLILB6 PPCLB6 LAB7 PPCOBLB7 PPPLILB7 PPCLB7 LAB8 PPCOBLB8 PPPLILB8 PPCLB8 LAB9 PPCOBLB9 PPPLILB9 PPCLB9 Setting Up the Examples Before you can run the SQL examples, set them up on your database. Also set up the necessary authorizations, load the new EMPLOYEE table, and create the required macros. The steps to set up the examples are the same for all operating systems. However, the files you use vary, based on your operating system. The next procedure is an overview of the required steps. For each operating system, there is a section detailing which files to use and their location. 214 Teradata Preprocessor2 for Embedded SQL Programmer Guide

215 Appendix C: Embedded SQL Examples z/os Operating Systems Procedure Overview To set up the SQL examples: 1 Install the PP2 product libraries on all operating systems you intend to use. 2 Run the LABS control stream to: Create the new EMPLOYEE table. Load the EMPLOYEE table. Create the LAB6 macro. Create the LAB7 macro. Note: Execute the create files and load the data only once on any one platform. 3 Grant the following access privileges for the user ID you want to use with the examples. SELECT UPDATE INSERT DELETE Caution: Remember to set the LOGON string variable length and to modify the code to include these items for your installation: TDPID USERID password z/os Operating Systems This section gives details for setting up the embedded SQL examples on z/os platforms. Examples are available for: C COBOL PL/I Where to Find Source Code and LAB Files After you install the PP2 product libraries, you can find the LAB files, the source code for creating the EMPLOYEE table, and the source code for creating the macros for LAB6 and LAB 7 in the sample dataset DBC.SAMPLIB. See LAB Files on page 214 for a list of the LAB file names for each programming language. Which Setup Files to Use In the procedure outlined in Procedure Overview on page 215, use the following files to set up the embedded SQL examples. Teradata Preprocessor2 for Embedded SQL Programmer Guide 215

216 Appendix C: Embedded SQL Examples Network-Attached Operating Systems File Name LABSCNTL LABSBTEQ Description Control stream to execute the BTEQ script BTEQ script that creates, loads, and displays the EMPLOYEE table. It also creates the macros used by the examples z/os JCL The commands required for z/os are: //jobcard //* //BTEQ EXEC PGM=ITBMAIN //STEPLIB DD DSN=bteq.library,DISP=SHR //RUNDR DD DSN=DBC.SAMPLIB(LABSBTEQ),DISP=SHR //SYSPRINT DD SYSOUT=* //SYSIN DD *.RUN DD=RUNDR // Network-Attached Operating Systems This section gives details for setting up the embedded SQL examples on network-attached platforms. Examples are available for: C COBOL 1 Where to Find Source Code and LAB Files Which Setup Files to Use After you install the PP2 product libraries, you can find the LAB files, the source code for creating the EMPLOYEE table, and the source code for creating the macros for LAB6 and LAB 7 in the installed Directories with a file type of TXT. See LAB Files on page 214 for a list of the LAB file names for each programming language. In the procedure outlined in Procedure Overview on page 215, use the following files to set up the embedded SQL examples. File Name LABSBTEQ LABSDATA Description BTEQ script that creates, loads, and displays the EMPLOYEE table. It also creates the macros used by the examples. New EMPLOYEE table data. 1. COBOL is supported on NCR 5100 systems. 216 Teradata Preprocessor2 for Embedded SQL Programmer Guide

217 Appendix C: Embedded SQL Examples z/vm Operating Systems z/vm Operating Systems This section gives details for setting up the embedded SQL examples on z/vm platforms. Examples are available for: C COBOL PL/I Where to Find Source Code and LAB Files Which Setup Files to Use After you install the PP2 product libraries, you can find the LAB files, the source code for creating the EMPLOYEE table, and the source code for creating the macros for LAB6 and LAB 7 on the TDP installation disk with a file type of SAMPLE. Be sure to rename the files before using them. See LAB Files on page 214 for a list of the LAB file names for each programming language. In the procedure outlined in Procedure Overview on page 215, use the following files to set up the embedded SQL examples. File Name Description Rename the File LABSEXEC Control stream that executes the BTEQ script. LABS EXEC LABSBTEQ BTEQ script that creates, loads, and displays the EMPLOYEE table. It also creates the macros used by the examples. LABS BTEQ LABSDATA Contains the new EMPLOYEE table data. LABS DATA z/vm EXEC The EXEC required for z/vm installations is: (See file LABSEXEC) &TRACE * FILEDEF LABDAT DISK LABS DATA FILEDEF RUNDR DISK LABS BTEQ * &STACK LIFO.RUN DD=RUNDR EXEC BTEQ * -EXIT &EXIT Operator Messages The message ERROR/WARNING DETECTED IN xxx is displayed in all cases where the returned SQLCODE is non-zero. Teradata Preprocessor2 for Embedded SQL Programmer Guide 217

218 Appendix C: Embedded SQL Examples EMPLOYEE Table Source Code A SQLCODE of 100 is valid for data returning statements. It indicates that the end of the result set was reached. EMPLOYEE Table Source Code To create the new EMPLOYEE table, follow the next example. This code resides in the LABSBTEQ file. Remember to substitute the userid and password appropriate to your installation..echoreq off.logon tdpid/userid,password DROP TABLE EMPLOYEE; CREATE TABLE EMPLOYEE, FALLBACK, NO BEFORE JOURNAL, NO AFTER JOURNAL (EMPLOYEE_NUMBER INTEGER, MANAGER_EMPLOYEE_NUMBER INTEGER, DEPARTMENT_NUMBER INTEGER, JOB_CODE INTEGER, LAST_NAME CHAR(20) NOT NULL, FIRST_NAME VARCHAR(30) NOT NULL, HIRE_DATE DATE NOT NULL, BIRTHDATE DATE NOT NULL, SALARY_AMOUNT DECIMAL(10,2) NOT NULL) UNIQUE PRIMARY INDEX(EMPLOYEE_NUMBER);.import data dd=labdat.repeat * USING FIELD1 (INT), FIELD2 (INT), FIELD3 (INT), FIELD4 (INT), FIELD5 (CHAR(20)), FIELD6 (VARCHAR(30)), FIELD7 (INT), FIELD8 (INT), FIELD9 (DEC (10,2)) INSERT INTO EMPLOYEE VALUES (:FIELD1, :FIELD2, :FIELD3, :FIELD4, :FIELD5, :FIELD6, :FIELD7, :FIELD8, :FIELD9);.SIDETITLES ON.FOLDLINE ON ALL.SKIPDOUBLE ON 1 SELECT * FROM EMPLOYEE ORDER BY 1; 218 Teradata Preprocessor2 for Embedded SQL Programmer Guide

219 Appendix C: Embedded SQL Examples LAB6 and LAB7 Macros Source Code LAB6 and LAB7 Macros Source Code Two macros are required for the embedded SQL examples LAB6 and LAB7. Sample source code for creating the two macros is shown below. This code resides in the LABSBTEQ file. DROP MACRO LAB6; CREATE MACRO LAB6 AS (INSERT EMPLOYEE VALUES ( 2001, 1003, 2215, 9567, TIME, SUMMER, 74/12/02, 55/06/06, 62000);); DROP MACRO LAB7; CREATE MACRO LAB7 AS (SELECT EMPLOYEE_NUMBER, MANAGER_EMPLOYEE_NUMBER, DEPARTMENT_NUMBER, JOB_CODE, LAST_NAME, FIRST_NAME, HIRE_DATE, BIRTHDATE, SALARY_AMOUNT FROM EMPLOYEE ORDER BY 1; SELECT EMPLOYEE_NUMBER, MANAGER_EMPLOYEE_NUMBER, DEPARTMENT_NUMBER, JOB_CODE, LAST_NAME, FIRST_NAME, HIRE_DATE, BIRTHDATE, SALARY_AMOUNT FROM EMPLOYEE ORDER BY 1 DESC;);.quit Teradata Preprocessor2 for Embedded SQL Programmer Guide 219

220 EMPLOYEE Table Data for the new EMPLOYEE table is shown below. You can find this information in the LABSDATA file. EMPLOYEE NUMBER MANAGER EMPLOYEE NUMBER DEPARTMENT NUMBER JOB CODE LAST NAME FIRST NAME HIRE DATE BIRTH DATE SALARY AMOUNT Hoover William 76/06/18 50/01/ Brown Alan 76/07/31 44/08/ Trader James 76/07/31 47/06/ Johnson Darlene 76/10/15 46/04/ Ryan Loretta 76/10/15 55/09/ Stein John 76/10/15 53/10/ Villegas Arnando 77/01/02 37/01/ Kanieski Carol 77/02/01 58/05/ Lombardo Domingus 77/02/01 45/11/ Rogers Frank 77/03/01 35/04/ Daly James 77/03/15 49/12/ Hopkins Paulene 77/03/15 42/02/ Phillips Charles 77/04/01 63/08/ Crane Robert 78/01/15 60/07/ Wilson Edward 78/03/01 57/03/ Rogers Nora 78/03/01 59/09/ Runyon Irene 78/05/01 51/11/ Ratzlaff Larry 78/07/15 54/05/ Kubic Ron 78/08/01 42/12/ Teradata Preprocessor2 for Embedded SQL Programmer Guide

221 EMPLOYEE NUMBER MANAGER EMPLOYEE NUMBER DEPARTMENT NUMBER JOB CODE LAST NAME FIRST NAME HIRE DATE BIRTH DATE SALARY AMOUNT Charles John 78/10/01 49/06/ Morrissey Jim 78/10/01 43/04/ Machado Albert 79/03/01 57/07/ Greene Peter 79/03/01 62/10/ Brown Allen 79/05/01 54/01/ Short Michael 79/05/01 47/07/ Teradata Preprocessor2 for Embedded SQL Programmer Guide 221

222 222 Teradata Preprocessor2 for Embedded SQL Programmer Guide

223 Glossary Numeric 2PC Two-Phase Commit. A account The distinct account name portion of the system account strings, excluding the performance group designation. Accounts can be employed wherever a user object can be specified. all joins In Teradata SQL, a join is a SELECT operation that allows you to combine columns and rows from two or more tables to produce a result. Join types restricted by DWM are: inner join, outer join, merge join, product join, and all joins. all joins are a combination of the above types, depending on how the user selects the information to be returned. In addition to the four types listed above, selecting all joins may include an exclusion join, nested join, and RowID join. allocation group (AG) A set of parameters that determine the amount of resources available to the sessions assigned to a PG referencing a specific AG. Has an assigned weight that is compared to other AG weights. An AG can limit the total amount of CPU used by sessions under its control. AMP Access Module Processor. Virtual processors (vprocs) that receive steps from PEs (Parsing Engines) and perform database functions to retrieve or update data. Each AMP is associated with one virtual disk (vdisk), where the data is stored. An AMP manages only its own vdisk, not the vdisk of any other AMP. AMP worker task (AWT) Processes (threads on some platforms) dedicated to servicing the Teradata Database work requests. For each AMP vproc, a fixed number of AWTs are preallocated during Teradata Database initialization. Each AWT looks for a work request to arrive in the Teradata Database, services the request, and then looks for another. An AWT can process requests of any work type. Each Teradata Database query is composed of a series of work requests that are performed by AWTs. Each work request is assigned a work type indicating when the request should be executed relative to other work requests waiting to execute. ANSI American National Standards Institute. The private, non-profit organization responsible for approving US standards in many areas, including computers and communications. API Application Program Interface. An interface (calling conventions) by which an application program accesses an operating system and other services. An API is defined at source code level and provides a level of abstraction between the application and the kernel Teradata Preprocessor2 for Embedded SQL Programmer Guide 223

224 Glossary (or other privileged utilities) to ensure the portability of the code. A language and message format used by an application program to communicate with the operating system or some other control program such as a database management system (DBMS) or communications protocol. An API can also provide an interface between a high level language and lower level utilities and services written without consideration for the calling conventions supported by compiled languages. In this case, the API may translate the parameter lists from one format to another and the interpret call-by-value and call-by-reference arguments in one or both directions. ASCII American Standard Code for Information Interchange. The basis of character sets used in almost all present-day computers. B BTET Begin Transaction End Transaction. The Transaction mode (option TRANSACT or -tr) that implicitly creates transactions for each SQL request if there is not an active transaction. Commands that mark a unit of work that is all updated or all rolled back (not updated). BTEQ Basic Teradata Query. A general-purpose, command-based program that allows users on a workstation to communicate with one or more Teradata Database systems, and to format reports for both print and screen output. bypass objects Specific users, groups, and accounts can be set up to circumvent DWM query management by declaring them to be bypassed. Basically, this turns off the DWM query checking mechanism for all of the requests issued by those users and/or using those accounts. C CICS Customer Information Control System. An online transaction processing (OLTP) program from IBM used with the COBOL programming language. Using the application programming interface (API) provided by CICS, a programmer can write programs that communicate with online users and read from or write to customer and other records (orders, inventory figures, customer data, and so forth) in a database (usually referred to as "data sets") using CICS facilities rather than IBM's access methods directly. Like other transaction managers, CICS can ensure that transactions are completed and, if not, undo partly completed transactions so that the integrity of data records is maintained. CLIv2 Call-Level Interface version 2. The application used by Teradata DWM to connect to the Teradata Database. CLI2SPB CLIv2 system parameter block (SPB) for network-attached systems. The internal SPB, is a data structure that is examined during initialization. During initialization, any DBCAREA values not set in the clispb.dat file by the user will default to the values contained in CLI2SPB. COBOL Common Business Oriented Language. A programming language for simple computations on large amounts of data, designed by the CODASYL Committee in April Teradata Preprocessor2 for Embedded SQL Programmer Guide

225 Glossary COBOL's natural language style is intended to be largely self-documenting. It introduced the record structure. CPU Central Processing Unit. The part of a computer which controls all the other parts. D DBA Database Administrator. Generally, a person responsible for the design and management of one or more databases and for the evaluation, selection and implementation of database management systems. DBC The default database associated with user DBC. When you first install Teradata Database on your server, it has only one user. This user is called User DBC and it owns all other databases and users in the system. DBCAREA A communication structure shared by an application program and CLI. The application uses it to forward control and data information. CLI uses it to return control and data information. An application may use a single DBCAREA or multiple DBCAREAs. CLI retains no knowledge of a particular DBCAREA across multiple CLI calls. CLI is concerned only with the values for DBCAREA that are meaningful to the routine called. DBQL Database Query Log. DBQL are a series of system tables created in the DBC database during the Teradata Database installation process. They are used to track query processing. See Database Administration to learn more about the DBQL. DBQM Database Query Manager (an earlier version of Teradata QS). DCB Data Control Block. The control structure that defines the attributes of the file for z/ OS systems. DDL Data Definition Language. SQL statements used to define, revise, and remove database objects. They are used to manage and control access to schema objects in a database. See SQL Reference: Data Definition Statements to learn more. DIT Directory Information Tree. A graphical display of an organization's directory structure, sites, and servers, shown as a branching structure. The top-level (root) directory usually represents the organization level. DML Data Manipulation Language. SQL statements used to change data in the database tables. Can require an application to supply data to the database using input (bind) variables. To find out about DML statements, see SQL Reference: Data Manipulation Statements. DNS Domain Name System. A general-purpose distributed, replicated, data query service chiefly used on Internet for translating hostnames into Internet addresses. Also, the style of hostname used on the Internet, though such a name is properly called a fully qualified domain name. DNS can be configured to use a sequence of name servers, based on the domains in the name being looked for, until a match is found. Teradata Preprocessor2 for Embedded SQL Programmer Guide 225

226 Glossary E EBCDIC Extended Binary Coded Decimal Interchange Code. EBCDIC is an extension to 8 bits of BCDIC (Binary Coded Decimal Interchange Code), an earlier 6-bit character set used on IBM computers. US EBCDIC uses more or less the same characters as ASCII, but different code points. It has non-contiguous letter sequences; some ASCII characters do not exist in EBCDIC (for example, square brackets), and EBCDIC has some (cent sign, not sign) not in ASCII. As a consequence, the translation between ASCII and EBCDIC was never officially completely defined. Some printers, telex machines, and even electronic cash registers can speak EBCDIC, but only so they can converse with IBM mainframes. EUC Extended UNIX Code. Extended UNIX Code (EUC) for Japanese and Traditional- Chinese defines a set of encoding rules that can support from 1 to 4 character sets. exclusion join In Teradata SQL, a product join or merge join where only the rows that do not satisfy (are NOT in) the conditional specified in the SELECT are joined. execution time frame waiting to run. A period of time when DWM can execute scheduled requests that are G global rule Object Access and Query Resource rules can be specified as being global, that is, they apply to all objects, and therefore to all requests. When a rule is specified as being global, no query objects need be (or can be) associated with the rule because all objects are implicitly included. Care should be taken defining a global access rule, as it causes all requests to be rejected except those from the DBC user and any bypassed objects. GSS Generic Security Services. An application level interface (API) to system security services. It provides a generic interface to services which may be provided by a variety of different security mechanisms. Vanilla GSS-API supports security contexts between two entities (known as "principals"). H HSHSPB CLIv2 system parameter block for channel-attached systems. A data structure that is examined during initialization. HSHSPB is the source of the default DBCAREA values if these values were not set in the DBCAREA by the application. I ID Identifier or Identification. IMS Information Management System. A database system from IBM consisting of IMS/ Data Base and IMS/Data Communications. inner join In Teradata SQL, a join operation on two or more tables, according to a join condition, that returns the qualifying rows from each table. 226 Teradata Preprocessor2 for Embedded SQL Programmer Guide

227 Glossary I/O Input/Output. Communication between a computer and its users, its storage devices, other computers (via a network) or the outside world. The devices the computer uses to do this are called "peripherals." What actually counts as I/O depends on what level of detail you are considering, e.g. communication between processors would not be considered I/O when considering a multiprocessor as a single system. J JCL Job Control Language. A scripting language used on IBM mainframe operating systems to instruct the Job Entry Subsystem (that is, JES2 or JES3) how to run a batch program or start a subsystem. JCL is characterized by a pair of slashes // that start each statement. JDBC Java Database Connectivity. An API for the Java programming language that defines how a client may access a database. It provide methods for querying and updating data in a database. JDBC is oriented towards relational databases. JIS Japanese Industrial Standards specify the standards used for industrial activities in Japan. The standardization process is coordinated by Japanese Industrial Standards Committee and published through Japanese Standards Association. join In Teradata SQL, a join is a SELECT operation that allows you to combine columns and rows from two or more tables to produce a result. Join types restricted by DWM are inner join, outer join, merge join, product join, and all joins. For more information, see all joins, exclusion join, inner join, merge join, nested join, and RowId join. M merge join In Teradata SQL, the type of join that occurs when the WHERE conditional of a SELECT statement causes the system first to sort the rows of two tables based on a join field (specified in the statement), then traverse the result while performing a merge/match process. MPP Massively Parallel Processing. An MPP implementation of Teradata consists of multiple SMP nodes that work together. The nodes are connected through the BYNET, a combination of hardware and software that allows the vprocs (PEs and AMPs) to communicate with each other. Teradata is a linearly expandable database system because as additional nodes and vprocs are added, the system capacity scales in a linear fashion. MTDP Micro Teradata Director Program. The Teradata Director Program on networkattached systems. TDP provides a high-performance interface for messages communicated between the client and the Teradata system. It provides the data communications component of the Teradata Database. N nested join In Teradata SQL, this join occurs when the user specifies a field that is a unique primary index on one table and which is in itself an index (unique/non-unique primary or secondary) to the second table. Teradata Preprocessor2 for Embedded SQL Programmer Guide 227

228 Glossary O Object Access filter An Object Access filter allows you to define the criteria for limiting access to issuing objects and/or query objects. Queries that reference objects associated with the rule (either individually or in combination) during the specified dates and times are rejected. Global rules are not applicable for this type. ODBC Open Database Connectivity. An application that may be used by Teradata Tools and Utilities to establish a connection with a Teradata Database. outer join In Teradata SQL, an extension of an inner join operation. In addition to returning qualifying rows from tables joined according to a join condition (the inner join), an outer join returns non-matching rows from one or both of its tables. Multiple tables are joined two at a time. P PDE Parallel Database Extensions. A software layer that runs on the operating system on each node. This additional software layer was created by Teradata to support the parallel environment. PE Parsing Engine. Vprocs that receive SQL requests from the client and break the requests into steps. The PEs send the steps to the AMPs and subsequently return the answer to the client. performance groups A performance group is a collection of parameters used to control and prioritize resource allocation for a particular set of Teradata Database sessions within the Priority Scheduler. Every Teradata Database session is assigned to a performance group during the logon process. Performance groups are the primary consideration in partitioning the working capacity of the Teradata Database. To learn more about performance groups, see the Priority Scheduler section of Utilities. performance periods A threshold or limit value that determines when a session is under the control of that performance period. A performance period links PGs/Teradata Database sessions under its control to an AG that defines a scheduling strategy. A performance period allows you to change AG assignments based on time-of-day or resource usage. PIC Position Independent Code. Object code that can execute at different locations in memory. PIC is commonly used for shared libraries so that the same library code can be mapped to a location in each application (using the virtual memory system) where it won t overlap the application or other shared libraries. PL/I An attempt to combine the best features of Fortran, COBOL and ALGOL 60. Developed by George Radin of IBM in Originally named NPL and Fortran VI. PL/I was one of the first languages to have a formal semantic definition, using the Vienna Definition Language. PL/I has no reserved words. Types are fixed, float, complex, character strings with maximum length, bit strings, and label variables. Arrays have lower bounds and may be dynamic. It also has summation, multi-level structures, structure assignment, un-typed pointers, side effects 228 Teradata Preprocessor2 for Embedded SQL Programmer Guide

229 Glossary and aliasing. Control flow constructs include goto; do-end groups; do-to-by-while-end loops; external procedures; internal nested procedures and blocks; generic procedures and exception handling. Procedures may be declared recursive. Many implementations support concurrency ('call task' and 'wait(event)' are equivalent to fork/join) and compile-time statements. PMPC Performance Monitoring/Production Control is a Teradata Database administrative API. Teradata DWM receives performance group information from PMPC. PP2 Preprocessor2. The preprocessor used to incorporate Structured Query Language (SQL) statements into application programs that access data in a Teradata Database. priority definition set A collection of data that includes the resource partition, performance group, allocation group, performance period type, and other definitions that control how the Priority Scheduler manages and schedules session execution. product join In Teradata SQL, the type of join that occurs when the WHERE conditional of a SELECT statement causes the Teradata Database system to compare all qualifying rows from one table to all qualifying rows from the other table. Because each row of one table is compared to each row of another table, this join can be costly in terms of system performance. Note that product joins without an overall WHERE constraint are considered unconstrained (Cartesian). If the tables to be joined are small, the effect of an unconstrained join on performance may be negligible, but if they are large, there may be a severe negative effect on system performance. profiles A profile is a set of parameters you assign to a user, group of users, or an account that determines what scheduling capabilities are available and how your Teradata Query Scheduler scheduled requests server handles their scheduled requests. Q query analysis A feature that estimates the answer set size (number of rows) and processing time of a SELECT type query. query management The primary function of DWM is to manage logons and queries. This feature examines logon and query requests before they are dispatched for execution within the Teradata Database, and may reject logons, and may reject or delay queries. It does this by comparing the objects referenced in the requests to the types of DBA-defined rules. Query Resource filter A Query Resource filter allows you to define the criteria for limiting resource usage associated with queries. You can define resource criteria such as: Row count Processing time No joins permitted No full table scans permitted Queries that are estimated to meet or exceed the limits for the rule during the specified dates and times are rejected. You may define global rules for this type. QS Query Scheduler. A Teradata tool used to schedule SQL requests. Teradata Preprocessor2 for Embedded SQL Programmer Guide 229

230 Glossary R request A message sent from an application program, such as DWM, to the Teradata Database. In the Teradata Query Scheduler schedule request environment, a request is the definition of the parameters and text associated with a schedule request. resource partition A collection of prioritized PGs related by their users associations. Has an assigned weight that determines the proportion of resources available to that partition relative to the other partitions defined for that Teradata Database. results table/file In the Schedule Request environment, a results table or file is a database table or a Windows file into which result data for a schedule request that is not self-contained are stored. results file storage A symbolic name to a root directory where scheduled requests results are stored. You map a file storage location to a Windows root directory where results are stored. RowID join In Teradata SQL, this join occurs when one of the join tables has a non-unique primary index constant, and another column of that table matches weakly with a non-unique secondary index column of the second table. rule Rules are the name given to the method used by DWM to define what requests are prohibited from being immediately executed on the Teradata Database. That is, the rules enforced by DWM provide the Query Management capabilities. S scheduled requests scheduled later time. The capability to store scripts of SQL requests and execute them at a self-contained statement A query request that stores the result data that it generates, if any. For example, an INSERT/SELECT statement would be self-contained, whereas a SELECT statement would not. SMP Symmetric Multi Processing. An SMP platform consists of a single Teradata node. An SMP system has multiple CPUs that work together. All applications run under a single operating system on the node. The AMPs and PEs on an SMP system communicate through the BYNET software that handles the message queuing and flow control. SQL Structured Query Language. An industry-standard language for creating, updating and, querying relational database management systems. SQL was developed by IBM in the 1970s. It is the de facto standard as well as being an ISO and ANSI standard. It is often embedded in general purpose programming languages. Programming language used to communicate with the Teradata Database. SQLCA SQL Communications Area. A data structure containing a list of return codes and other status information about a completed DML statement. SQLCA provides the following support for embedded SQL applications: result reporting, warning condition reporting, and support for DSNTIAR. See SQL Reference: Stored Procedures and Embedded SQL to learn more. 230 Teradata Preprocessor2 for Embedded SQL Programmer Guide

231 Glossary SQLDA SQL Descriptor Area. A data structure containing a list of individual item descriptors for each of the values produced by a dynamically-performed single row SELECT. An application program needs information (such as the number of columns in a retrieved row, their data types, size, and precision) so it can process values retrieved dynamically at run time. SQL/DS Structured Query Language/Data System. A database package from IBM including a relational database management system. IBM s implementation of SQL available for both mainframes and microcomputers. SQL/DS allows users to store data in a database and retrieve or manipulate that data from programs or interactively using CMS. SSO Single Sign On. T TDP Teradata Director Program. An interface for messages communicated between the client and the Teradata system. TDP transforms headers and parcels into one or more channel blocks and sends the channel blocks over the block multiplexer channel to the Teradata system. It provides the data communications component of the Teradata Database. Every channel-attached client system connected to a Teradata system has at least one TDP associated with it. TDPID Teradata Director Program Identifier. In an MVS and VOS3 environment, a tdpid is a Subsystem ID of four characters; the first three of which are TDP and a fourth that uniquely differentiates TDPs on that system. On VM, the tdpid is the userid of the virtual machine in which that TDP is executing, and is usually named in the same manner as the MVS tdpid. TSO Time Sharing Option. System software from IBM that provides time-sharing on an IBM mainframe running in an MVS environment. U UDF User-Defined Function. A routine that has been defined or programmed by the user of the system and has been included in a standard library of functions. In these cases, "user" typically means programmer, not end user. UTF Universal Transformation Format. A method for converting 16-bit Unicode characters into 7- or 8-bit characters. UTF-7 converts to 7-bit ASCII for transmission over 7-bit mail systems, while UTF-8 converts Unicode to 8-bit bytes. V VM/SP Virtual Machine/System Product. VM has been known as VM/SP (System Product, the successor to CP/67), VM/XA, and currently as VM/ESA (Enterprise Systems Architecture). VM/ESA is still in used in 1999, featuring a web interface, Java, and DB2. It is still a major IBM operating system. VM is an IBM pseudo-operating system hypervisor running on IBM 370, ESA and IBM 390 architecture computers. Teradata Preprocessor2 for Embedded SQL Programmer Guide 231

232 Glossary VS Virtual Storage. An IBM disk file storage scheme first used in S/370 and virtual storage. Both IMS/DB and DB2 are implemented on top of VS and use its underlying data structures. W WD Workload Definition. A set of rules that describes a class of queries. workgroups Workgroups represent collections of related scheduled request work for users, user groups, or accounts. Each workgroup is assigned a maximum number of requests that can be executing from that workgroup simultaneously thereby ensuring that requests for all workgroups get a fair share of their scheduled work done within the execution time frames. workload limits rule A Workload Limits rule allows you to limit the number of logon sessions and all-amp queries, as well as reject or delay queries when workload limits are encountered. You can define which users, accounts, performance groups, or users within performance groups that are associated with this type of rule. Z z/os An enterprise operating system on which to build and deploy Internet and Java-enabled applications, providing a comprehensive and diverse application execution environment. z/vm A test and production environment for enterprises deploying the latest e-business solutions. Built upon the VM/ESA base, z/vm exploits the z/architecture and helps enterprises meet their growing demands for multi-user server solutions with a broad range of support for operating system environments such as z/os, OS/390, TPF, VSE/ESA, CMS, or Linux on zseries. z VM/CMS Conversational Monitor System. An IBM time-sharing and personal computing environment executing under Virtual Machine (VM) in a virtual machine environment. VM/ CMS is designed to support large numbers of interactive users. It relies on numerous APIs into the Control Program (CP) to provide very efficient single-user processing. 232 Teradata Preprocessor2 for Embedded SQL Programmer Guide

233 Index Numerics 2PC defined 223 A accounts defined 223 AIX C applications, linking 208 COBOL applications, linking 210 all joins defined 223 allocation group defined 223 AMP defined 223 AMP worker task defined 223 ANSI defined 223 ANSI SQL -sc, PP2 network options 71 SQLCHECK, PP2 mainframe options 71 API defined 223, 224 application linking AIX, C script 208 AIX, COBOL script 210 HP-UX, C script 208 HP-UX, COBOL script 210 MP-RAS, C script 208 MP-RAS, COBOL script 210 MP-RAS, LPI COBOL script 211 Red Hat Linux, C script 208, 209 SPARC, C script 209 Windows NT/2000, C++ script 211 Windows, C++ script 211 application requirements C 81 COBOL 134 PL/I 169 applications guidelines, linking 203 array support 84, 136, 172 B BIGINT support 84, 135, 171 BTEQ defined 224 BTET defined 224 bypass objects defined 224 C C applications linking, AIX script 208 linking, HP-UX script 208 linking, MP-RAS script 208 linking, Red Hat Linux script 208, 209 linking, SPARC script 209 C++ applications linking, Windows NT/2000 script 211 linking, Windows XP script 211 character sets Chinese 51 international 51 Korean 51 supported 51 Chinese character sets 51 CICS defined 224 CLI2SPB defined 224 client language source code 28 CLIv2 defined 224 COBOL defined 224 COBOL applications linking, AIX script 210 linking, HP-UX script 210 linking, MP-RAS script 210 coding considerations C 84 continuation for SQL statements 85 dynamic SQL 86 format for embedded SQL 84 including code 86 margins 87 Teradata Preprocessor2 for Embedded SQL Programmer Guide 233

234 Index sequence numbers 87 special considerations 89 SQL strings 87 statement labels 87 string delimiters 87 COBOL 136 comments 137 continuation for SQL statements 138 dynamic SQL 138 format for embedded SQL 137 including code 139 paragraph names 139 sequence numbers 139 special considerations 142 string delimiters 140 PL/I comments 173 continuation for SQL statements 173 format for embedded SQL 172 including code 173 macro processor 174 margins 174 sequence numbers 174 special considerations 175 SQL strings 174 statement labels 174 string delimiters 174 communications variables, ANSI-compatible C 83 COBOL 135 PL/I 170 connection to Teradata Database from PP2 35 explicit connection 36 implicit connection 39 runtime execution connection 36 CPU defined 225 create files embedded SQL, network-attached platforms 216 embedded SQL, OS/390 platforms 215 embedded SQL, VM/CMS platforms 217 D data types Teradata Database equivalents COBOL 151 PL/I 183 DBA defined 225 DBC defined 225 DBCAREA defined 225 DBQL defined 225 DBQM defined 225 DCB defined 225 DDL defined 225 diagnostics. See PP2, diagnostics DIT defined 225 DML defined 225 DNS defined 225 E EBCDIC defined 226 embedded SQL macros, LAB6 and LAB7 219 embedded SQL examples platforms 217 z/os JCL 216 EMPLOYEE table 214 data 220 environments mainframe, files 40 error return C ANSI mode 105 SQLCODE variable 105 SQLSTATE variable 106 Teradata mode PPRTEXT 107 SQLCA 106 SQLCODE field 107 COBOL ANSI mode 158 SQLCODE variable 158 SQLSTATE variable 159 Teradata mode PPRTEXT 160 SQLCA 159 SQLCODE field 160 PL/I ANSI mode 188 PPRTEXT 188 SQLCODE variable 188 SQLSTATE variable 188 Teradata mode PPRTEXT 189 SQLCA Teradata Preprocessor2 for Embedded SQL Programmer Guide

235 Index SQLCODE field 189 EUC defined 226 exception conditions, WHENEVER C 108 COBOL 161 PL/I 190 exclusion joins defined 226 EXEC z/vm platforms 217 execution time frames defined 226 G global rules defined 226 glossary 223 GSS defined 226 H host variables C 89 requirements 92 C language 92 C language support 81 declaration 93 indicator variables 93 preprocessor issues 93 SQL 92 values byte string assignment 95 character assignment 96 character string data 97 character string padding 98 character truncation 99 conversion rules 94 date assignment 99 host-to-teradata Database assignment rules 100 numeric assignment 99 single-character data 96 Teradata Database-to-host assignment 94 varying-character data 96 COBOL 142 COBOL structures as input host variables 142 COBOL structures as output host variables 142 declaration Teradata Database data types 151 requirements 145 requirements, preprocessor issues 147 values 147 byte string assignment 149 character string assignment 149 date assignment 149 host-to-teradata Database assignment rules 150 numeric assignment 149 Teradata Database-to-host assignment 148 PL/I 176 declaration Teradata Database data types 183 requirements 178 PL/I language support 169 structures as input/output host variables 176 values byte string assignment 181 character string assignment 181 date assignment 182 host-to-teradata Database assignment rules 182 numeric assignment 181 string truncation 181 Teradata Database-to-host assignment 180 HP-UX C applications, linking 208 COBOL applications, linking 210 HSHSPB defined 226 I I/O defined 227 ID defined 226 IMS defined 226 indicator variables C input 104 output 104 rules 103 structures 105 COBOL input 156 output 156 structures 157 PL/I 185 input 186 output 187 structures 187 inner joins defined 226 integer operations 84, 135, 171 international character sets 51 invoking PP2, z/os 40 Teradata Preprocessor2 for Embedded SQL Programmer Guide 235

236 Index PP2, z/vm 40 J JCL defined 227 z/os platforms, embedded SQL examples 216 JDBC defined 227 JIS defined 227 joins defined 227 K Korean character sets 51 L LAB files location, network-attached platforms 216 location, OS/390 platforms 215 location, VM/CMS platforms 217 LAB6 and LAB7 embedded SQL macros 219 LABs files, setup 214 LABSBTEQ file embedded SQL macros 219 LABSDATA file 220 large decimal support 135, 171 -ld logdata option 62 linking applications, guidelines 203 C applications, AIX 208 C applications, HP-UX 208 C applications, MP-RAS 208 C applications, Red Hat Linux 208, 209 C applications, SPARC 209 C++ applications, Windows NT/ C++ applications, Windows XP 211 COBOL applications, AIX 210 COBOL applications, HP-UX 210 COBOL applications, MP-RAS 210 LPI COBOL applications, MP-RAS 211 -lm logmech option 64 LOGDATA statement 37 LOGGING ONLINE ARCHIVE OFF statement 123, 168, 197 LOGGING ONLINE ARCHIVE ON statement 123, 168, 197 LOGMECH statement 37 logon mechanisms 37 LPI COBOL applications linking, MP-RAS script 211 M macros embedded SQL, LAB6 and LAB7 219 mainframe environments 40 mainframe environments PL/I 169 merge joins defined 227 MPP defined 227 MP-RAS C applications, linking 208 COBOL applications, linking 210 LPI COBOL applications, linking 211 MTDP defined 227 multi-byte character sets graphic literals COBOL 150 PL/I 183 N nested joins defined 227 network-attached environments bit support 44 network-attached platforms create files, embedded SQL 216 LAB files, location 216 O object access rules defined 228 ODBC defined 228 online archive 122, 168, 196 operator messages SQLCODE variable 217 OS/390 platforms create files, embedded SQL 215 LAB files, location 215 outer join defined 228 P PDE defined 228 performance groups defined 228 performance periods defined Teradata Preprocessor2 for Embedded SQL Programmer Guide

237 Index PIC defined 228 PL/I defined 228 PMPC defined 229 PP2 64-bit support 44 COBOL dialects supported 133 defined 229 diagnostics 28 input 26 invocation MVS batch example 40 MVS TSO example 42 NT example 44 UNIX example 44 options mainframe APOST 48 APOSTSQL 49 CHARSET 50 CURPREFIX 56 DATABASE 57 DATE 58 FLAG 60 INPUT 61 LINECOUNT 63 MARGINS 65 NONULLSCAN 66 NOOPTIONS 67 NOPRINT 68 NOPUNCH 69 NOSOURCE 70 NOTERM 74 NOXREF 79 NULLSCAN 66 OPTIONS 67 PRINT 68 PUNCH 69 QUOTE 48 QUOTESQL 49 SOURCE 70 SQLCHECK 71 SQLFLAGGER 72 TERM 74 TRANSACT 75 USERID 77 VERSION 78 XREF 79 network -a 48 -as 49 -c 56 -cs 50 -d 58 -db 57 -e 74 -f 60 -i 61 -l 68 -lc 63 -ld 62 -lm 64 -lo 67 -ls 70 -lx 79 -m 65 -ne 74 -nl 68 -nlo 67 -nls 70 -nlx 79 -nns 66 -no 69 -ns 66 -o 69 -q 48 -qs 49 -sc 71 -sf 72 -tr 75 -u 77 -v 78 output 26 output listing 27 PL/I language support MVS 169 z/vm CMS 169 precompilation 21 programming languages, supported 24 return codes 214 PP2 release number 27 precompilation 21 procedure, overview 203 precompiler definition 21 Preprocessor2 invocation. See PP2, invocation priority definition set defined 229 procedure precompilation 203 product join defined 229 product version numbers 3 profiles defined 229 program status information Teradata Preprocessor2 for Embedded SQL Programmer Guide 237

238 Index ANSI mode C 81 COBOL 134 PL/I 169 Teradata mode C 81 COBOL 134 PL/I 169 Q QS defined 229 query analysis defined 229 query banding 31 query management defined 229 Query Resource filters defined 229 R Red Hat Linux C applications, linking 208, 209 requests defined 230 resource partitions defined 230 results file storage defined 230 results files defined 230 results tables defined 230 RowID joins defined 230 rules defined 230 S scheduled requests defined 230 scripts AIX, linking C applications 208 AIX, linking COBOL applications 210 HP-UX, linking C applications 208 HP-UX, linking COBOL applications 210 MP-RAS, linking C applications 208 MP-RAS, linking COBOL applications 210 MP-RAS, linking LPI COBOL applications 211 Red Hat Linux, linking C applications 208, 209 SPARC, linking C applications 209 Windows NT/2000, linking C++ applications 211 Windows XP, linking C++ applications 211 self-contained statements defined 230 server failure and recovery 28 session query band 31 setting up SQL examples 215 SMP defined 230 software releases supported 3 SPARC C applications, linking 209 SQL defined 230 dynamic, statement example, PL/I 191 embedded, LAB macros 219 error return. See error return SQL examples LABs 213 setting up 215 SQL/DS defined 231 SQLCA 82, 134, 169, 170, 189 defined 230 SQLCODE variable ANSI communications variable C 83 COBOL 135 PL/I 170 operator messages 217 SQLDA defined 231 SQLSTATE variable ANSI communications variable C 83 COBOL 135 PL/I 170 SSO defined 231 T TDP defined 231 TDPID defined 231 Teradata Database release number 27 transaction control 2PC mode 76 ANSI mode 75 BTET mode 76 COMMIT mode 75 transaction query band Teradata Preprocessor2 for Embedded SQL Programmer Guide

239 Index TSO defined 231 U UDF defined 231 universal transformation format 51 UTF defined 231 UTF V version number 3 PP2 27 Teradata Database 27 VM/CMS platforms create files, embedded SQL 217 LAB files, location 217 VM/SP defined 231 VS defined 232 W WD defined 232 WHENEVER. See exception conditions Windows NT 44 Windows NT/2000 C++ applications, linking 211 Windows XP C++ applications, linking 211 workgroups defined 232 workload limits rules defined 232 Z z VM/CMS defined 232 z/os defined 232 invoking PP2 40 z/os platforms JCL, embedded SQL examples 216 z/vm defined 232 invoking PP2 40 z/vm platforms, EXEC 217 Teradata Preprocessor2 for Embedded SQL Programmer Guide 239

240 Index 240 Teradata Preprocessor2 for Embedded SQL Programmer Guide

Teradata Business Intelligence Optimizer. Release Definition

Teradata Business Intelligence Optimizer. Release Definition Teradata Business Intelligence Optimizer Release Definition Release 13.00 B035-4104-099C March 2010 The product or products described in this book are licensed products of Teradata Corporation or its affiliates.

More information

Teradata Tools and Utilities. Installation Guide for Microsoft Windows

Teradata Tools and Utilities. Installation Guide for Microsoft Windows Teradata Tools and Utilities Installation Guide for Microsoft Windows Release 12.00.00 B035-2407-067A December 2007 The product or products described in this book are licensed products of Teradata Corporation

More information

Teradata Business Intelligence Optimizer. Release Definition

Teradata Business Intelligence Optimizer. Release Definition Teradata Business Intelligence Optimizer Release Definition Release 13.01 B035-4104-060C June 2010 The product or products described in this book are licensed products of Teradata Corporation or its affiliates.

More information

Teradata Database. SQL Reference. Stored Procedures and Embedded SQL

Teradata Database. SQL Reference. Stored Procedures and Embedded SQL Teradata Database SQL Reference Stored Procedures and Embedded SQL Release 12.0 B035-1148-067A October 2007 The product or products described in this book are licensed products of Teradata Corporation

More information

Teradata Query Scheduler. User Guide

Teradata Query Scheduler. User Guide Teradata Query Scheduler User Guide Release 14.00 B035-2512-071A November 2011 The product or products described in this book are licensed products of Teradata Corporation or its affiliates. Teradata,

More information

Teradata Manager. User Guide

Teradata Manager. User Guide Teradata Manager User Guide Release 12.0 B035-2428-067A July 2007 The product or products described in this book are licensed products of Teradata Corporation or its affiliates. Teradata, BYNET, DBC/1012,

More information

Teradata SQL Assistant/Web Edition. User Guide

Teradata SQL Assistant/Web Edition. User Guide Teradata SQL Assistant/Web Edition User Guide Release 12.00.00 B035-2505-067A July 2007 The product or products described in this book are licensed products of Teradata Corporation or its affiliates. Teradata,

More information

Teradata SQL Assistant for Microsoft Windows. User Guide

Teradata SQL Assistant for Microsoft Windows. User Guide Teradata SQL Assistant for Microsoft Windows User Guide Release 12.00.00 B035-2430-067A July 2007 The product or products described in this book are licensed products of Teradata Corporation or its affiliates.

More information

Teradata Database. Security Administration

Teradata Database. Security Administration Teradata Database Security Administration Release 13.0 B035-1100-098A November 2009 The product or products described in this book are licensed products of Teradata Corporation or its affiliates. Teradata,

More information

Teradata AWS. User Guide

Teradata AWS. User Guide Teradata AWS User Guide Release 4.5 B035-5220-089A August 2009 The product or products described in this book are licensed products of Teradata Corporation or its affiliates. Teradata, BYNET, DBC/1012,

More information

OpenSSL Heartbleed Vulnerability Fix Procedure for Aster Database Versions 5.0.2x, 5.0.1, 5.0.0 and 4.6.3x

OpenSSL Heartbleed Vulnerability Fix Procedure for Aster Database Versions 5.0.2x, 5.0.1, 5.0.0 and 4.6.3x OpenSSL Heartbleed Vulnerability Fix Procedure for Aster Database Versions 5.0.2x, 5.0.1, 5.0.0 and 4.6.3x Product ID: B700-6070-502K Aster Database version: 5.0.2x, 5.0.1, 5.0.0 and 4.6.3x Summary This

More information

Teradata Workload Analyzer. User Guide

Teradata Workload Analyzer. User Guide Teradata Workload Analyzer User Guide Release 13.10 B035-2514-020A February 2010 The product or products described in this book are licensed products of Teradata Corporation or its affiliates. Teradata,

More information

Teradata Database. Introduction to Teradata Warehouse

Teradata Database. Introduction to Teradata Warehouse Teradata Database Introduction to Teradata Warehouse Release 12.0 B035-1091-067A March 2010 The product or products described in this book are licensed products of Teradata Corporation or its affiliates.

More information

Teradata Database. SQL Reference. Data Types and Literals

Teradata Database. SQL Reference. Data Types and Literals Teradata Database SQL Reference Data Types and Literals Release 12.0 B035-1143-067A November 2009 The product or products described in this book are licensed products of Teradata Corporation or its affiliates.

More information

Teradata Database. Introduction to Teradata

Teradata Database. Introduction to Teradata Teradata Database Introduction to Teradata Release 13.10 B035-1091-109A August 2010 The product or products described in this book are licensed products of Teradata Corporation or its affiliates. Teradata,

More information

Teradata SQL Assistant for Microsoft Windows. User Guide

Teradata SQL Assistant for Microsoft Windows. User Guide Teradata SQL Assistant for Microsoft Windows User Guide Release 14.01 B035-2430-032A March 2012 The product or products described in this book are licensed products of Teradata Corporation or its affiliates.

More information

Teradata Database. Introduction to Teradata

Teradata Database. Introduction to Teradata Teradata Database Introduction to Teradata Release 13.0 B035-1091-098A March 2010 The product or products described in this book are licensed products of Teradata Corporation or its affiliates. Teradata,

More information

Teradata Database. SQL Fundamentals

Teradata Database. SQL Fundamentals Teradata Database SQL Fundamentals Release 13.0 B035-1141-098A March 2010 The product or products described in this book are licensed products of Teradata Corporation or its affiliates. Teradata, BYNET,

More information

Teradata SQL Assistant for Microsoft Windows. User Guide

Teradata SQL Assistant for Microsoft Windows. User Guide Teradata SQL Assistant for Microsoft Windows User Guide Release 14.10 B035-2430-082K February 2013 The product or products described in this book are licensed products of Teradata Corporation or its affiliates.

More information

Teradata Alerts Installation, Configuration, and Upgrade Guide Release 14.10 B035-2211-053K May 2013

Teradata Alerts Installation, Configuration, and Upgrade Guide Release 14.10 B035-2211-053K May 2013 Teradata Alerts Installation, Configuration, and Upgrade Guide Release 14.10 B035-2211-053K May 2013 The product or products described in this book are licensed products of Teradata Corporation or its

More information

Aster Express Getting Started Guide

Aster Express Getting Started Guide Aster Express Getting Started Guide Release Number 6.00 Product ID: B700-6050-600K April 2014 The product or products described in this book are licensed products of Teradata Corporation or its affiliates.

More information

Oracle Business Intelligence Publisher. 1 Oracle Business Intelligence Publisher Certification. Certification Information 10g Release 3 (10.1.3.4.

Oracle Business Intelligence Publisher. 1 Oracle Business Intelligence Publisher Certification. Certification Information 10g Release 3 (10.1.3.4. Oracle Business Intelligence Publisher Certification Information 10g Release 3 (10.1.3.4.2) E12692-08 September 2011 This document outlines the certified hardware and software configurations for Oracle

More information

Appliance Backup Utility Installation and User Guide Release 14.00 B035-3134-121A December 2011

Appliance Backup Utility Installation and User Guide Release 14.00 B035-3134-121A December 2011 Appliance Backup Utility Installation and User Guide Release 14.00 B035-3134-121A December 2011 The product or products described in this book are licensed products of Teradata Corporation or its affiliates.

More information

Symantec Enterprise Security Manager Patch Policy Release Notes

Symantec Enterprise Security Manager Patch Policy Release Notes Symantec Enterprise Security Manager Patch Policy Release Notes Symantec Enterprise Security Manager Patch Policy Release Notes The software described in this book is furnished under a license agreement

More information

Teradata Tools and Utilities for Microsoft Windows Installation Guide Release 14.10 B035-2407-082K March 2013

Teradata Tools and Utilities for Microsoft Windows Installation Guide Release 14.10 B035-2407-082K March 2013 Teradata Tools and Utilities for Microsoft Windows Installation Guide Release 14.10 B035-2407-082K March 2013 The product or products described in this book are licensed products of Teradata Corporation

More information

Version 14.0. Overview. Business value

Version 14.0. Overview. Business value PRODUCT SHEET CA Datacom Server CA Datacom Server Version 14.0 CA Datacom Server provides web applications and other distributed applications with open access to CA Datacom /DB Version 14.0 data by providing

More information

Teradata Data Warehouse Appliance. 2650 Platform. Customer Guide for Hardware Replacement

Teradata Data Warehouse Appliance. 2650 Platform. Customer Guide for Hardware Replacement Teradata Data Warehouse Appliance 2650 Platform Customer Guide for Hardware Replacement B035-5437-080K September 2011 The product or products described in this book are licensed products of Teradata Corporation

More information

DB2 Database Demonstration Program Version 9.7 Installation and Quick Reference Guide

DB2 Database Demonstration Program Version 9.7 Installation and Quick Reference Guide DB2 Database Demonstration Program Version 9.7 Installation and Quick Reference Guide George Baklarz DB2 Worldwide Technical Sales Support IBM Toronto Laboratory DB2 Demonstration Program Version 9.7 Usage

More information

PeopleSoft Customer Relationship Management 9.1 Hardware and Software Requirements Guide

PeopleSoft Customer Relationship Management 9.1 Hardware and Software Requirements Guide PeopleSoft Customer Relationship Management 9.1 Hardware and Software Requirements Guide June 2012 PeopleSoft Customer Relationship Management 9.1 Hardware and Software Requirements Guide SKU crm91hwsw

More information

Teradata Viewpoint. Configuration Guide

Teradata Viewpoint. Configuration Guide Teradata Viewpoint Configuration Guide Release 13.0.1 B035-2207-059A May 2009 The product or products described in this book are licensed products of Teradata Corporation or its affiliates. Teradata, BYNET,

More information

IBM Tivoli Web Response Monitor

IBM Tivoli Web Response Monitor IBM Tivoli Web Response Monitor Release Notes Version 2.0.0 GI11-4068-00 +---- Note ------------------------------------------------------------+ Before using this information and the product it supports,

More information

System Requirements and Platform Support Guide

System Requirements and Platform Support Guide Foglight 5.6.7 System Requirements and Platform Support Guide 2013 Quest Software, Inc. ALL RIGHTS RESERVED. This guide contains proprietary information protected by copyright. The software described in

More information

Veritas Cluster Server Database Agent for Microsoft SQL Configuration Guide

Veritas Cluster Server Database Agent for Microsoft SQL Configuration Guide Veritas Cluster Server Database Agent for Microsoft SQL Configuration Guide Windows 2000, Windows Server 2003 5.0 11293743 Veritas Cluster Server Database Agent for Microsoft SQL Configuration Guide Copyright

More information

Data Sheet VISUAL COBOL 2.2.1 WHAT S NEW? COBOL JVM. Java Application Servers. Web Tools Platform PERFORMANCE. Web Services and JSP Tutorials

Data Sheet VISUAL COBOL 2.2.1 WHAT S NEW? COBOL JVM. Java Application Servers. Web Tools Platform PERFORMANCE. Web Services and JSP Tutorials Visual COBOL is the industry leading solution for COBOL application development and deployment on Windows, Unix and Linux systems. It combines best in class development tooling within Eclipse and Visual

More information

IBM Enterprise Content Management Software Requirements

IBM Enterprise Content Management Software Requirements IBM Enterprise Content Management Software Requirements This document describes the software prerequisite requirements for the IBM Enterprise Content Management suite of products. Last Updated: May 31,

More information

Installation Guide Customized Installation of SQL Server 2008 for an SAP System with SQL4SAP.VBS

Installation Guide Customized Installation of SQL Server 2008 for an SAP System with SQL4SAP.VBS Installation Guide Customized Installation of SQL Server 2008 for an SAP System with SQL4SAP.VBS Target Audience Technology Consultants System Administrators PUBLIC Document version: 1.00 09/16/2008 Document

More information

Oracle Virtual Desktop Client. Release Notes for Release 3.2

Oracle Virtual Desktop Client. Release Notes for Release 3.2 Oracle Virtual Desktop Client Release s for Release 3.2 E36350-03 January 2013 Oracle Virtual Desktop Client: Release s for Release 3.2 Copyright 2013, Oracle and/or its affiliates. All rights reserved.

More information

IBM Lotus Enterprise Integrator (LEI) for Domino. Version 8.5.2. August 17, 2010

IBM Lotus Enterprise Integrator (LEI) for Domino. Version 8.5.2. August 17, 2010 IBM Lotus Enterprise Integrator (LEI) for Domino Version 8.5.2 August 17, 2010 A) What's new in LEI V8.5.2 B) System requirements C) Installation considerations D) Operational considerations E) What's

More information

Data Transfer Tips and Techniques

Data Transfer Tips and Techniques Agenda Key: Session Number: System i Access for Windows: Data Transfer Tips and Techniques 8 Copyright IBM Corporation, 2008. All Rights Reserved. This publication may refer to products that are not currently

More information

StreamServe Persuasion SP5 Supported platforms and software

StreamServe Persuasion SP5 Supported platforms and software StreamServe Persuasion SP5 Supported platforms and software Reference Guide Rev A StreamServe Persuasion SP5 Reference Guide Rev A 2001-2010 STREAMSERVE, INC. ALL RIGHTS RESERVED United States patent #7,127,520

More information

Application Development Guide: Building and Running Applications

Application Development Guide: Building and Running Applications IBM DB2 Universal Database Application Development Guide: Building and Running Applications Version 8 SC09-4825-00 IBM DB2 Universal Database Application Development Guide: Building and Running Applications

More information

Veritas Cluster Server Database Agent for Microsoft SQL Configuration Guide

Veritas Cluster Server Database Agent for Microsoft SQL Configuration Guide Veritas Cluster Server Database Agent for Microsoft SQL Configuration Guide Windows Server 2003, Windows Server 2008 5.1 Veritas Cluster Server Database Agent for Microsoft SQL Configuration Guide Copyright

More information

StorageTek Library Attach for Window Servers

StorageTek Library Attach for Window Servers StorageTek Library Attach for Window Servers Release Notes Version 1.4.3 Part Number: 316138001 May 2010, Revision AA Submit comments about this document by clicking the Feedback [+] link at: http://docs.sun.com

More information

ORACLE GOLDENGATE BIG DATA ADAPTER FOR HIVE

ORACLE GOLDENGATE BIG DATA ADAPTER FOR HIVE ORACLE GOLDENGATE BIG DATA ADAPTER FOR HIVE Version 1.0 Oracle Corporation i Table of Contents TABLE OF CONTENTS... 2 1. INTRODUCTION... 3 1.1. FUNCTIONALITY... 3 1.2. SUPPORTED OPERATIONS... 4 1.3. UNSUPPORTED

More information

Siebel Installation Guide for Microsoft Windows. Siebel Innovation Pack 2013 Version 8.1/8.2, Rev. A April 2014

Siebel Installation Guide for Microsoft Windows. Siebel Innovation Pack 2013 Version 8.1/8.2, Rev. A April 2014 Siebel Installation Guide for Microsoft Windows Siebel Innovation Pack 2013 Version 8.1/8.2, Rev. A April 2014 Copyright 2005, 2014 Oracle and/or its affiliates. All rights reserved. This software and

More information

Backup & Restore with SAP BPC (MS SQL 2005)

Backup & Restore with SAP BPC (MS SQL 2005) How-to Guide SAP CPM How To Backup & Restore with SAP BPC (MS SQL 2005) Version 1.0 September 2007 Applicable Releases: SAP BPC 5.1 Copyright 2007 SAP AG. All rights reserved. No part of this publication

More information

Symantec NetBackup for DB2 Administrator's Guide

Symantec NetBackup for DB2 Administrator's Guide Symantec NetBackup for DB2 Administrator's Guide UNIX, Windows, and Linux Release 7.5 Symantec NetBackup for DB2 Administrator's Guide The software described in this book is furnished under a license agreement

More information

Release Notes. IBM Tivoli Identity Manager Oracle Database Adapter. Version 5.0.1. First Edition (December 7, 2007)

Release Notes. IBM Tivoli Identity Manager Oracle Database Adapter. Version 5.0.1. First Edition (December 7, 2007) IBM Tivoli Identity Manager Version 5.0.1 First Edition (December 7, 2007) This edition applies to version 5.0 of Tivoli Identity Manager and to all subsequent releases and modifications until otherwise

More information

Siebel Installation Guide for UNIX. Siebel Innovation Pack 2013 Version 8.1/8.2, Rev. A April 2014

Siebel Installation Guide for UNIX. Siebel Innovation Pack 2013 Version 8.1/8.2, Rev. A April 2014 Siebel Installation Guide for UNIX Siebel Innovation Pack 2013 Version 8.1/8.2, Rev. A April 2014 Copyright 2005, 2014 Oracle and/or its affiliates. All rights reserved. This software and related documentation

More information

Adobe LiveCycle ES Update 1 System Requirements Adobe LiveCycle ES Foundation-based solution components

Adobe LiveCycle ES Update 1 System Requirements Adobe LiveCycle ES Foundation-based solution components Adobe LiveCycle ES Update 1 System Requirements Adobe LiveCycle ES Foundation-based solution s LiveCycle Barcoded Forms ES LiveCycle e Business Activity ty Monitoring ES LiveCycle Content Services ES LiveCycle

More information

Hitachi Backup Services Manager Certified Configurations Guide 6.5

Hitachi Backup Services Manager Certified Configurations Guide 6.5 Hitachi Backup Services Manager Certified Configurations Guide 6.5 Doc ID:MK-96APT014-02 i ii Chapter 0Preface Thank you for purchasing Hitachi TM Backup Services Manager powered by APTARE. About This

More information

Micro Focus. Data Express. SQL Server Module User Guide

Micro Focus. Data Express. SQL Server Module User Guide Micro Focus Data Express Copyright 2007-2008 Micro Focus (IP) Ltd. All rights reserved. Micro Focus (IP) Ltd. has made every effort to ensure that this book is correct and accurate, but reserves the right

More information

Contents. 2. cttctx Performance Test Utility... 8. 3. Server Side Plug-In... 9. 4. Index... 11. www.faircom.com All Rights Reserved.

Contents. 2. cttctx Performance Test Utility... 8. 3. Server Side Plug-In... 9. 4. Index... 11. www.faircom.com All Rights Reserved. c-treeace Load Test c-treeace Load Test Contents 1. Performance Test Description... 1 1.1 Login Info... 2 1.2 Create Tables... 3 1.3 Run Test... 4 1.4 Last Run Threads... 5 1.5 Total Results History...

More information

HP OpenView AssetCenter

HP OpenView AssetCenter HP OpenView AssetCenter Software version: 5.0 Integration with software distribution tools Build number: 50 Legal Notices Warranty The only warranties for HP products and services are set forth in the

More information

Migrating Non-Oracle Databases and their Applications to Oracle Database 12c O R A C L E W H I T E P A P E R D E C E M B E R 2 0 1 4

Migrating Non-Oracle Databases and their Applications to Oracle Database 12c O R A C L E W H I T E P A P E R D E C E M B E R 2 0 1 4 Migrating Non-Oracle Databases and their Applications to Oracle Database 12c O R A C L E W H I T E P A P E R D E C E M B E R 2 0 1 4 1. Introduction Oracle provides products that reduce the time, risk,

More information

PeopleSoft Financials/Supply Chain Management 9.1 FP2 Hardware and Software Requirements

PeopleSoft Financials/Supply Chain Management 9.1 FP2 Hardware and Software Requirements PeopleSoft Financials/Supply Chain Management 9.1 FP2 Hardware and Software Requirements November 2013 PeopleSoft Financials/Supply Chain Management 9.1 FP2 Hardware and Software Requirements SKU fscm91hwsw_fp2_112013

More information

Tivoli Storage Manager for Databases

Tivoli Storage Manager for Databases Tivoli Storage Manager for Databases Version 5 Release 4 Data Protection for Oracle for UNIX and Linux Installation and User s Guide SC32-9064-03 Tivoli Storage Manager for Databases Version 5 Release

More information

IBM Lotus Protector for Mail Encryption. User's Guide

IBM Lotus Protector for Mail Encryption. User's Guide IBM Lotus Protector for Mail Encryption User's Guide Version Information Lotus Protector for Mail Encryption User's Guide. Lotus Protector for Mail Encryption Version 2.1.0. Released December 2010. This

More information

Unified Infrastructure Management Compatibility Matrix April 4, 2016

Unified Infrastructure Management Compatibility Matrix April 4, 2016 Unified Infrastructure Management Compatibility Matrix April 4, 2016 1 Unified Infrastructure Management Compatibility Matrix- CA Technologies Legal Notices Copyright 2016, CA. All rights reserved. Warranty

More information

IBM Tivoli Remote Control

IBM Tivoli Remote Control Robust remote desktop management across the enterprise IBM Tivoli Remote Control Highlights Enables organizations to Supports Federal Desktop Core remotely manage thousands of Configuration (FDCC) and

More information

User's Guide FairCom Performance Monitor

User's Guide FairCom Performance Monitor User's Guide FairCom Performance Monitor User's Guide FairCom Performance Monitor Contents 1. c-treeace Performance Monitor... 4 2. Startup... 5 3. Using Main Window... 6 4. Menus... 8 5. Icon Row... 11

More information

Oracle Enterprise Manager

Oracle Enterprise Manager Oracle Enterprise Manager System Monitoring Plug-in Installation Guide for Microsoft Active Directory Release 12.1.0.1.0 E28548-04 February 2014 Microsoft Active Directory, which is included with Microsoft

More information

PeopleSoft Financials/Supply Chain Management 9.2 Hardware/Software Requirements Installation (through update Image 5)

PeopleSoft Financials/Supply Chain Management 9.2 Hardware/Software Requirements Installation (through update Image 5) PeopleSoft Financials/Supply Chain Management 9.2 Hardware/Software Requirements Installation (through update Image 5) March 2014 PeopleSoft Financials/Supply Chain Management 9.2 Hardware/Software Requirements

More information

CA Aion Business Rules Expert r11

CA Aion Business Rules Expert r11 PRODUCT sheet: CA AION BUSINESS RULES EXPERT r11 CA Aion Business Rules Expert r11 CA Aion Business Rules Expert r11 (CA Aion BRE) is an industry-leading system that automates and streamlines business

More information

JD Edwards EnterpriseOne Tools. 1 Understanding JD Edwards EnterpriseOne Business Intelligence Integration. 1.1 Oracle Business Intelligence

JD Edwards EnterpriseOne Tools. 1 Understanding JD Edwards EnterpriseOne Business Intelligence Integration. 1.1 Oracle Business Intelligence JD Edwards EnterpriseOne Tools Embedded Business Intelligence for JD Edwards EnterpriseOne Release 8.98 Update 4 E21426-02 March 2011 This document provides instructions for using Form Design Aid to create

More information

Data Access Guide. BusinessObjects 11. Windows and UNIX

Data Access Guide. BusinessObjects 11. Windows and UNIX Data Access Guide BusinessObjects 11 Windows and UNIX 1 Copyright Trademarks Use restrictions Patents Copyright 2004 Business Objects. All rights reserved. If you find any problems with this documentation,

More information

An Oracle White Paper February 2014. Oracle Data Integrator 12c Architecture Overview

An Oracle White Paper February 2014. Oracle Data Integrator 12c Architecture Overview An Oracle White Paper February 2014 Oracle Data Integrator 12c Introduction Oracle Data Integrator (ODI) 12c is built on several components all working together around a centralized metadata repository.

More information

Redpaper. IBM InfoSphere Information Server Installation and Configuration Guide. Front cover. ibm.com/redbooks

Redpaper. IBM InfoSphere Information Server Installation and Configuration Guide. Front cover. ibm.com/redbooks Front cover IBM InfoSphere Information Server Installation and Configuration Guide Pre-installation checklists for a fast start implementation Guidelines for planning and configuring your installation

More information

Smart Plug-in for Siebel

Smart Plug-in for Siebel [SUPPORTED PLATFORMS GUIDE] Siebel SPI Version 04.00 Smart Plug-in for Siebel SUPPORTED PLATFORMS GUIDE This document contains information about all HP Software and Oracle s Siebel products and versions,

More information

How to Install MS SQL Server Express

How to Install MS SQL Server Express How to Install MS SQL Server Express EventTracker v8.x Publication Date: Jun 8, 2016 EventTracker 8815 Centre Park Drive Columbia MD 21045 www.eventtracker.com Abstract This guide helps users to install

More information

Version 8.2. Tivoli Endpoint Manager for Asset Discovery User's Guide

Version 8.2. Tivoli Endpoint Manager for Asset Discovery User's Guide Version 8.2 Tivoli Endpoint Manager for Asset Discovery User's Guide Version 8.2 Tivoli Endpoint Manager for Asset Discovery User's Guide Note Before using this information and the product it supports,

More information

Ontrack PowerControls User Guide Version 7.0. Instructions for Operating Ontrack PowerControls ExtractWizard. An Altegrity Company

Ontrack PowerControls User Guide Version 7.0. Instructions for Operating Ontrack PowerControls ExtractWizard. An Altegrity Company Ontrack PowerControls User Guide Version 7.0 Instructions for Operating Ontrack PowerControls ExtractWizard An Altegrity Company NOTICE TO USERS Ontrack PowerControls is a software application that has

More information

IBM CICS Transaction Gateway for Multiplatforms, Version 7.0

IBM CICS Transaction Gateway for Multiplatforms, Version 7.0 Delivers highly flexible, security-rich and scalable SOA access to CICS applications IBM Multiplatforms, Version 7.0 Highlights Connects WebSphere SOA Introduces real-time monitoring Foundation server

More information

Mimer SQL. Programmer s Manual. Version 8.2 Copyright 2000 Mimer Information Technology AB

Mimer SQL. Programmer s Manual. Version 8.2 Copyright 2000 Mimer Information Technology AB Mimer SQL Version 8.2 Copyright 2000 Mimer Information Technology AB Second revised edition December, 2000 Copyright 2000 Mimer Information Technology AB. Published by Mimer Information Technology AB,

More information

Quick Beginnings for DB2 Servers

Quick Beginnings for DB2 Servers IBM DB2 Universal Database Quick Beginnings for DB2 Servers Version 8 GC09-4836-00 IBM DB2 Universal Database Quick Beginnings for DB2 Servers Version 8 GC09-4836-00 Before using this information and

More information

CA Workload Automation Agent for Databases

CA Workload Automation Agent for Databases CA Workload Automation Agent for Databases Implementation Guide r11.3.4 This Documentation, which includes embedded help systems and electronically distributed materials, (hereinafter referred to as the

More information

Crystal Reports Installation Guide

Crystal Reports Installation Guide Crystal Reports Installation Guide Version XI Infor Global Solutions, Inc. Copyright 2006 Infor IP Holdings C.V. and/or its affiliates or licensors. All rights reserved. The Infor word and design marks

More information

PeopleSoft Enterprise Performance Management 9.1 Revision 1 Hardware and Software Requirements Guide

PeopleSoft Enterprise Performance Management 9.1 Revision 1 Hardware and Software Requirements Guide PeopleSoft Enterprise Performance Management 9.1 Revision 1 Hardware and Software Requirements Guide April, 2012 PeopleSoft Enterprise Performance Management 9.1 Revision 1 Hardware and Software Requirements

More information

IBM Tivoli Monitoring for Databases

IBM Tivoli Monitoring for Databases Enhance the availability and performance of database servers IBM Tivoli Monitoring for Databases Highlights Integrated, intelligent database monitoring for your on demand business Preconfiguration of metric

More information

Deploying Business Objects Crystal Reports Server on IBM InfoSphere Balanced Warehouse C-Class Solution for Windows

Deploying Business Objects Crystal Reports Server on IBM InfoSphere Balanced Warehouse C-Class Solution for Windows Deploying Business Objects Crystal Reports Server on IBM InfoSphere Balanced Warehouse C-Class Solution for Windows I Installation & Configuration Guide Author: Thinh Hong Business Partner Technical Enablement

More information

Oracle Enterprise Manager

Oracle Enterprise Manager Oracle Enterprise Manager System Monitoring Plug-in Installation Guide for Microsoft Internet Information Services Release 12.1.0.2.0 E28547-05 February 2014 This document provides a brief description

More information

1 Review Information About this Guide

1 Review Information About this Guide Oracle Database Client Quick Installation Guide 11g Release 2 (11.2) for Microsoft Windows x64 (64-Bit) E49700-03 December 2014 This guide describes how to quickly install the Oracle Database Client product

More information

SupportPac CB12. General Insurance Application (GENAPP) for IBM CICS Transaction Server

SupportPac CB12. General Insurance Application (GENAPP) for IBM CICS Transaction Server SupportPac CB12 General Insurance Application (GENAPP) for IBM CICS Transaction Server SupportPac CB12 General Insurance Application (GENAPP) for IBM CICS Transaction Server ii General Insurance Application

More information

Symantec NetBackup Enterprise Server and Server 7.x OS Software Compatibility List

Symantec NetBackup Enterprise Server and Server 7.x OS Software Compatibility List Symantec NetBackup Enterprise Server and Server 7.x OS Software Compatibility List Created on December 20, 2013 Copyright 2013 Symantec Corporation. All rights reserved. Symantec, the Symantec Logo, and

More information

HP OpenView Patch Manager Using Radia

HP OpenView Patch Manager Using Radia HP OpenView Patch Manager Using Radia for the Windows and Linux operating systems Software Version: 2.0 Migration Guide February 2005 Legal Notices Warranty Hewlett-Packard makes no warranty of any kind

More information

IBM DB2 Data Archive Expert for z/os:

IBM DB2 Data Archive Expert for z/os: Front cover IBM DB2 Data Archive Expert for z/os: Put Your Data in Its Place Reduce disk occupancy by removing unused data Streamline operations and improve performance Filter and associate data with DB2

More information

etrust Audit Using the Recorder for Check Point FireWall-1 1.5

etrust Audit Using the Recorder for Check Point FireWall-1 1.5 etrust Audit Using the Recorder for Check Point FireWall-1 1.5 This documentation and related computer software program (hereinafter referred to as the Documentation ) is for the end user s informational

More information

Universal File Mover Status Monitor Installation and Operation Manual

Universal File Mover Status Monitor Installation and Operation Manual Universal File Mover Status Monitor Installation and Operation Manual Capitalware Inc. Unit 11, 1673 Richmond Street, PMB524 London, Ontario N6G2N3 Canada [email protected] http://www.capitalware.com

More information

HP Service Manager Compatibility Matrix

HP Service Manager Compatibility Matrix HP Service Manager Compatibility Matrix Software Version 9.21 January 12, 2011 Click one of the following links to see more detailed information. Tier Definitions Servers Applications Support Windows Client

More information

Dell NetVault Backup Plug-in for SQL Server 6.1

Dell NetVault Backup Plug-in for SQL Server 6.1 Dell NetVault Backup Plug-in for SQL Server 6.1 April 2014 These release notes provide information about the Dell NetVault Backup Plug-in for SQL Server release. About Enhancements Resolved issues Known

More information

Linux. Managing security compliance

Linux. Managing security compliance Linux Managing security compliance Linux Managing security compliance Note Before using this information and the product it supports, read the information in Notices on page 7. First Edition (December

More information

Symantec Backup Exec System Recovery Granular Restore Option User's Guide

Symantec Backup Exec System Recovery Granular Restore Option User's Guide Symantec Backup Exec System Recovery Granular Restore Option User's Guide Symantec Backup Exec System Recovery Granular Restore Option User's Guide The software described in this book is furnished under

More information

Symantec NetBackup for Oracle Administrator's Guide

Symantec NetBackup for Oracle Administrator's Guide Symantec NetBackup for Oracle Administrator's Guide UNIX, Windows, and Linux Release 7.5 Symantec NetBackup for Oracle Administrator's Guide The software described in this book is furnished under a license

More information

ODBC Driver User s Guide. Objectivity/SQL++ ODBC Driver User s Guide. Release 10.2

ODBC Driver User s Guide. Objectivity/SQL++ ODBC Driver User s Guide. Release 10.2 ODBC Driver User s Guide Objectivity/SQL++ ODBC Driver User s Guide Release 10.2 Objectivity/SQL++ ODBC Driver User s Guide Part Number: 10.2-ODBC-0 Release 10.2, October 13, 2011 The information in this

More information

Using VMware Player. VMware Player. What Is VMware Player?

Using VMware Player. VMware Player. What Is VMware Player? VMWARE APPLICATION NOTE VMware Player Using VMware Player This document contains the following sections: Work and Play in a Virtual World on page 1 Options and Features in VMware Player on page 4 Installing

More information

Veritas Operations Manager Release Notes. 3.0 Rolling Patch 1

Veritas Operations Manager Release Notes. 3.0 Rolling Patch 1 Veritas Operations Manager Release Notes 3.0 Rolling Patch 1 Veritas Operations Manager Release Notes The software described in this book is furnished under a license agreement and may be used only in

More information

VERITAS NetBackup 6.0 Encryption

VERITAS NetBackup 6.0 Encryption VERITAS NetBackup 6.0 Encryption System Administrator s Guide for UNIX, Windows, and Linux N15274C September 2005 Disclaimer The information contained in this publication is subject to change without notice.

More information

User's Guide c-treeace Status Log Analyzer

User's Guide c-treeace Status Log Analyzer User's Guide c-treeace Status Log Analyzer User's Guide c-treeace Status Log Analyzer Contents 1. Introduction... 4 2. Startup... 5 3. Open a File... 6 4. Using Main Window... 9 4.1 Filtered Event View...

More information

CA Nimsoft Monitor. Probe Guide for NT Event Log Monitor. ntevl v3.8 series

CA Nimsoft Monitor. Probe Guide for NT Event Log Monitor. ntevl v3.8 series CA Nimsoft Monitor Probe Guide for NT Event Log Monitor ntevl v3.8 series Legal Notices Copyright 2013, CA. All rights reserved. Warranty The material contained in this document is provided "as is," and

More information