Manual Informix | Sql | Databases

INFORMIX-4GL

SQL-Based Application Development Language for the UNIX Operating System

Reference Manual

INFORMIX-4GL

Version4.0 March 1990 Part No. 000-7044

THE INFORMIX SOFTWARE AND USER MANUAL ARE PROVIDED ‘‘AS IS’’ WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE INFORMIX SOFTWARE AND USER MANUAL IS WITH YOU. SHOULD THE INFORMIX SOFTWARE AND USER MANUAL PROVE DEFECTIVE, YOU (AND NOT INFORMIX OR ANY AUTHORIZED REPRESENTATIVE OF INFORMIX) ASSUME THE ENTIRE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION. IN NO EVENT WILL INFORMIX BE LIABLE TO YOU FOR ANY DAMAGES, INCLUDING ANY LOST PROFITS, LOST SAVINGS, OR OTHER INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF OR INABILITY TO USE SUCH INFORMIX SOFTWARE OR USER MANUAL, EVEN IF INFORMIX OR AN AUTHORIZED REPRESENTATIVE OF INFORMIX HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY. IN ADDITION, INFORMIX SHALL NOT BE LIABLE FOR ANY CLAIM ARISING OUT OF THE USE OF OR INABILITY TO USE SUCH INFORMIX SOFTWARE OR USER MANUAL BASED UPON STRICT LIABILITY OR INFORMIX’S NEGLIGENCE. SOME STATES DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO THE ABOVE EXCLUSION MAY NOT APPLY TO YOU. THIS WARRANTY GIVES YOU SPECIFIC LEGAL RIGHTS AND YOU MAY ALSO HAVE OTHER RIGHTS, WHICH VARY FROM STATE TO STATE. All rights reserved. No part of this work covered by the copyright hereon may be reproduced or used in any form or by any means—graphic, electronic, or mechanical, including photocopying, recording, taping, or information storage and retrieval systems—without permission of the publisher. Published by: Informix Software, Inc. 4100 Bohannon Drive Menlo Park, CA 94025
INFORMIX and C-ISAM are registered trademarks of Informix Software, Inc. UNIX is a trademark of AT&T. IBM is a registered trademark of the International Business Machines Corporation.

RESTRICTED RIGHTS LEGEND Use, duplication, or disclosure by the Government is subject to restrictions as set forth in subdivision (b)(3)(ii) of the Rights in Technical Data and Computer Software Clause at 52.227-7013 (and any other applicable license provisions set forth in the Government contract).
Copyright © 1981-1990 by Informix Software, Inc. +

ii

Table of Contents

INFORMIX-4GL
Reference Manual
Introduction
About This Manual Intro-3 Related Informix Products and Documentation Database Management Systems Intro-5 Process Architecture Intro-5 Informix Database Engines Intro-6 Summary of Chapters Intro-8 Syntax Conventions Intro-9 The Demonstration Database Intro-11 Chapter 1 Intro-4

Compiling 4GL Source Files Chapter Overview 1-5 The Two Implementations of INFORMIX-4GL 1-5 INFORMIX-4GL (C Compiler Version) 1-7 The Programmer´s Environment (C Compiler Version) 1-7 The INFORMIX-4GL Menu 1-8 The MODULE Design Menu 1-9 The FORM Design Menu 1-14 The PROGRAM Design Menu 1-18 The QUERY LANGUAGE Menu 1-25 Creating Executable 4GL Programs (C Compiler Version) 1-25 Working in the Programmer’s Environment 1-25 Working at the Command Line 1-30 Program Filename Extensions (C Compiler Version) 1-35 INFORMIX-4GL (Rapid Development System) 1-36 The RDS Programmer´s Environment 1-36 The INFORMIX-4GL Menu 1-37 The MODULE Design Menu 1-38 The FORM Design Menu 1-43

The PROGRAM Design Menu 1-48 The QUERY LANGUAGE Menu 1-54 Creating Executable RDS Programs 1-54 Working in the RDS Programmer’s Environment Working at the RDS Command Line 1-59 RDS Program Filename Extensions 1-72 Chapter 2 INFORMIX-4GL Programming Chapter Overview 2-3 Language Conventions 2-3 Comments 2-3 INFORMIX-4GL Identifiers 2-4 Scope of Identifiers 2-4 Constants 2-5 Program Variables 2-6 Data Types 2-7 Data Conversion 2-10 Operators and Expressions 2-11 Binding to Database and Forms 2-14 The THRU Keyword and the .* Notation INFORMIX-4GL Statements 2-16 Variable Definition 2-17 Assignment 2-17 Program Organization 2-17 Program Flow 2-18 Screen Interaction 2-19 Report Generation 2-21 Error and Exception Handling 2-21 Data Validation 2-23 Built-in Functions 2-24 ASCII 2-25 CLIPPED 2-27 COLUMN 2-29 CURRENT 2-30 DATE 2-32 DATE( ) 2-33 DAY( ) 2-34 EXTEND( ) 2-35 LENGTH( ) 2-38 MDY( ) 2-39 MONTH( ) 2-40 TIME 2-41 TODAY 2-42

1-54

2-15

iv Table of Contents

UNITS 2-43 USING 2-44 WEEKDAY( ) 2-53 YEAR( ) 2-54 C Functions 2-55 Chapter 3 Using SQL Chapter Overview 3-5 Relational Databases 3-5 SQL Identifiers 3-6 Owner Naming 3-7 Database Data Types 3-8 SQL Statement Summary 3-10 Data Definition 3-11 Data Manipulation 3-12 Cursor Management 3-13 SELECT Cursors 3-13 INSERT Cursors 3-25 Dynamic Management 3-28 Preparing Statements 3-29 Executing PREPAREd Statements 3-33 Preparing Multiple SQL Statements 3-38 The FREE Statement 3-39 Data Access 3-40 User Status and Privileges 3-41 Data Integrity 3-42 Transactions 3-42 Transaction Log File Maintenance 3-45 Audit Trails 3-45 Comparison of Transactions and Audit Trails Locking 3-47 Row-Level Locking 3-48 Table-Level Locking 3-49 Wait for Locked Row 3-50 Indexing Strategy 3-50 Query Optimizer 3-52 Auto-Indexing 3-52 Clustered Indexes 3-52 NULL Values 3-53 Default Values 3-54 The NULL in Expressions 3-54 The NULL in Boolean Expressions 3-55 The NULL in WHERE Clauses 3-55

3-47

Table of Contents

v

The NULL in ORDER BY Clauses 3-56 The NULL in GROUP BY Clauses 3-56 The NULL Keyword in INSERT and UPDATE Statements Views 3-57 Creating and Deleting Views 3-58 Querying Through Views 3-58 Modifying Through Views 3-59 Privileges with Views 3-60 Data Constraints Using Views 3-60 Outer Joins 3-61 Table Access by ROWID 3-62 SQLCA Record 3-63 TODAY, CURRENT, and USER Functions 3-65 Chapter 4 Form Building and Compiling Chapter Overview 4-3 Structure of a Form Specification File 4-4 DATABASE Section 4-7 SCREEN Section 4-9 TABLES Section 4-15 ATTRIBUTES Section 4-17 AUTONEXT 4-24 COLOR 4-26 COMMENTS 4-28 DEFAULT 4-30 DISPLAY LIKE 4-32 DOWNSHIFT 4-33 FORMAT 4-34 INCLUDE 4-36 NOENTRY 4-38 PICTURE 4-39 REQUIRED 4-41 REVERSE 4-43 UPSHIFT 4-44 VALIDATE LIKE 4-46 VERIFY 4-47 WORDWRAP 4-48 INSTRUCTIONS Section 4-52 Default Screen Attributes 4-57 The upscol Tables in a MODE ANSI Database 4-60 Creating and Compiling a Form 4-61 Through the Programmer’s Environment 4-62 Through the Operating System 4-63 Using PERFORM Forms in INFORMIX-4GL 4-64

3-57

vi Table of Contents

Chapter 5

Report Writing Chapter Overview 5-3 Calling a REPORT Routine 5-4 Structure of a REPORT Routine 5-5 DEFINE Section 5-7 OUTPUT Section 5-9 REPORT TO 5-10 LEFT MARGIN 5-12 RIGHT MARGIN 5-13 TOP MARGIN 5-15 BOTTOM MARGIN 5-16 PAGE LENGTH 5-17 ORDER BY Section 5-18 FORMAT Section 5-20 EVERY ROW 5-21 Control Blocks 5-23 AFTER GROUP OF 5-25 BEFORE GROUP OF 5-27 FIRST PAGE HEADER 5-29 ON EVERY ROW 5-31 ON LAST ROW 5-33 PAGE HEADER 5-34 PAGE TRAILER 5-36 Statements 5-37 NEED 5-38 PAUSE 5-39 PRINT 5-40 PRINT FILE 5-42 SKIP 5-43 Expressions and Built-in Functions Aggregates 5-46 LINENO 5-48 PAGENO 5-49 SPACES 5-50 WORDWRAP 5-51 4GL Function Library Chapter Overview 6-3 The 4GL Library Functions ARG_VAL 6-4 ARR_COUNT 6-6 ARR_CURR 6-7 DOWNSHIFT 6-9

5-44

Chapter 6

6-3

Table of Contents vii

ERR_GET 6-10 ERR_PRINT 6-11 ERR_QUIT 6-12 ERRORLOG 6-13 INFIELD 6-14 LENGTH 6-16 NUM_ARGS 6-17 SCR_LINE 6-18 SET_COUNT 6-20 SHOWHELP 6-21 STARTLOG 6-23 UPSHIFT 6-25 Chapter 7 INFORMIX-4GL Statement Syntax Types of Statements 7-5 Statements Supported Only on INFORMIX-SE 7-6 Statements Supporting INFORMIX-OnLine Enhancements INFORMIX-4GL Extensions to ANSI Syntax 7-7 Definition of Statements 7-11 ALTER INDEX 7-12 ALTER TABLE ( O ) 7-14 BEGIN WORK 7-18 CALL 7-19 CASE 7-21 CLEAR 7-23 CLOSE 7-25 CLOSE DATABASE 7-27 CLOSE FORM 7-28 CLOSE WINDOW 7-30 COMMIT WORK 7-31 CONSTRUCT 7-32 CONTINUE 7-38 CREATE AUDIT 7-39 CREATE DATABASE ( O ) 7-41 CREATE INDEX 7-44 CREATE SYNONYM 7-47 CREATE TABLE ( O ) 7-49 CREATE VIEW 7-57 CURRENT WINDOW 7-60 DATABASE 7-62 DECLARE 7-64 DEFER 7-69 DEFINE 7-71

7-7

viii

Table of Contents

DELETE 7-73 DISPLAY 7-75 DISPLAY ARRAY 7-79 DISPLAY FORM 7-83 DROP AUDIT 7-85 DROP DATABASE 7-86 DROP INDEX 7-88 DROP SYNONYM 7-89 DROP TABLE 7-90 DROP VIEW 7-91 ERROR 7-92 EXECUTE 7-94 EXIT 7-96 FETCH 7-98 FINISH REPORT 7-101 FLUSH 7-102 FOR 7-104 FOREACH 7-106 FREE ( O ) 7-109 FUNCTION 7-110 GLOBALS 7-112 GOTO 7-114 GRANT 7-115 IF 7-118 INITIALIZE 7-120 INPUT 7-122 INPUT ARRAY 7-129 INSERT 7-138 LABEL 7-141 LET 7-142 LOAD 7-143 LOCK TABLE 7-146 MAIN 7-148 MENU 7-149 MESSAGE 7-154 OPEN 7-156 OPEN FORM 7-159 OPEN WINDOW 7-160 OPTIONS 7-165 OUTPUT TO REPORT 7-170 PREPARE 7-171 PROMPT 7-173 PUT 7-177
Table of Contents ix

RECOVER TABLE 7-179 RENAME COLUMN 7-181 RENAME TABLE 7-182 REPORT 7-184 RETURN 7-186 REVOKE 7-187 ROLLBACK WORK 7-189 ROLLFORWARD DATABASE 7-190 RUN 7-191 SCROLL 7-192 SELECT 7-193 SET EXPLAIN 7-194 SET LOCK MODE ( O ) 7-197 SLEEP 7-199 START DATABASE 7-200 START REPORT 7-202 UNLOAD 7-203 UNLOCK TABLE 7-205 UPDATE 7-206 UPDATE STATISTICS 7-210 VALIDATE 7-211 WHENEVER 7-213 WHILE 7-216 The SELECT Statement 7-218 SELECT Clause 7-222 INTO Clause 7-224 FROM Clause 7-226 WHERE Clause 7-228 GROUP BY Clause 7-240 HAVING Clause 7-242 ORDER BY Clause 7-243 INTO TEMP Clause 7-245 UNION Operator 7-246 Functions in SQL Statements 7-248 Aggregate Functions 7-249 LENGTH( ) 7-251 DATE( ) 7-252 DAY( ) 7-253 MDY( ) 7-254 MONTH( ) 7-255 WEEKDAY( ) 7-256 YEAR( ) 7-257 CURRENT 7-258 EXTEND( ) 7-260
x Table of Contents

Appendix A Appendix B Appendix C Appendix D Appendix E Appendix F Appendix G Appendix H Appendix I Appendix J

Demonstration Database and Application System Catalogs Environment Variables Reserved Words INFORMIX-4GL Utility Programs DECIMAL Functions for C Outer Joins ASCII Character Set Modifying termcap and terminfo Working with DATETIME and INTERVAL Data Error Messages Index

Table of Contents xi

xii

Table of Contents

Introduction

Introduction
About This Manual 3 4 Related Informix Products and Documentation Database Management Systems Process Architecture 5 Informix Database Engines Summary of Chapters Syntax Conventions 9 11 8 6 5

The Demonstration Database

2

Introduction

About This Manual
Informix Software, Inc. developed INFORMIX-4GL (Fourth-Generation Application Development Language) for the database designer who wants to create custom database management applications. You can use INFORMIX-4GL to perform the following functions:

• Embed industry-standard database creation and query statements (SQL)
in a fourth-generation language (INFORMIX-4GL).

• Create interactive screen forms that provide an interface between the user
of your application and the database.

• Design output reports to list and summarize database information.
The INFORMIX-4GL language is available in two versions, both of which support a similar user interface:

• The C Compiler Version, based on compiled C code, is intended primarily
for a production environment.

• The Rapid Development System compiles source files into p-code
(pseudo-code) to reduce application development time. Chapter 1 identifies the differences between these two implementations, which mostly involve details of processing INFORMIX-4GL source files. Documentation for INFORMIX-4GL includes this and one other volume. An introductory book, the INFORMIX-4GL User Guide, presents both SQL and INFORMIX-4GL in stages, through example 4GL programs that increase in sophistication and subtlety. This book, the INFORMIX-4GL Reference Manual, describes all the syntax, rules, and definitions of the variables, statements, and keywords. Another section of this Introduction summarizes each chapter and appendix of the Reference Manual. Besides these manuals, the INFORMIX-4GL Quick Reference Guide lists the data types, operations, functions, and syntax of INFORMIX-4GL.

Introduction

3

Related Informix Products and Documentation

Related Informix Products and Documentation
This manual assumes that you have used INFORMIX-4GL and are familiar with the structure of relational databases. Readers with programming experience using INFORMIX-SQL or INFORMIX-ESQL/C will recognize old friends in a new setting. You can read about INFORMIX-SQL in the INFORMIX-SQL Reference Manual, and about INFORMIX-ESQL/C in the INFORMIX-ESQL/C Programmer’s Manual. The INFORMIX-4GL Interactive Debugger is a separate product designed for use with the INFORMIX-4GL Rapid Development System. This sourcelanguage debugger is useful when you are developing or modifying 4GL programs, or analyzing a 4GL program that someone else has written. The INFORMIX-4GL Interactive Debugger is described in the Guide to the INFORMIX-4GL Interactive Debugger. Like the INFORMIX-4GL Rapid Development System, the Debugger does not require a C-compiler, unless your application calls INFORMIX-ESQL/C functions or programmer-defined C functions. The underlying file and indexing structure of the database tables created through INFORMIX-4GL, INFORMIX-SQL, or INFORMIX-ESQL/C is built on C-ISAM. For more information about this indexed sequential access method, see the C-ISAM Programmer’s Manual. See also the section ‘‘Related Reading’’ in the Preface to the INFORMIX-4GL User Guide for a selected bibliography on programming in fourth-generation languages like INFORMIX-4GL. You can use INFORMIX-4GL with the INFORMIX-OnLine database engine, which supports enhanced system performance through the use of direct memory access (DMA) and raw file systems. Use of the INFORMIX-OnLine database engine with INFORMIX-4GL and other SQL products is described in the INFORMIX-OnLine Programmer’s Manual. The section ‘‘Informix Database Engines,’’ later in this Introduction, identifies additional INFORMIX-4GL features that are available only with INFORMIX-OnLine. Note: Two files supplement the information in the manual. RELNOTES describes performance differences from earlier versions of Informix products and how these differences may affect existing applications. DOCNOTES describes feature and performance topics not covered in the manual or modified since publication. Please examine these files as they contain vital information about application and performance issues. RELNOTES and DOCNOTES are located in the $INFORMIXDIR/release directory.

4

Introduction

Database Management Systems

Database Management Systems
A Database Management System (DBMS) can be divided into two parts as follows:

• A data language, which is the user interface to the DBMS • A database engine, which takes the data definition and data manipulation
language requests and performs the requested operations Database users instruct database management systems to perform queries and other operations on a database using language the DBMS understands. There are two such languages, data definition and manipulation languages, because the user must define the contents of a database and manipulate the data. These languages are often called, simply, data languages. The DBMS must understand these languages and translate the user instructions into appropriate instructions for the operating system and hardware. As a result of user instructions, the DBMS requests services such as allocation of space, storage and retrieval of blocks of data, and much more. The database engine operates as a process, an executing program. Database engines serve other processes, which are database applications. These applications contain the language statements that the database engine executes. Informix products use a database definition and manipulation language that is an extension of the ANSI standard SQL to send instructions to the database engine.

Process Architecture
A database engine performs SQL operations. The database engine is a process that handles storage and retrieval of data and other DBMS functions. The following figure shows this implementation for products on INFORMIX-SE.
MULTIPLE PROCESSES

INFORMIX-4GL

Pipes

INFORMIX-SE INFORMIX-SE INFORMIX-SE INFORMIX-ESQL
In Host Language

Fi Acc le ess

INFORMIX-SQL

Data

C-ISAM

Introduction

5

Informix Database Engines

Processes that use the database engine are implemented as applications in the following ways:

• With an embedded language, such as INFORMIX-ESQL/C or INFORMIX-ESQL/COBOL

• With a fourth-generation language, such as INFORMIX-4GL • As part of an interactive retrieval system, such as INFORMIX-SQL
INFORMIX-SE uses C-ISAM to store and retrieve data from the disk.

A database application spawns at least two processes: the database engine process and the application process. While the database engine is often thought of as a single entity, it is actually made up of one process for each application process. This one-to-one relationship between application and database process allows the engine to respond immediately to a specific application, rather than queuing requests from all applications that need service. The database engine and application communicate using pipes.

Informix Database Engines
You can use INFORMIX-4GL or any Informix application development tool with either of two database engines: INFORMIX-SE or INFORMIX-OnLine.
INFORMIX-SE is based on C-ISAM, a library of C language calls that works with UNIX to create and manipulate database files. INFORMIX-SE works

automatically and transparently, and it does not require any special instructions in your programs. Its easy setup and use make INFORMIX-SE an ideal engine for developing small- to medium-size applications that do not require maximum performance nor an extensive range of data-integrity options.
INFORMIX-OnLine is a transaction-processing database engine that manages I/O operations directly so that performance is maximized. It is designed to handle the high performance requirements and integrity concerns of many large applications. Most applications can run on either engine because few differences affect the programmer. INFORMIX-OnLine, however, provides features that increase performance, extend available data types, and improve the administrative aspects of database management. The following features are available only with INFORMIX-OnLine:

• Raw I/O and optimized shared memory for greater performance • High availability and automatic recovery • Increased locking and process isolation options for greater integrity
control

6

Introduction

Informix Database Engines

• • • •

Variable-length character data (VARCHARs) Binary Large OBjects (BLOBs) that can be any type or amount of data Distributed query capability across multiple databases Distributed query capability across multiple INFORMIX-OnLine systems, if you have the INFORMIX-STAR add-on product.

INFORMIX-OnLine can substantially improve application performance by using direct I/O to raw storage devices, and by tuning shared memory for maximum efficiency. INFORMIX-OnLine offers high data availability, which allows rapid recovery from system failures and provides you with logging choices, including the option of disk mirroring. INFORMIX-OnLine provides advanced concurrency control by allowing you to set the level of locking granularity and the level of user process isolation. INFORMIX-OnLine supports three additional data types not available with INFORMIX-SE. VARCHARs are variable-length character columns (up to 255 bytes) that use disk space only as it is needed. The TEXT and BYTE data types are Binary Large OBjects (BLOBs) capable of holding virtually any type or amount of data. TEXT can store ASCII text files with embedded control characters, such as documents generated through a word processor. BYTE can store any type of binary data, such as spreadsheets, program load modules, digitized images, or voice patterns. INFORMIX-OnLine allows access to multiple databases on the same computer. You can write applications that retrieve data from multiple tables, even if the tables reside in different databases. You can use the combined data for general display purposes or as input to a customized report. INFORMIX-STAR is an optional add-on product to INFORMIX-OnLine that allows you access to multiple INFORMIX-OnLine systems. With INFORMIX-STAR you can write queries that span multiple databases in different INFORMIX-OnLine systems across a network.

This manual provides you with information on how to use INFORMIX-4GL with INFORMIX-SE. If you are planning to use INFORMIX-OnLine, refer to the INFORMIX-OnLine Programmer’s Manual for information about programming issues. Notes are placed at appropriate locations in this manual to help clarify where INFORMIX-OnLine can provide additional functionality.

Introduction

7

Summary of Chapters

Summary of Chapters
The INFORMIX-4GL Reference Manual is divided into the following chapters and appendices: Introduction briefly describes the INFORMIX-4GL documentation, notational conventions used in syntax statements, and the demonstration database. describes the C Compiler and Rapid Development System implementations of INFORMIX-4GL. It also explains how to create executable versions of 4GL source files, both from the Programmer’s Environment and at the command line. gives the rules for programming in INFORMIX-4GL. It defines data types and binding of program variables, describes expressions and functions, and explains error handling and the interrelationships among all the INFORMIX-4GL statements. describes how to interact with databases by using the Informix extension to IBM’s Structured Query Language (SQL). This chapter also explains the interrelationships among various types of SQL statements and illustrates the use of the 4GL Programmer’s Environment. describes the procedures to construct and compile 4GL screen form specifications. describes the procedures to specify and produce 4GL reports. describes the functions in the INFORMIX-4GL library.

Chapter 1

Chapter 2

Chapter 3

Chapter 4 Chapter 5 Chapter 6

8

Introduction

Syntax Conventions

Chapter 7

contains an alphabetized description of each of the SQL and INFORMIX-4GL statements that you can use in an INFORMIX-4GL program. Use this chapter as a reference for syntax and rules concerning the use of these statements. describes the stores demonstration database. describes the system catalog tables that form the data dictionary of an INFORMIX-4GL database. describes the environment variables that are used by INFORMIX-4GL.

Appendix A Appendix B Appendix C Appendix D Appendix E

lists the reserved words of INFORMIX-4GL. describes the bcheck, dbload, dbexport, dbimport, dbschema, dbupdate, mkmessage, sqlconv, and upscol utility programs. contains descriptions of C functions that handle DECIMAL type variables in C programs. amplifies the Chapter 3 discussion of outer joins. lists the ASCII characters in order. describes modifications that you can make to your termcap and terminfo files to extend function key definitions, to specify characters for window borders, and to enable INFORMIX-4GL programs to interact with terminals that support color displays. describes how you can use the DATETIME and INTERVAL data types.

Appendix F Appendix G Appendix H Appendix I

Appendix J

Error Messages contains an extensive listing of error codes, explains their meaning, and suggests remedies for correcting the errors. Index is an alphabetic list of page references for selected 4GL topics in this manual and in its companion, the INFORMIX-4GL User Guide.

Syntax Conventions
This section explains how to interpret the listings of statement syntax that appear throughout this manual.

Introduction

9

Syntax Conventions

ABC

Enter any term that appears in uppercase letters exactly as shown, disregarding case. Such terms are ‘‘keywords.’’ For example,
CREATE INDEX indname means you must enter CREATE INDEX or create index without adding or deleting spaces or letters.

abc

Substitute a value for any term that appears in lowercase italic letters. In the previous example, you should substitute a value for indname. In each statement description in Chapter 7, the section ‘‘Explanation’’ describes what values you can substitute for italicized terms. Enter parentheses as shown. They are part of the syntax of a statement, not special symbols. Unless advised otherwise, do not enter brackets as part of a statement, since they surround any part of a statement that is optional. For example,
CREATE [ UNIQUE ] INDEX

() []

indicates that you can enter either CREATE INDEX or CREATE UNIQUE INDEX. | Select one of the options shown. The vertical bar indicates a choice among several options. For example,
[ ONE | TWO [ THREE ] | FOUR ]

means that you can enter ONE or TWO or FOUR , and that, if you enter TWO, you can also enter THREE. (Because all the choices are enclosed in square brackets, you can also choose to omit them completely.) {} Choose one of the listed options. When the options are enclosed in braces and separated by vertical bars, you must select one of the options. For example,
{ ONE | TWO | THREE }

means that you must enter ONE or TWO or THREE, and that you cannot enter more than one selection. Unless advised otherwise, do not enter braces in a statement. ABC Omit or use an option that is underlined. When one of several options is the default option, it appears underlined. For example:
[ CHOCOLATE | VANILLA | STRAWBERRY ]

means that you can select any of the three options, but that if you do not enter any of them, VANILLA is the default.

10

Introduction

The Demonstration Database

...

Enter additional items like those preceding the ellipsis, if you want. The ellipsis indicates that the immediately preceding item can be repeated indefinitely. For example, statement
...

means that there can be a series of statements following the one that is listed. Do not enter ellipsis symbols in a statement or program, unless you want to enter them as literal string values. Enter all other symbols, such as - / ; > . = ’ % : * " and , exactly as they appear in the syntax statement. The notation ‘‘(O)’’ sometimes follows the name of a statement at the beginning of a syntax description in Chapter 7. This means that additional options or features are supported by INFORMIX-4GL on the INFORMIX-OnLine database engine. Refer to the INFORMIX-OnLine Programmer’s Manual for details of the additional functionality available with INFORMIX-OnLine.

The Demonstration Database
Most of the examples in this manual are based on the stores demonstration database. This database, which is described and listed in detail in Appendix A, involves a wholesale sporting goods firm that maintains a stock of equipment and fills orders to retailers. You can create the stores database in the current directory by entering i4gldemo (if you have the INFORMIX-4GL C Compiler Version) or by entering r4gldemo (if you have the INFORMIX-4GL Rapid Development System). Each shell script removes any database labeled stores and installs the demonstration database. The stores database contains six tables: customer orders items stock contains information about the retail stores that purchase sporting supplies. contains information about the individual orders from the retail stores. contains information about the items in an order. contains information about the variety of sporting goods available.
Introduction 11

The Demonstration Database

manufact state

contains information about manufacturers of sporting goods. contains the names and abbreviations of U.S. states.

Note: The stores demonstration database includes additional system catalogs and the source code modules of several INFORMIX-4GL application programs.

12

Introduction

Chapter

1
Compiling 4GL Source Files
Chapter Overview 5 The Two Implementations of INFORMIX-4GL INFORMIX-4GL (C Compiler Version) 7 7 5 The Programmer´s Environment (C Compiler Version) The INFORMIX-4GL Menu 8 The MODULE Design Menu 9 The Modify Option 9 The New Option 12 The Compile Option 12 The Program_Compile Option 13 The Run Option 13 The Exit Option 14 The FORM Design Menu 14 The Modify Option 15 The Generate Option 16 The New Option 17 The Compile Option 17 The Exit Option 18 The PROGRAM Design Menu 18 The Modify Option 19 The New Option 22 The Compile Option 22 The Planned_Compile Option 23 The Run Option 24 The Drop Option 24 The Exit Option 24 The QUERY LANGUAGE Menu 25

Creating Executable 4GL Programs (C Compiler Version) 25 Working in the Programmer’s Environment 25 Creating a New Source Module 26 Revising an Existing Module 26 Compiling a Source Module 27 Linking Program Modules 28 Executing a Compiled Program 30 Working at the Command Line 30 Creating or Modifying a 4GL Source File 31 Compiling a 4GL Module 31 Compiling and Linking Multiple Source Files 32 Running 4GL Programs 34 4GL Programs That Call C Functions 34 Program Filename Extensions (C Compiler Version) INFORMIX-4GL (Rapid Development System) The RDS Programmer´s Environment 36 The INFORMIX-4GL Menu 37 The MODULE Design Menu 38 The Modify Option 39 The New Option 41 The Compile Option 41 The Program_Compile Option 41 The Run Option 42 The Debug Option 42 The Exit Option 43 The FORM Design Menu 43 The Modify Option 44 The Generate Option 46 The New Option 46 The Compile Option 47 The Exit Option 47 The PROGRAM Design Menu 48 The Modify Option 49 The New Option 51 The Compile Option 51 The Planned_Compile Option 52 The Run Option 52 The Debug Option 53 The Undefine Option 53 The Exit Option 53 The QUERY LANGUAGE Menu 54
1-2 Compiling 4GL Source Files

35

36

Creating Executable RDS Programs 54 Working in the RDS Programmer’s Environment 54 Creating a New Source Module 55 Revising an Existing Module 55 Compiling a Source Module 56 Combining Program Modules 57 Executing a Compiled RDS Program 58 Invoking the Debugger 59 Working at the RDS Command Line 59 Creating or Modifying a 4GL Source File 61 Compiling an RDS Source File 61 Concatenating Multi-Module Programs 63 Running RDS Programs 64 Running Multi-Module Programs 65 Running Programs with the Interactive Debugger RDS Programs That Call C Functions 66 Editing the fgiusr.c File 67 Creating a Customized Runner 69 Running Programs That Call C Functions 72 RDS Program Filename Extensions 72

65

Compiling 4GL Source Files

1-3

1-4

Compiling 4GL Source Files

Chapter Overview
This chapter describes how to create INFORMIX-4GL source-code modules, and how to produce executable 4GL programs from these source-code modules, both at the operating system prompt and from within the INFORMIX-4GL Programmer’s Environment. The procedures to do this are described for the INFORMIX-4GL C Compiler Version, as well as for the INFORMIX-4GL Rapid Development System. These two implementations of INFORMIX-4GL differ in how they process 4GL source-code modules.

The Two Implementations of INFORMIX-4GL
To write an INFORMIX-4GL program, you must first create an ASCII file of 4GL statements that perform logical tasks to support your application. Other chapters and appendixes describe the features of the INFORMIX-4GL application development language, and the use and syntax of its statements and utilities. This chapter explains the procedures by which you can transform one or more source-code files of INFORMIX-4GL statements into an executable 4GL program. Informix Software, Inc., offers two different implementations of the INFORMIX-4GL application development language:

• The INFORMIX-4GL C Compiler Version, which uses a preprocessor to
generate INFORMIX-ESQL/C source code. This code is preprocessed in turn to produce C source code, which is then compiled and linked as object code in an executable command file.

• The INFORMIX-4GL Rapid Development System, which uses a compiler
to produce pseudo-code (called ‘‘p-code’’) in a single step. You then invoke a ‘‘runner’’ to execute the p-code version of your application. (The INFORMIX-4GL Rapid Development System is sometimes abbreviated as RDS.)

Compiling 4GL Source Files

1-5

The Two Implementations of INFORMIX-4GL

Both implementations use the same INFORMIX-4GL statements, and nearly identical Programmer’s Environments. Because they use different methods to compile your 4GL source files into executable programs, however, there are a few differences in the user interfaces. These differences are summarized on this page and the next:

• Differences in Command Lines
Compiler RDS Effect of Command

i4gl r4gl Enter Programmer’s Environment c4gl sfile.4gl fglpc sfile Compile 4GL source file sfile.4gl xfile.4ge fglgo xfile Execute compiled 4GL program xfile i4gldemo r4gldemo Create the demonstration database The INFORMIX-4GL C Compiler Version requires no equivalent to the fglgo command, since its compiled object files are executable without a runner. The INFORMIX-4GL Rapid Development System also contains a command-file script to compile and execute 4GL programs that call C functions or INFORMIX-ESQL/C functions, as described near the end of this chapter.

• Differences in the Programmer’s Environment
The Programmer’s Environment is a system of menus that supports the various steps in the process of developing 4GL application programs. The Drop option on the PROGRAM Design Menu of the C Compiler Version is called Undefine in the INFORMIX-4GL Rapid Development System implementation. The New and Modify options of the PROGRAM Design Menu display a different screen form in the two implementations. Both of these screen forms are illustrated later in this chapter. The INFORMIX-4GL Rapid Development System includes a Debug option on its MODULE Design Menu and PROGRAM Design Menu. This option does not appear in the C Compiler Version. (The Debugger is based on p-code, so it can execute programs and modules compiled by the INFORMIX-4GL Rapid Development System). The INFORMIX-4GL Interactive Debugger is available as a separate product.

• Differences in Filename Extensions
Compiler .o .4ge RDS .4go .4gi Significance of Extension Compiled 4GL source-code module Executable (runable) 4GL program file

The backup file extensions .4bo and .4be for compiled modules and programs have the same names in both implementations. These
1-6 Compiling 4GL Source Files

INFORMIX-4GL (C Compiler Version)

designate files that are not interchangeable between the two 4GL implementations, however, because object code produced by a C compiler is different from p-code. Other filename extensions that are the same in both the C Compiler Version and Rapid Development System Version designate interchangeable files, if you use both implementations of INFORMIX-4GL to process the same 4GL source-code module.

INFORMIX-4GL (C Compiler Version)
The rest of this chapter describes in detail both implementations of INFORMIX-4GL. For each implementation, this chapter presents the following information:

• It identifies and illustrates all the menu options and screen form fields
of the Programmer’s Environment.

• It describes the steps for compiling and executing INFORMIX-4GL
programs from the Programmer’s Environment.

• It describes the equivalent command-line syntax for compiling and
executing INFORMIX-4GL programs.

• It identifies the filename extensions of 4GL source-code, object, error,
and backup files. The INFORMIX-4GL C Compiler Version is described first. If you have the INFORMIX-4GL Rapid Development System, skip ahead to the section entitled “The RDS Programmer´s Environment” near the middle of this chapter.

The Programmer´s Environment (C Compiler Version)
The INFORMIX-4GL C Compiler Version provides a series of nested menus, called the Programmer’s Environment. These menus support the steps of 4GL program development and keep track of the components of your application. You can invoke the Programmer’s Environment by entering i4gl at the system prompt.

Compiling 4GL Source Files

1-7

The INFORMIX-4GL Menu

The INFORMIX-4GL Menu
The i4gl command briefly displays the INFORMIX-4GL banner. Then a menu appears, called the INFORMIX-4GL Menu:
INFORMIX-4GL: Module Form Program Query-language Exit Create, modify, or run individual 4GL program modules. -------------------------------------------------Press CTRL-W for Help------

This is the highest menu, from which you can reach any other menu of the Programmer’s Environment. You have five options: Module Form Program Query-language Exit Work on an INFORMIX-4GL program module. Work on a screen form. Specify components of a multi-module program. Use the SQL interactive interface, if you have INFORMIX-SQL installed on your system. Return to the operating system.

The first three options display new menus that are described in the pages that follow. (You can also press CTRL-W at any menu to display an on-line help message that describes your options.) As at any 4GL menu, you can select an option in either of two ways:

• By typing the first letter of the option, or • By using the SPACEBAR or Arrow keys to move the highlight to the option
that you choose, and then pressing RETURN.

1-8

Compiling 4GL Source Files

The MODULE Design Menu

The MODULE Design Menu
You can press RETURN or type m or M to select the Module option of the INFORMIX-4GL Menu. This displays a new menu, called the MODULE Design Menu. Use this menu to work on an individual 4GL source-code module.
MODULE: Modify New Compile Program_Compile Change an existing 4GL program module. Run Exit

-------------------------------------------------Press CTRL-W for Help------

The MODULE Design Menu supports the following options: Modify New Compile Program_Compile Run Exit Change an existing 4GL source-code module. Create a new 4GL source-code module. Compile a 4GL source-code module. Compile a 4GL application program. Execute a compiled 4GL program module or a multimodule application program. Return to the INFORMIX-4GL Menu.

As in all of the menus of the Programmer’s Environment except the INFORMIX-4GL Menu, the Exit option returns control to the higher menu from which you accessed the current menu. You can use these options to create and compile source-code modules of a 4GL application. See “The FORM Design Menu” later in this chapter for information on creating 4GL screen forms. See also “The mkmessage Utility” section in Appendix E for information on how to create and compile programmer-defined help messages for an INFORMIX-4GL application.

The Modify Option
Select this option to edit an existing 4GL source-code module. If you select this option, INFORMIX-4GL requests the name of the 4GL source-code file to be modified and then prompts you to specify a text editor. If you have designated an editor with the DBEDIT environment variable

Compiling 4GL Source Files

1-9

The MODULE Design Menu

(see Appendix C) or named an editor previously in this session at the Programmer’s Environment, INFORMIX-4GL invokes that editor. The 4GL source file whose filename you specified is the current file. When you leave the editor, INFORMIX-4GL displays the MODIFY MODULE Menu, with the Compile option highlighted:
MODIFY MODULE: Compile Save-and-exit Compile the 4GL module specification. Discard-and-exit

-------------------------------------------------Press CTRL-W for Help------

If you press RETURN or type c or C to select the Compile option, INFORMIX-4GL displays the COMPILE MODULE Menu:
COMPILE MODULE: Object Runable Exit Create object file only; no linking to occur. -------------------------------------------------Press CTRL-W for Help------

The Object option creates a compiled file with the .o extension but makes no attempt to link the file with other files. The Runable option creates a compiled file with the .4ge extension. INFORMIX-4GL assumes that the current module is a complete 4GL program, and that no other module needs to be linked to it. Select the Runable option if the current program module is a stand-alone 4GL program. If this is not the case, (that is, if the file is one of several 4GL source-code modules within a multimodule program), then you should use the Object option instead, and you must use the PROGRAM Design menu to specify all the component modules. After you select Object or Runable, a message near the bottom of the screen will advise you if INFORMIX-4GL issues a compile-time warning or error. If there are warnings (but no errors), an executable file is produced. Select the

1-10

Compiling 4GL Source Files

The MODULE Design Menu

Exit option of the next menu, and then Save-and-exit at the MODIFY MODULE Menu, if you want to save the executable file without reading the warnings. Alternatively, you can examine the warning messages by selecting Correct at the next menu. When you finish editing the .err file that contains the warnings, you must select Compile again from the MODIFY MODULE Menu, since the Correct option deletes the executable file. If there are compilation errors, the following menu appears:
COMPILE MODULE: Correct Exit Correct errors in the 4GL module. -------------------------------------------------Press CTRL-W for Help------

If you choose to correct the errors, an editing session begins on a copy of your source module with embedded error messages. You do not need to delete the error messages, since INFORMIX-4GL does this for you. Correct your source file, save your changes, and exit from the editor. The MODIFY MODULE Menu reappears, prompting you to recompile, or to save or discard your changes without compiling. If there are no compilation errors, the MODIFY MODULE Menu appears with the Save-and-Exit option highlighted. Select this option to save the current source-code module as a file with extension .4gl, and create an object file with the same filename, but with the extension .o. If you specified Runable when you compiled, the executable version is saved with the extension .4ge. The Discard-and-Exit option discards any changes to your file since you selected the Modify option.

Compiling 4GL Source Files 1-11

The MODULE Design Menu

The New Option
Select this option to create a new 4GL source-code module.
MODULE: Modify New Compile Program_Compile Create a new 4GL program module. Run Exit

-------------------------------------------------Press CTRL-W for Help------

This option resembles the Modify option, but NEW MODULE is the menu title, and you must enter a new module name, rather than select it from a list. If you have not designated an editor previously in this session or with DBEDIT, you are prompted for an editor. Then an editing session begins.

The Compile Option
The Compile option enables you to compile an individual 4GL source-code module without first selecting the Modify option.
MODULE: Modify New Compile Program_Compile Compile an existing 4GL program module. Run Exit

-------------------------------------------------Press CTRL-W for Help------

After you specify the name of a 4GL source-code module to compile, the screen displays the COMPILE MODULE Menu. Its Object, Runable, and Exit options were described earlier in the discussion of the Modify option.

1-12

Compiling 4GL Source Files

The MODULE Design Menu

The Program_Compile Option
The Program_Compile option of the MODULE Design Menu is the same as the Compile option of the PROGRAM Design Menu. (See that option for details.) You can use this option to compile and link modules, as described in the program specification database, taking into account the time when the modules were last updated. This option is useful when you have just modified a single module of a complex program, and need to test it by compiling and linking it with the other modules.

The Run Option
Select this option to begin execution of a compiled program.
MODULE: Modify New Compile Program_Compile Run Exit Execute an existing 4GL program module or application program. -------------------------------------------------Press CTRL-W for Help------

The RUN PROGRAM screen presents a list of compiled modules and programs, with the highlight on the module corresponding to the current file, if any has been specified. Compiled programs must have the extension .4ge to be included in the list. If you compile a program outside the Programmer’s Environment and you want it to appear in the program list, give it the extension .4ge. If no compiled programs exist, INFORMIX-4GL displays an error message and restores the MODULE Design Menu.

Compiling 4GL Source Files

1-13

The FORM Design Menu

The Exit Option
Select this option to exit from the MODULE Design Menu and display the INFORMIX-4GL Menu.
MODULE: Modify New Compile Program_Compile Returns to the INFORMIX-4GL Menu. Run Exit

-------------------------------------------------Press CTRL-W for Help------

The FORM Design Menu
You can type f or F at the INFORMIX-4GL Menu to select the Form option. This option displays a menu, called the FORM Design Menu:
FORM: Modify Generate New Compile Exit Change an existing form specification. -------------------------------------------------Press CTRL-W for Help------

You can use this menu to create, modify, and compile screen form specifications. These define visual displays that 4GL applications can use to query and modify the information in a database. INFORMIX-4GL form specification files are ASCII files that are described in Chapter 4 of this manual, and in Chapters 6 and 7 of the INFORMIX-4GL User Guide. The FORM Design Menu supports the following options: Modify Generate New Compile Exit Change an existing 4GL screen form specification. Create a default 4GL screen form specification. Create a new 4GL screen form specification. Compile an existing 4GL screen form specification. Return to the INFORMIX-4GL Menu.

1-14

Compiling 4GL Source Files

The FORM Design Menu

Readers familiar with INFORMIX-SQL may notice that this resembles the menu displayed by the Form option of the INFORMIX-SQL Main Menu.

The Modify Option
The Modify option of the FORM Design Menu enables you to edit an existing form specification file. It resembles the Modify option in the MODULE Design Menu, since both options are used to edit program modules.
FORM: Modify Generate New Compile Exit Change an existing form specification. -------------------------------------------------Press CTRL-W for Help------

If you select this option, you are prompted to select the name of a form specification file to modify. Source files created at the FORM Design Menu have the file extension .per. (If you use a text editor outside of the Programmer’s Environment to create form specification files, you must give them the extension .per before you can compile them with the FORM4GL screen form facility.) If you have not already designated a text editor in this INFORMIX-4GL session or with DBEDIT, you are prompted for the name of an editor. Then an editing session begins, with the form specification source-code file that you specified as the current file. When you leave the editor, INFORMIX-4GL displays the MODIFY FORM Menu with the Compile option highlighted. Now you can press RETURN to compile the revised form specification file.
MODIFY FORM: Compile Save-and-exit Compile the form specification. Discard-and-exit

-------------------------------------------------Press CTRL-W for Help------

Compiling 4GL Source Files

1-15

The FORM Design Menu

If there are compilation errors, INFORMIX-4GL displays the COMPILE FORM Menu:
COMPILE FORM: Correct Exit Correct errors in the form specification. -------------------------------------------------Press CTRL-W for Help------

Press RETURN to select Correct as your option. An editing session begins on a copy of the current form, with diagnostic error messages embedded where the compiler detected syntax errors. INFORMIX-4GL automatically deletes these messages when you save and exit from the editor. After you have corrected the errors, the MODIFY FORM Menu appears again, with the Compile option highlighted. Press RETURN to recompile. Repeat these steps until the compiler reports no errors. If there are no compilation errors, you are prompted whether to save the modified form specification file and the compiled form, or to discard the changes. (Discarding the changes restores the version of your form specifications from before you chose the Modify option.)

The Generate Option
You can type g or G to select the Generate option. This option creates a simple ‘‘default’’ screen form that you can use directly in your program, or that you can later edit by selecting the Modify option.
FORM: Modify Generate New Compile Exit Generate and compile a default form specification. -------------------------------------------------Press CTRL-W for Help------

1-16

Compiling 4GL Source Files

The FORM Design Menu

When you select this option, INFORMIX-4GL prompts you to select a database, to choose a filename for the form specification, and to identify the tables that the form will access. After you provide these data, INFORMIX-4GL creates and compiles a form specification file. (This is equivalent to running the -d (default) option of FORM4GL, as described near the end of Chapter 4, “Form Building and Compiling.”)

The New Option
The New option of the FORM Design Menu enables you to create a new screen form specification.
FORM: Modify Generate New Compile Create a new form specification. Exit

-------------------------------------------------Press CTRL-W for Help------

After prompting you for the name of your form specification file, INFORMIX-4GL places you in the editor where you can create a form specification file. When you leave the editor, INFORMIX-4GL transfers you to the NEW FORM Menu that is like the MODIFY FORM Menu. You can compile your form and correct it in the same way.

The Compile Option
The Compile option enables you to compile an existing form specification file without going through the Modify option.
FORM: Modify Generate New Compile Exit Compile an existing form specification. -------------------------------------------------Press CTRL-W for Help------

Compiling 4GL Source Files

1-17

The PROGRAM Design Menu

INFORMIX-4GL compiles the form specification file whose name you specify. If the compilation fails, INFORMIX-4GL displays the COMPILE FORM Menu

with the highlight on the Correct option.

The Exit Option
The Exit option restores the INFORMIX-4GL Menu.
FORM: Modify Generate New Compile Returns to the INFORMIX-4GL Menu. Exit

-------------------------------------------------Press CTRL-W for Help------

The PROGRAM Design Menu
An INFORMIX-4GL program can be a single source-code module that you create and compile at the MODULE Design Menu. For applications of greater complexity, however, it is often easier to develop and maintain separate 4GL modules. The INFORMIX-4GL Menu includes the Program option so that you can create multi-module programs. If you select this option, INFORMIX-4GL searches your DBPATH directories (see Appendix C) for the program specification database, called syspgm4gl. This database describes the component modules and function libraries of your 4GL program. If INFORMIX-4GL cannot find this database, you are asked if you want one created. If you enter y in response, INFORMIX-4GL creates the syspgm4gl database, grants CONNECT privilege to PUBLIC, and displays the PROGRAM Design Menu. As Database Administrator of syspgm4gl, you can later restrict the access of other users.

1-18

Compiling 4GL Source Files

The PROGRAM Design Menu

If syspgm4gl already exists, the PROGRAM Design Menu appears.
PROGRAM: Modify New Compile Planned_Compile Run Drop Exit Change the compilation definition of a 4GL application program. -------------------------------------------------Press CTRL-W for Help------

You can use this menu to create or modify a multi-module 4GL program specification, to compile and link a program, or to execute a program. The PROGRAM Design Menu supports the following options: Modify New Compile Planned_Compile Run Drop Exit Change an existing program specification. Create a new program specification. Compile an existing program. List the steps necessary to compile and link an existing program. Execute an existing program. Delete an existing program specification. Return to the INFORMIX-4GL Menu.

You must first use the MODULE Design Menu and FORM Design Menu to enter and edit the INFORMIX-4GL statements within the component sourcecode modules of a 4GL program. Then you can use the PROGRAM Design Menu to identify which modules are part of the same application program, and to link all the modules as an executable command file.

The Modify Option
The Modify option enables you to modify the specification of an existing 4GL program. (This option is not valid unless at least one program has already been specified. If none has, you can create a program specification by selecting the New option from the same menu.) INFORMIX-4GL prompts you for

Compiling 4GL Source Files

1-19

The PROGRAM Design Menu

the name of the program specification to be modified. It then displays a menu and form that you can use to update the information in the program specification database as shown in Figure 1-1:
MODIFY PROGRAM: 4GL Other Edit the 4GL sources list. Libraries Compile_Options Rename Exit

-------------------------------------------------Press CTRL-W for Help-----Program [myprog ] 4gl Source [main [funct [rept [ [ 4gl Source Path [/u/john/appl/4GL [/u/john/appl/4GL [/u/john/appl/4GL [ [ Ext [c [ [ [ Other Source Path [/u/john/appl/C [ [ [ Compile Options [ [ ] ]

] ] ] ] ]

] ] ] ] ]

Other Source [cfunc ] [ ] [ ] [ ] Libraries [m [

] ] ] ] ] ]

] ] ] ]

Figure 1-1

Example of a Program Specification Entry

The name of the program appears in the Program field. In Figure 1-1 the name is myprog. You can change this name by selecting the Rename option. INFORMIX-4GL assigns the program name, with the extension .4ge, to the executable program produced by compiling and linking all the source files and libraries. (Compiling and linking occurs when you select the Compile option, as described later in this chapter.) In this example, the resulting executable program would have the name myprog.4ge. Use the 4GL option to update the entries for the 4GL Source fields and the 4GL Source Path fields on the form. The five rows of fields under these labels form a screen array. When you select the 4GL option, INFORMIX-4GL executes an INPUT ARRAY statement so you can move and scroll through the array. See the INPUT ARRAY statement in Chapter 7 for information about how to use your function keys to scroll, delete rows, and insert new rows. (You cannot redefine the function keys, however, as you can with an INFORMIX-4GL program.)

1-20

Compiling 4GL Source Files

The PROGRAM Design Menu

The INFORMIX-4GL source program that appears in Figure 1-1 contains three modules:

• One module contains the main program (main.4gl). • One module contains functions (funct.4gl). • One module contains REPORT statements (rept.4gl).
Each module is located in the directory /u/john/appl/4GL. If your program includes a module containing only global variables (for example, global.4gl), you must also list that module in this section. Use the Other option to include non-INFORMIX-4GL source modules or object-code modules in your program. Enter this information into the three-column screen array with the headings Other Source, Ext, and Other Source Path. Enter the filename and location of each non-INFORMIX-4GL source-code or object-code module in these fields. Enter the name of the module in the Other Source field, the filename extension of the module (for example, ec for an INFORMIX-ESQL/C module, or c for a C module) in the Ext field, and the full directory path of the module in the Other Source Path field. The example in Figure 1-1 includes a file containing C function sourcecode (cfunc.c) located in /u/john/appl/C. You can list up to 100 files in this array. The Libraries option enables you to indicate the names of up to ten special libraries to link with your program. INFORMIX-4GL calls the C compiler to do the linking and adds the appropriate -l prefix, so you should enter only what follows the prefix. The example displayed in Figure 1-1 calls only the standard C math library. Use the Compile_Options option to indicate up to ten C compiler options. Enter this information in the Compile Options field. You cannot, however, specify the -e or -a options of c4gl in this field. (See the section “Working at the Command Line” for more information about the options of the c4gl command). The Exit option exits from the MODIFY PROGRAM Menu and displays the PROGRAM Design Menu.

Compiling 4GL Source Files

1-21

The PROGRAM Design Menu

The New Option
Use the New option on the PROGRAM Design Menu to create a new specification of the program modules and libraries that make up an application program. You can also specify any necessary compiler or loader options.
PROGRAM: Modify New Compile Planned_Compile Run Drop Exit Add the compilation definition of a 4GL application program. -------------------------------------------------Press CTRL-W for Help------

The submenu screen forms displayed by the New and the Modify options of the PROGRAM Design Menu are identical, except that you must first supply a name for your program when you select the New option. (INFORMIX-4GL displays a blank form in the NEW PROGRAM Menu.) The NEW PROGRAM Menu has the same options as the MODIFY PROGRAM Menu, as illustrated earlier.

The Compile Option
The Compile option performs the compilation and linking described in the program specification database, taking into account the time when each file was last updated. It compiles only those files that have not been compiled since they were changed.
PROGRAM: Modify New Compile Planned_Compile Compile a 4GL application program. Run Drop Exit

-------------------------------------------------Press CTRL-W for Help------

INFORMIX-4GL lists each step of the preprocessing and compilation as it

occurs. An example of these messages appears in the illustration of ‘‘The Planned_Compile Option’’ in the next section.

1-22

Compiling 4GL Source Files

The PROGRAM Design Menu

The Planned_Compile Option
Taking into account the time when the various files in the dependency relationships last changed, the Planned_Compile option prompts for a program name and displays a summary of the steps that will be executed if you select the Compile option. No compilation actually takes place.
PROGRAM: Modify New Compile Planned_Compile Run Drop Exit Show the planned compile actions of a 4GL application program. -------------------------------------------------Press CTRL-W for Help-----Compiling INFORMIX-4GL sources: /u/john/appl/4GL/main.4gl /u/john/appl/4GL/funct.4gl /u/john/appl/4GL/rept.4gl Compiling Embedded SQL sources: Compiling with options: Linking with libraries: m Compiling/Linking other sources: /u/john/appl/C/cfunc.c

In this instance, changes were made to all the components of the 4GL program that were listed in Figure 1-1. This display indicates that no source-code module has been compiled since the program was changed.

Compiling 4GL Source Files

1-23

The PROGRAM Design Menu

The Run Option
The Run option of the PROGRAM Design Menu is the same as the Run option of the MODULE Design Menu. It displays a list of any compiled programs (files with the extension .4ge) and positions the highlight on the current program, if a program has been specified. INFORMIX-4GL then executes the program that you select.
PROGRAM: Modify New Compile Planned_Compile Execute a 4GL application program Run Drop Exit

-------------------------------------------------Press CTRL-W for Help------

The Drop Option
The Drop option of the PROGRAM Design Menu prompts you for a program name and removes the compilation and linking definition of that program from the syspgm4gl database. This action removes the definition only. Your program and 4GL modules are not removed.
PROGRAM: Modify New Compile Planned_Compile Run Drop Exit Drop the compilation definition of a 4GL application program. -------------------------------------------------Press CTRL-W for Help------

The Exit Option
The Exit option clears the PROGRAM Design Menu and restores the INFORMIX-4GL Menu.

1-24

Compiling 4GL Source Files

The QUERY LANGUAGE Menu

The QUERY LANGUAGE Menu
The SQL interactive interface is identical to the interactive SQL interface of INFORMIX-SQL. You can use this option only if you have separately purchased INFORMIX-SQL and installed it. The Query-language option is placed at the top-level menu so you can test SQL statements without leaving the INFORMIX-4GL Programmer’s Environment. You can also use this option to create, execute, and save SQL scripts.

Creating Executable 4GL Programs (C Compiler Version)
To create a 4GL application with the C Compiler Version of INFORMIX-4GL requires the following steps: 1. Preprocess INFORMIX-4GL code to produce INFORMIX-ESQL/C code. 2. Preprocess the INFORMIX-ESQL/C code to produce C language code. 3. Compile the C code with the C compiler to create an object file. 4. Link the object file with the INFORMIX-ESQL/C libraries, and to any additional libraries whose functions are called. The sections that follow describe how to carry out these steps, both from the Programmer’s Environment and at the system prompt.

Working in the Programmer’s Environment
If your software has been installed according to the instructions in your Installation Guide, you can enter i4gl at the system prompt to invoke the Programmer’s Environment. After a pause for the sign-on message, the INFORMIX-4GL Menu appears.

Compiling 4GL Source Files

1-25

Working in the Programmer’s Environment

Creating a New Source Module
This section outlines the procedure for creating a new module. If your source module already exists but needs to be modified, you should skip ahead to the next section, ‘‘Revising an Existing Module.’’

• Press RETURN at the INFORMIX-4GL Menu to select the Module option.
The screen displays the MODULE Design Menu.

• If you are creating a new .4gl source module, press n to select the New
option of the MODULE Design Menu. The screen prompts you for a name to assign to the new module.

• Enter a name for the new module. The name must begin with a letter and
can include letters, numbers, and underscores. The name must be unique among the files in the same directory, and among the other program modules, if it will be part of a multi-module program. INFORMIX-4GL attaches extension .4gl to this identifier, as the filename of your new source module.

Revising an Existing Module
If you are revising an existing 4GL source file, rather than creating a new one, the procedures to begin an editing session are slightly different from the steps that were just described.

• Select the Modify option of the MODULE Design Menu. • The screen lists the names of all the .4gl source modules in the current
directory and prompts you to select a source file to edit. Use the Arrow keys to highlight the name of a source module and press RETURN, or enter a filename (with no extension). If you specified the name of an editor with the DBEDIT environment variable, an editing session with that editor begins automatically. Otherwise, the screen prompts you to specify a text editor.

• Specify the name of a text editor, or press RETURN for vi, the default
editor. Now you can begin an editing session by entering 4GL statements. (The chapters that follow describe INFORMIX-4GL statements and programs.)

• When you have finished entering or editing your 4GL code, use an
appropriate editor command to save your source file and end the text editing session.

1-26

Compiling 4GL Source Files

Working in the Programmer’s Environment

Compiling a Source Module
The .4gl source file module that you create or modify is an ASCII file that must be compiled before it can be executed. After you save your file and exit from the editor, the screen prompts you to choose among Compile, Save-and-exit, or Discard-and-exit options.

• Select the Compile option to compile the module. After you select
Compile, the screen prompts you to select among three options: Object, Runable, and Exit. What you should do depends on whether your module is a complete program, or whether it is one of several .4gl modules that together comprise a complete program.

• If the module is a complete 4GL program that requires no other modules,
select Runable. This option first creates an intermediate ESQL/C version of your source-code module, then calls the ESQL/C preprocessor which produces C output, and finally calls the C compiler to produce a compiled file with the same filename, but with the extension .4ge.

• If the module is one module of a multi-module 4GL program, select
Object. This option creates a compiled object file module, with the same filename, but with extension .o. See also the procedures for linking program modules, which are described later in this section. If the compiler detects errors after either option, no compiled file is created, and the screen prompts you to select Correct or Exit. Follow the first two steps on the next page after an error.

• Select Correct to resume the previous text editing session, with the same
4GL source code, but with error messages in the file.

• Edit the file to correct the error, and select Compile again. If an error message appears, repeat the previous steps, until the module compiles without error.

• After the module compiles successfully, the screen prompts you again to
Compile, or to Save-and-exit, or to Discard-and-exit. Select the second option, to save the compiled program. The MODULE Design Menu appears again on your screen.

• If your program requires screen forms, you must select Exit to return to the
INFORMIX-4GL Menu, and then select Form to display the FORM Design

Menu. See Chapter 4 for information about designing and creating screen forms.

• If your program displays help messages, you must create a help file and
compile it with the mkmessage utility. See Chapter 8 of the INFORMIX-

Compiling 4GL Source Files

1-27

Working in the Programmer’s Environment

4GL User Guide for more information about help messages in INFORMIX-4GL programs.

Linking Program Modules
If the module that you compiled is the only module in your program, you are now ready to run your program, and you can skip the steps that are described here. If your new or modified module is part of a multi-module 4GL program, however, you must link all of the modules into a single program file before you can run the program.

• If you are not at the INFORMIX-4GL Menu, select Exit until that menu
appears. Then select the Program option, to display the PROGRAM Design Menu.

• Select the New option if you are creating a new multi-module 4GL
program, or select Modify if you are modifying an existing one. In either case, the screen prompts you for the name of a program.

• Enter the name (without a file extension) of the program that you are
modifying, or the name to be assigned to a new program. Names must begin with a letter, and can include letters, underscores ( _ ), and numbers. After you enter a valid name, the PROGRAM screen appears, with your program name in the first field. If you selected Modify, the names and pathnames of the source-code modules are also displayed. In that case, the PROGRAM screen appears below the MODIFY PROGRAM Menu, rather than below the NEW PROGRAM Menu. (Both menus list the same options.)

1-28

Compiling 4GL Source Files

Working in the Programmer’s Environment

MODIFY PROGRAM: 4GL Other Libraries Compile_Options Rename Exit Edit the 4GL sources list. -------------------------------------------------Press CTRL-W for Help-----Program [ ] 4gl Source [ ] [ ] [ ] [ ] [ ] Other Source [ ] [ ] [ ] [ ] Libraries [ [ 4gl Source Path [ [ [ [ [ Ext [ [ [ [ ] ] ] ] ] ] Other Source Path [ [ [ [ Compile Options [ [ ] ] ] ] ] ] ] ] ] ] ]

• To specify new 4GL modules or edit the list of 4GL modules, press
RETURN to select the 4GL option. You can enter or edit the name of a

module, without the .4gl file extension. Repeat this step for every module. If the module is not in the current directory nor in a directory specified by the DBPATH environment variable, enter the pathname to the directory where the module resides.

• If your program includes any modules that are not 4GL source files, you
should select the Other option. This option enables you to specify each filename in the Other Source field, the filename extension in the Ext field, and the pathname in the Other Source Path field. These fields are part of an array that can specify up to 100 ‘‘other’’ modules, such as C language source files or object files. If you have the INFORMIX-ESQL/C product installed on your system, you can also specify ESQL/ C source modules (with extension .ec) here.

• To specify any function libraries that should be linked to your program
(besides the INFORMIX-4GL library that is described in Chapter 6), select the Libraries option. This option enables you to enter or edit the list of library names in the Libraries fields.

• Select the Compile_Options option if you want to specify compiler flags.
These flags can be entered or edited in the Compile Options fields.

• After you have correctly listed all of the modules of your program, select
the Exit option to return to the PROGRAM Design Menu.

Compiling 4GL Source Files

1-29

Working at the Command Line

• Select the Compile option of the PROGRAM Design Menu. This option
produces an executable file that contains all your 4GL program modules. Its filename is the program name that you specified, with extension .4ge. The screen lists the names of your .4gl source modules, and displays the PROGRAM Design Menu with the Run option highlighted. See also the section “Program Filename Extensions (C Compiler Version)” later in this chapter for information about the backup files that are produced automatically when you work at the Programmer’s Environment of the INFORMIX-4GL C Compiler Version.

Executing a Compiled Program
After compiling and linking your program modules, you can type r or R or press RETURN to select the Run option. This option begins execution of the compiled 4GL program. Your program can display menus, screen forms, windows, or other screen output according to your program logic and your keyboard interaction with the program.

Working at the Command Line
You can also create .4gl source files and compiled .o and .4ge files at the operating system prompt. Figure 1-2 shows the process of creating, compiling, linking, and running an INFORMIX-4GL program from the command line.

TEXT EDITOR

.4gl Source Files

.c, .ec Files

.o Object Files

.err Error File
Figure 1-2 1-30

PREPROCESSOR & COMPILER c4gl

.4ge Compiled Program File

Creating and Running an INFORMIX-4GL Program

Compiling 4GL Source Files

Working at the Command Line

Here the rectangles represent processes controlled by specific commands, and the circles represent files. Arrows indicate whether a file can serve as input or output (or as both) for a process. This diagram is simplified and ignores the similar processes by which forms, help messages, and other components of 4GL applications are compiled, linked, and executed.

• The cycle begins in the upper left corner with a text editor, such as vi,
to produce a 4GL source module.

• A multi-module program can include additional 4GL source files (.4gl),
INFORMIX-ESQL/C source files (.ec), C language source files (.c), and

object files (.o).

• The program module can then be compiled, by invoking the c4gl preprocessor and compiler command. (If error messages result, find them in the .err file and edit the source file to correct the errors. Then recompile the corrected source module.) The resulting compiled .4ge program file is an executable command file that you can run by entering its name at the system prompt: filename.4ge where filename.4ge specifies your compiled 4GL file. The correspondence between commands and menu options of the Programmer’s Environment is summarized by the following list:
Command

vi c4gl filename.4ge

Invokes UNIX System Editor 4GL Preprocessor/Compiler 4GL Application

Menu Option Module New/Modify Compile Run

Creating or Modifying a 4GL Source File
Use your system editor or another text editing program to create a .4gl source file or to modify an existing file. See the documentation of your text editor and the other chapters of this manual for details.

Compiling a 4GL Module
You can compile an INFORMIX-4GL source file at the system prompt by entering a command of the form: c4gl source.4gl -o filename.4ge

Compiling 4GL Source Files

1-31

Working at the Command Line

The c4gl command compiles your 4GL source-code module (here called source.4gl) and produces an executable program called filename.4ge. The complete syntax of the c4gl command appears on the next page.

Compiling and Linking Multiple Source Files
An INFORMIX-4GL program can include several source-code modules. You cannot execute a 4GL program until you have preprocessed and compiled all the source modules and linked them with any function libraries that they reference. You can do all this in a single step at the system prompt by the c4gl command, which performs the following processing steps: 1. Reads your 4GL source-code files (extension .4gl) and preprocesses them to produce ESQL/C code. 2. Reads the ESQL/C code and preprocesses it to produce C code. 3. Reads the C code and compiles it to produce an object file. 4. Links the object file to the INFORMIX-ESQL/C libraries and to any additional libraries that you specify in the command line. You must assign the filename extension .4gl to any INFORMIX-4GL sourcecode modules that you compile. The resulting .4ge file is an executable version of your program. Notice that ESQL/C source files (with extension .ec), C source files (with extension .c), and C object files (with extension .o) are intermediate steps in producing an executable INFORMIX-4GL program. Besides 4GL source files (with extension .4gl), you can also include files of any or all of these types when you specify a c4gl command line to compile and link the component modules of a 4GL program. The c4gl command supports the following syntax:

Syntax
c4gl { -V | [ -ansi] [-e ] [ -a ] [ -otherargs . . . ] [ -o outfile ] source.4gl . . . [ otheresql.ec . . . ] [ othersrc.c . . . ] [ otherobj.o . . . ] [ yourlib . . . ] }

Explanation
-V -ansi displays the release version number of your SQL software, without processing any source files. instructs the compiler to check all SQL statements for compliance with ANSI standards.

1-32

Compiling 4GL Source Files

Working at the Command Line

-e -a

performs only the preprocessor steps, with no compilation or linking. causes your compiled program to check array bounds at run time. The -a option must appear on the command line before the source.4gl filename. are other arguments for your C compiler. is a name that you assign to the compiled 4GL program. is the name of an INFORMIX-4GL source module. You must specify the .4gl extension. is an ESQL/C source file to compile and link. is a C language source file to compile and link. is an object file to link with your 4GL program. is a library from which to extract functions that are not part of the INFORMIX-4GL or INFORMIX-ESQL/C libraries.

-otherargs outfile source.4gl otheresql.ec othersrc.c otherobj.o yourlib

Notes
1. If you specify the -V option to display the version number, all other arguments are ignored, and no output files are produced. 2. Since the -a option requires additional run-time processing, you may want to use this option only during development to debug your program. 3. The c4gl command passes all C compiler arguments (otherargs) and other C source and object files (othersrc.c, otherobj.o) directly to the C compiler (cc). 4. You can compile INFORMIX-4GL modules separately from your MAIN program block. If there is no MAIN program block in source.4gl, your code is compiled to source.o, but not linked with other modules or libraries. You can use c4gl to link your code with a module that includes the MAIN program block at another time. (Chapter 2 of the INFORMIX-4GL User Guide describes the MAIN program block.) 5. If you specify the -ansi option, it must appear first in your list of c4gl command arguments. The -ansi option asks for compile-time warning messages if your source code includes Informix extensions to the ANSI standard for SQL. (Chapter 7 lists the Informix syntax extensions.) Compiler warnings and error messages are saved in a file called source.err. 6. If you omit the -o outfile option, the default filename is a.out.

Compiling 4GL Source Files

1-33

Working at the Command Line

Examples
The simplest case is to compile a single-module INFORMIX-4GL program. This command produces an executable program called single.4ge:
c4gl single.4gl -o single.4ge

In the next example, the object files mod1.o, mod2.o, and mod3.o are previously compiled INFORMIX-4GL modules, and mod4.4gl is a source-code module. Suppose that you want to compile and link mod4.4gl with the three object modules to create an executable program called myappl.4ge. To do so, enter the following command line:
c4gl mod1.o mod2.o mod3.o mod4.4gl -o myappl.4ge

Running 4GL Programs
As noted in the previous section, a valid c4gl command line produces a .4ge file (or whatever you specify after the -o argument) that is an executable command file. To execute your compiled INFORMIX-4GL application program, enter the filename at the system prompt. For example, to run myappl.4ge (the program in the previous example), simply enter the command line: myappl.4ge (Some INFORMIX-4GL programs may require additional command-line arguments, such as constants or filenames, depending on the logic of your specific 4GL application.)

4GL Programs That Call C Functions
No special procedures are needed to create, compile, and execute 4GL programs that call C functions or INFORMIX-ESQL/C functions when you use the C Compiler Version of INFORMIX-4GL. See, however, the section “C Functions” in Chapter 2 for details of creating INFORMIX-4GL programs that call programmer-defined C functions within 4GL modules. See also Appendix F, “DECIMAL Functions for C,” which addresses issues of data conversion.

1-34

Compiling 4GL Source Files

Program Filename Extensions (C Compiler Version)

Program Filename Extensions (C Compiler Version)
Source, runable, error, and backup files generated by INFORMIX-4GL are stored in the current directory and are labeled with a filename extension. The following list shows the file extensions for the source, runable, and error files. These files are produced during the normal course of using the C Compiler Version of INFORMIX-4GL. file.4gl file.o file.4ge file.err is an INFORMIX-4GL source file. is an INFORMIX-4GL object file. is an INFORMIX-4GL executable (runable) file. is an INFORMIX-4GL source error file, created when an attempt to compile a module fails. The file contains INFORMIX-4GL source code, plus any compiler syntax error or warning messages. is an intermediate source file, created during the normal course of compiling an INFORMIX-4GL module. is an intermediate C file, created during the normal course of compiling an INFORMIX-4GL module. is an INFORMIX-4GL object error file, created when an attempt to compile or to link a non-INFORMIX-4GL sourcecode or object module fails. The file contains INFORMIX-4GL source code and annotated compiler errors. is a FORM4GL source file. is a FORM4GL object file. is a FORM4GL source error file.

file.ec file.c file.erc

form.per form.frm form.err

The last three files do not exist unless you create or modify a screen form specification file, as described in Chapter 4. The next page lists the corresponding file extensions for the backup files that INFORMIX-4GL automatically creates when you use the Programmer’s Environment to process 4GL source files. The following list identifies the backup files that are produced when you use INFORMIX-4GL from the Programmer’s Environment. file.4bl file.4bo is an INFORMIX-4GL source backup file, created during the modification and compilation of a .4gl program module. is an object backup file, created during the compilation of a .o program module.

Compiling 4GL Source Files

1-35

INFORMIX-4GL (Rapid Development System)

file.4be file.pbr file.fbm

is an object backup file, created during the compilation of a .4ge program module. is a FORM4GL source backup file. is a FORM4GL object backup file.

Under normal conditions, INFORMIX-4GL creates the backup files and intermediate files as necessary and deletes them upon a successful compilation. If you interrupt a compilation, you may find one or more of these files in your current directory. During the compilation process, INFORMIX-4GL stores a backup copy of the file.4gl source file in file.4bl. The time stamp is modified on the (original) file.4gl source file, but not on the backup file.4bl file. In the event of a system crash, you may need to replace the modified file.4gl file with the backup copy contained in the file.4bl file. The Programmer’s Environment does not allow you to begin modifying a .4gl or .per source file if the corresponding backup file already exists in the same directory. After an editing session terminates abnormally, for example, you must delete or rename any backup file before you can resume editing your 4GL module or form from the Programmer’s Environment.

INFORMIX-4GL (Rapid Development System)
The rest of this chapter provides a description of the INFORMIX-4GL Rapid Development System. Except as otherwise noted, the other chapters and appendixes of this manual describe features that are identical in both the C Compiler Version and Rapid Development System Version implementations of INFORMIX-4GL.

The RDS Programmer´s Environment
The INFORMIX-4GL Rapid Development System provides a series of menus called the Programmer’s Environment. These menus support the steps of 4GL program development and keep track of the components of your application. You can invoke the Programmer’s Environment by entering r4gl at the system prompt.

1-36

Compiling 4GL Source Files

The INFORMIX-4GL Menu

The INFORMIX-4GL Menu
The r4gl command briefly displays the INFORMIX-4GL banner and sign-on message. Then a menu appears, called the INFORMIX-4GL Menu:
INFORMIX-4GL: Module Form Program Query-language Exit Create, modify or run individual 4GL program modules. -------------------------------------------------Press CTRL-W for Help------

This is the highest menu, from which you can reach any other menu of the Programmer’s Environment. You have five options: Module Form Program Query-language Exit Work on an INFORMIX-4GL program module. Work on a screen form. Specify components of a multi-module program. Use the SQL interactive interface, if you have INFORMIX-SQL installed on your system. Return to the operating system.

The first three options display new menus that are described in the pages that follow. (You can also press CTRL-W at any menu to display an on-line help message that describes your options.) As at any 4GL menu, you can select an option in either of two ways:

• By typing the first letter of the option, or • By using the SPACEBAR or Arrow keys to move the highlight to the option
that you choose, and then pressing RETURN.

Compiling 4GL Source Files

1-37

The MODULE Design Menu

The MODULE Design Menu
You can press RETURN or type m or M to select the Module option of the INFORMIX-4GL Menu. This option displays a new menu, called the MODULE Design Menu. Use this menu to work on an individual 4GL source-code file.
MODULE: Modify New Compile Program_Compile Change an existing 4GL program module. Run Debug Exit

-------------------------------------------------Press CTRL-W for Help------

The MODULE Design Menu supports the following options: Modify New Compile Program_Compile Run Debug Change an existing 4GL source-code module. Create a new 4GL source-code module. Compile an existing 4GL source-code module. Compile a 4GL application program. Execute a compiled 4GL module or multi-module application program. Invoke the INFORMIX-4GL Interactive Debugger to examine an existing 4GL program module or application program (if you have the Debugger product installed on your system). Return to the INFORMIX-4GL Menu.

Exit

As in all of the menus of the Programmer’s Environment except the INFORMIX-4GL Menu, the Exit option returns control to the higher menu from which you accessed the current menu. You can use these options to create and compile source-code modules of a 4GL application. (See “The FORM Design Menu” later in this chapter for information on creating 4GL screen forms. Refer also to “The mkmessage Utility” section of Appendix E for information on creating and compiling programmer-defined help messages for an INFORMIX-4GL application.)

1-38

Compiling 4GL Source Files

The MODULE Design Menu

The Modify Option
Select this option to edit an existing 4GL source-code module. If you select this option, INFORMIX-4GL requests the name of the 4GL source-code file to be modified, and then prompts you to specify a text editor. If you have designated an editor with the DBEDIT environment variable (see Appendix C) or named an editor previously in this session at the Programmer’s Environment, INFORMIX-4GL invokes that editor. The 4GL source file whose filename you specified is the current file. When you leave the editor, INFORMIX-4GL displays the MODIFY MODULE Menu, with the Compile option highlighted:
MODIFY MODULE: Compile Save-and-exit Compile the 4GL module specification. Discard-and-exit

-------------------------------------------------Press CTRL-W for Help------

If you press RETURN or type c or C to select the Compile option, INFORMIX-4GL displays the COMPILE MODULE Menu:
COMPILE MODULE: Object Runable Exit Create object file (.4go suffix). -------------------------------------------------Press CTRL-W for Help------

The Object option creates a file with a .4go extension. The Runable option creates a file with a .4gi extension. Select the Runable option if the current program module is a stand-alone 4GL program. If this is not the case, (that is, if the file is one of several 4GL source-code modules within a multi-module program), then you should use the Object option instead, and you must use the PROGRAM Design Menu to specify all the component modules.

Compiling 4GL Source Files

1-39

The MODULE Design Menu

After you select Object or Runable, a message near the bottom of the screen will advise you if INFORMIX-4GL issues a compile-time warning or error. If there are warnings (but no errors), a p-code file is produced. Select the Exit option of the next menu, and then Save-and-exit at the MODIFY MODULE Menu, if you want to save the p-code file without reading the warnings. Alternatively, you can examine the warning messages by selecting Correct at the next menu. When you finish editing the .err file that contains the warnings, you must select Compile again from the MODIFY MODULE Menu, since the Correct option deletes the p-code file. If there are compilation errors, the following menu appears:
COMPILE MODULE: Correct Exit Correct errors in the 4GL module. -------------------------------------------------Press CTRL-W for Help------

If you choose to correct the errors, an editing session begins on a copy of your source module with embedded error messages. (You do not need to delete error messages, since INFORMIX-4GL does this for you.) Correct your source file, save your changes, and exit from the editor. The MODIFY MODULE Menu reappears, prompting you to recompile, or to save or discard your changes without compiling. If there are no compilation errors, the MODIFY MODULE Menu appears with the Save-and-Exit option highlighted. If you select this option, INFORMIX-4GL saves the current source-code module as a disk file with the filename extension .4gl, and saves the compiled version as a file with the same filename, but with the extension .4go or .4gi. If you select the Discard-and-Exit option, INFORMIX-4GL discards any changes made to your file since you selected the Modify option.

1-40

Compiling 4GL Source Files

The MODULE Design Menu

The New Option
Select this option to create a new 4GL source-code module.
MODULE: Modify New Compile Program_Compile Create a new 4GL program module. Run Debug Exit

-------------------------------------------------Press CTRL-W for Help------

This option resembles the Modify option, but NEW MODULE is the menu title, and you must enter a new module name, rather than select it from a list. If you have not designated an editor previously in this session or with DBEDIT, you are prompted for an editor. Then an editing session begins.

The Compile Option
The Compile option enables you to compile an individual 4GL source-code module without first selecting the Modify option.
MODULE: Modify New Compile Program_Compile Compile an existing 4GL program module. Run Debug Exit

-------------------------------------------------Press CTRL-W for Help------

After you specify the name of a 4GL source-code module to compile, the screen displays the COMPILE MODULE Menu. Its Object, Runable, and Exit options were described two pages earlier in the discussion of the Modify option.

The Program_Compile Option
The Program_Compile option of the MODULE Design Menu is the same as the Compile option of the PROGRAM Design Menu (see that option for details). It permits you to compile and combine modules as described in the
Compiling 4GL Source Files 1-41

The MODULE Design Menu

program specification database, taking into account the time when the modules were last updated. This option is useful when you have just modified a single module of a complex program and want to test it by compiling it with the other modules.

The Run Option
Select this option to begin execution of a compiled program.
MODULE: Modify New Compile Program_Compile Run Debug Exit Execute an existing 4GL program module or application program. -------------------------------------------------Press CTRL-W for Help------

The RUN PROGRAM screen presents a list of compiled modules and programs, with the highlight on the module corresponding to the current file, if any has been specified. Compiled programs must have the extension .4gi to be included in the list. If you compile a module with the extension .4go, you can run it by typing the filename and extension at the prompt. If no compiled programs exist, INFORMIX-4GL displays an error message and restores the MODULE Design Menu.

The Debug Option
Select this option to use the INFORMIX-4GL Interactive Debugger to analyze a program. This option is implemented only if you have separately purchased and installed the INFORMIX-4GL Interactive Debugger on your system.
MODULE: Modify New Compile Program_Compile Returns to the INFORMIX-4GL Menu. Run Debug Exit

-------------------------------------------------Press CTRL-W for Help------

1-42

Compiling 4GL Source Files

The FORM Design Menu

If you have the Debugger product, refer to the INFORMIX-4GL Interactive Debugger documentation for more information about this option.

The Exit Option
Select this option to exit from the MODULE Design Menu and display the INFORMIX-4GL Menu.
MODULE: Modify New Compile Program_Compile Returns to the INFORMIX-4GL Menu. Run Debug Exit

-------------------------------------------------Press CTRL-W for Help------

The FORM Design Menu
You can type f or F at the INFORMIX-4GL Menu to select the Form option. This option replaces the INFORMIX-4GL Menu with a new menu, called the FORM Design Menu:
FORM: Modify Generate New Compile Exit Change an existing form specification. -------------------------------------------------Press CTRL-W for Help------

You can use this menu to create, modify, and compile screen form specifications. These specifications define visual displays that 4GL applications can use to query and modify the information in a database. INFORMIX-4GL screen form specifications are ASCII files that are described in Chapter 4 of this manual, and in Chapters 6, 7, and 11 of the INFORMIX-4GL User Guide. The FORM Design Menu supports the following options: Modify Generate Change an existing 4GL screen form specification. Create a default 4GL screen form specification.
Compiling 4GL Source Files 1-43

The FORM Design Menu

New Compile Exit

Create a new 4GL screen form specification. Compile an existing 4GL screen form specification. Return to the INFORMIX-4GL Menu.

Readers familiar with the menu system of INFORMIX-SQL may notice that this menu resembles the menu displayed by the Form option of the INFORMIX-SQL Main Menu. Chapter 4 of this manual and Chapters 6 and 7 of the INFORMIX-4GL User Guide describe the usage and statement syntax of 4GL screen form specifications.

The Modify Option
The Modify option of the FORM Design Menu enables you to edit an existing form specification file. It resembles the Modify option in the MODULE Design Menu, since both options are used to edit program modules.
FORM: Modify Generate New Compile Exit Change an existing form specification. -------------------------------------------------Press CTRL-W for Help------

If you select this option, you are prompted to select the name of a form specification file to modify. Source files created at the FORM Design Menu (or at the command line by the FORM4GL screen form facility) have the file extension .per.

1-44

Compiling 4GL Source Files

The FORM Design Menu

If you have not already designated a text editor in this INFORMIX-4GL session or with DBEDIT, you are prompted for the name of an editor. Then an editing session begins, with the form specification source-code file that you specified as the current file. When you leave the editor, INFORMIX-4GL displays the MODIFY FORM Menu with the Compile option highlighted.
MODIFY FORM: Compile Save-and-exit Compile the form specification. Discard-and-exit

-------------------------------------------------Press CTRL-W for Help------

Now you can press RETURN to compile the revised form specification file. If the compiler finds errors, the COMPILE FORM Menu appears:
COMPILE FORM: Correct Exit Correct errors in the form specification. -------------------------------------------------Press CTRL-W for Help------

Press RETURN to select Correct as your option. An editing session begins on a copy of the current form, with diagnostic error messages embedded where the compiler detected errors. INFORMIX-4GL deletes these messages when you save and exit from the editor. After you correct the errors, the MODIFY FORM Menu appears again, with the Compile option highlighted. Press RETURN to recompile. If there are no compilation errors, you are prompted whether to save the modified form specification file and the compiled form, or to discard the changes. (Discarding the changes restores the version of your form specifications from before you chose the Modify option.)

Compiling 4GL Source Files

1-45

The FORM Design Menu

The Generate Option
You can type g or G to select the Generate option. This option creates a simple ‘‘default’’ screen form for use directly in your 4GL program, or for you to edit later by selecting the Modify option.
FORM: Modify Generate New Compile Exit Generate and compile a default form specification. -------------------------------------------------Press CTRL-W for Help------

When you select this option, INFORMIX-4GL prompts you to select a database, to choose a filename for the form specification, and to identify the tables that the form will access. After you provide this information, INFORMIX-4GL creates and compiles a form specification file. (This is equivalent to running the -d (default) option of FORM4GL, as described near the end of Chapter 4, “Form Building and Compiling.”)

The New Option
The New option of the FORM Design Menu enables you to create a new screen form specification.
FORM: Modify Generate New Compile Create a new form specification. Exit

-------------------------------------------------Press CTRL-W for Help------

After prompting you for the name of your form specification file, INFORMIX-4GL places you in the editor where you can create a form specification file. When you leave the editor, INFORMIX-4GL transfers you to the NEW FORM Menu that is like the MODIFY FORM Menu. You can compile your form and correct it in the same way.

1-46

Compiling 4GL Source Files

The FORM Design Menu

The Compile Option
The Compile option enables you to compile an existing form specification file without going through the Modify option.
FORM: Modify Generate New Compile Exit Compile an existing form specification. -------------------------------------------------Press CTRL-W for Help------

INFORMIX-4GL prompts you for the name of the form specification file and then performs the compilation. If the compilation is not successful, INFORMIX-4GL displays the COMPILE FORM Menu with the highlight on the Correct option.

The Exit Option
The Exit option clears the FORM Design Menu from the screen.
FORM: Modify Generate New Compile Returns to the INFORMIX-4GL Menu. Exit

-------------------------------------------------Press CTRL-W for Help------

Selecting this option restores the INFORMIX-4GL Menu:
INFORMIX-4GL: Module Form Program Query-language Exit Create, modify or run individual 4GL program modules. -------------------------------------------------Press CTRL-W for Help------

Compiling 4GL Source Files

1-47

The PROGRAM Design Menu

The PROGRAM Design Menu
An INFORMIX-4GL program can be a single source-code module that you create and compile at the MODULE Design Menu. For applications of greater complexity, however, it is often easier to develop and maintain an INFORMIX-4GL program that includes several modules. The INFORMIX-4GL Menu includes the Program option so that you can create multiple-module programs. When you select this option, INFORMIX-4GL searches your DBPATH directories (see Appendix C) for the program specification database, called syspgm4gl. This database describes the runner options and the modules of your program. If INFORMIX-4GL cannot find this database, you are asked if you want one created. If you enter y in response, INFORMIX-4GL creates the syspgm4gl database, grants CONNECT privilege to PUBLIC, and displays the PROGRAM Design Menu. As Database Administrator of syspgm4gl, you can later restrict the access of other users. If syspgm4gl already exists, the PROGRAM Design Menu appears.
PROGRAM: Modify New Compile Planned_Compile Run Debug Undefine Change the compilation definition of a 4GL application program. Exit

-------------------------------------------------Press CTRL-W for Help------

You can use this menu to create or modify a multi-module 4GL program specification, to compile a program, or to execute or analyze a program. The PROGRAM Design Menu supports the following eight options: Modify New Compile Planned_Compile Run Debug Undefine Exit
1-48 Compiling 4GL Source Files

Change an existing program specification. Create a new program specification. Compile an existing program. Display the steps to compile an existing program. Execute an existing program. Invoke the INFORMIX-4GL Interactive Debugger. Delete an existing program specification. Return to the INFORMIX-4GL Menu.

The PROGRAM Design Menu

You must first use the MODULE Design Menu and FORM Design Menu to enter and edit the INFORMIX-4GL statements within the component source-code modules of a 4GL program. Then you can use the PROGRAM Design Menu to identify which modules are part of the same application program, and to combine all the 4GL modules in an executable program.

The Modify Option
The Modify option enables you to modify the specification of an existing 4GL program. (This option is not valid unless at least one program has already been specified. If none has, you can create a program specification by selecting the New option from the same menu.) INFORMIX-4GL prompts you for the name of the program specification you want to modify. It then displays a screen and menu that you can use to update the information in the program specification database, as shown in Figure 1-3:
MODIFY PROGRAM: 4GL Globals Edit the 4GL sources list. Other Program_Runner Rename Exit

-------------------------------------------------Press CTRL-W for Help-----Program [myprog ] Runner [fglgo ] Runner Path [ ] Debugger [fgldb ] Debugger Path [ ] 4gl Source [main [funct [rept [ [ 4gl Source Path [/u/john/appl/4GL [/u/john/appl/4GL [/u/john/appl/4GL [ [ Global Source Path [ [ Other .4go Path [ [

] ] ] ] ]

] ] ] ] ]

Global Source [ ] [ ] Other .4go [obj ] [ ]

] ]

] ]

Figure 1-3

Example of a Program Specification Entry

The name of the program appears in the Program field. In Figure 1-3 this name is myprog. You can change the name by selecting the Rename option. The program name, with extension .4gi, is assigned to the program produced by compiling and combining all the source files. (Compiling and combining is done by the Compile option, as described later in this chapter, or by the Program_Compile option of the MODULE Design Menu.) In this case, the runable program would have the name myprog.4gi.
Compiling 4GL Source Files 1-49

The PROGRAM Design Menu

The 4GL option enables you to update the entries for 4gl Source and 4gl Source Path. The five rows of fields under these labels form a screen array. If you select the 4GL option, INFORMIX-4GL executes an INPUT ARRAY statement so you can move through the array and scroll for up to a maximum of 100 entries. The INPUT ARRAY statement description in Chapter 7 explains how to use function keys to scroll, delete rows, and insert new rows. (You cannot redefine function keys, however, as you can with an INFORMIX-4GL program.) In the example shown in Figure 1-3, the 4GL source program has been broken into three modules: a module containing the MAIN program block (main.4gl), a module containing functions (funct.4gl), and a module containing REPORT statements (rept.4gl). These modules are all located in the directory /u/john/appl/4GL. If a module contains only global variables, you can list it here or in the Global Source array. The Globals option enables you to update the Global Source array. If you use the Global Source array to store a globals module, any modification of the globals module file causes all 4GL modules to be recompiled when you select the Compile option. The Other option enables you to update the entries for the Other .4go and Other .4go Path fields. This is where you specify the name and location of other 4GL object files (.4go files) to include in your program. Do not specify the filename extensions. You can list up to 100 files in this array. The Program_Runner option enables you to specify the name and location of the p-code runner to execute your program. You can run INFORMIX-4GL programs with fglgo (the default) or with a customized p-code runner. A customized p-code runner is an executable program that you create to run 4GL programs that call C functions, as described later in this chapter. If you do not modify the Runner field, your program is executed by fglgo when you select the Run option from the PROGRAM Design Menu. The MODIFY PROGRAM screen form contains two additional fields labeled Debugger and Debugger Path. If you have the INFORMIX-4GL Interactive Debugger, you can also use the Program_Runner option to enter the name of a customized Debugger. See the section “RDS Programs That Call C Functions” later in this chapter for information about the use of a customized Debugger. For the procedures to create a customized Debugger, refer to Appendix C of the Guide to the INFORMIX-4GL Interactive Debugger, which includes an example. The Exit option of the MODIFY PROGRAM Menu returns you to the PROGRAM Design Menu.
1-50 Compiling 4GL Source Files

The PROGRAM Design Menu

The New Option
The New option of the PROGRAM Design Menu enables you to create a new specification of the program modules and libraries that make up the desired application program.
PROGRAM: Modify New Compile Planned_Compile Run Debug Undefine Add the compilation definition of a 4GL application program. Exit

-------------------------------------------------Press CTRL-W for Help------

The New option is identical to the Modify option, except that you must first supply a name for your program. INFORMIX-4GL then displays a blank form with a NEW PROGRAM Menu that has the same options as the MODIFY PROGRAM Menu.

The Compile Option
The Compile option compiles and combines the modules listed in the program specification database, taking into account the time when files were last updated. INFORMIX-4GL compiles only those files that have been modified since they were last compiled, except in the case where you have modified a module listed in the Global Source array. If you have modified a module that is listed in the Global Source array, all files are recompiled.
PROGRAM: Modify New Compile Planned_Compile Compile a 4GL application program. Run Debug Undefine Exit

-------------------------------------------------Press CTRL-W for Help------

The Compile option produces a runable p-code file with a .4gi extension. INFORMIX-4GL lists each step of the compilation as it occurs.

Compiling 4GL Source Files

1-51

The PROGRAM Design Menu

The Planned_Compile Option
Taking into account the time of last change for the various files in the dependency relationships, the Planned_Compile option prompts for a program name and displays a summary of the steps that will be executed if you select Compile. No compilation actually takes place.
PROGRAM: Modify New Compile Planned_Compile Run Debug Undefine Show the planned compile actions of a 4GL application program. Exit

-------------------------------------------------Press CTRL-W for Help-----Compiling INFORMIX-4GL sources: /u/john/appl/4GL/main.4gl /u/john/appl/4GL/funct.4gl /u/john/appl/4GL/rept.4gl Linking other objects: /u/john/appl/Com/obj.4go

If you have made changes in all the components of the program listed in Figure 1-3 since the last time they were compiled, INFORMIX-4GL displays the previous screen.

The Run Option
Select the Run option to execute a compiled program.
PROGRAM: Modify New Compile Planned_Compile Run Debug Execute a 4GL application program Undefine Exit

-------------------------------------------------Press CTRL-W for Help------

The screen lists any compiled programs (files with the extension .4gi) and highlights the current program, if one has been specified. This option resembles the Run option of the MODULE Design Menu. Although .4go files are not displayed, you can also enter the name and extension of a .4go file. Whatever compiled program you select is executed by fglgo, or by the runner that you specified in the Runner field of the Program Specification screen. This screen was illustrated earlier, in the description of the MODIFY PROGRAM Menu.
1-52 Compiling 4GL Source Files

The PROGRAM Design Menu

The Debug Option
The Debug option works like the Run option but enables you to examine a 4GL program with the INFORMIX-4GL Interactive Debugger. This option is not implemented unless you have purchased the Debugger.
PROGRAM: Modify New Compile Planned_Compile Run Debug Undefine Drop the compilation definition of a 4GL application program. Exit

-------------------------------------------------Press CTRL-W for Help------

The Undefine Option
The Undefine option of the PROGRAM Design Menu prompts you for a program name and removes the compilation definition of that program from the syspgm4gl database. This action removes the definition only. Your program and 4GL modules are not removed.
PROGRAM: Modify New Compile Planned_Compile Run Debug Undefine Drop the compilation definition of a 4GL application program. Exit

-------------------------------------------------Press CTRL-W for Help------

The Exit Option
The Exit option clears the PROGRAM Design Menu from the screen and restores the INFORMIX-4GL Menu.

Compiling 4GL Source Files

1-53

The QUERY LANGUAGE Menu

The QUERY LANGUAGE Menu
The SQL interactive interface is identical to the interactive SQL interface of INFORMIX-SQL. You can use this option only if you have separately purchased and installed INFORMIX-SQL on your system. The Query-language option is placed at the top-level menu so you can test SQL statements without leaving the INFORMIX-4GL Programmer’s Environment. You can also use this option to create, execute, and save SQL scripts.

Creating Executable RDS Programs
To create an INFORMIX-4GL application with the INFORMIX-4GL Rapid Development System requires the following steps: 1. Create or modify a .4gl source file. 2. Compile the source file into a .4go p-code file. 3. Combine multiple .4go modules into a single .4gi file. 4. Invoke the INFORMIX-4GL runner, specifying a 4GL program. Step 3 is not required if your program has only one module. The sections that follow describe how to carry out these steps, both from the Programmer’s Environment and at the system prompt. Subsequent sections of this chapter describe how to use the INFORMIX-4GL Rapid Development System to compile and execute 4GL programs that call C functions. (These special Rapid Development System procedures require a C language compiler and linker, which are unnecessary for 4GL applications that do not call programmer-defined C functions.)

Working in the RDS Programmer’s Environment
If your software has been installed according to the instructions in your Installation Guide, you can enter r4gl at the system prompt to invoke the Programmer’s Environment. After a sign-on message, the INFORMIX-4GL Menu appears.

1-54

Compiling 4GL Source Files

Working in the RDS Programmer’s Environment

Creating a New Source Module
This section outlines the procedure for creating a new module. If your source module already exists but needs to be modified, skip ahead to the next section, ‘‘Revising an Existing Module.’’

• Press RETURN at the INFORMIX-4GL Menu to select the Module option.
The screen displays the MODULE Design Menu.

• If you are creating a new .4gl source module, press n to select the New
option of the MODULE Design Menu. The screen prompts you for a name to assign to the new module.

• Enter a name for the new module. The name must begin with a letter, and
can include letters, numbers, and underscores. The name must be unique among the files in the same directory, and among the other program modules, if it will be part of a multi-module program. INFORMIX-4GL attaches extension .4gl to this identifier, as the filename of your new source module.

Revising an Existing Module
If you are revising an existing 4GL source file, rather than creating a new one, the procedures to begin an editing session are slightly different from the steps that were just described.

• Select the Modify option of the MODULE Design Menu. • The screen lists the names of all the .4gl source modules in the current
directory and prompts you to select a source file to edit. Use the Arrow keys to highlight the name of a source module and press RETURN, or enter a filename (with no extension). If you specified an editor with the DBEDIT environment variable, an editing session begins automatically. Otherwise, the screen prompts you to specify a text editor.

• Specify the name of a text editor, or press RETURN for vi, the default editor. Now you can begin an editing session by entering 4GL statements. (The chapters that follow describe INFORMIX-4GL statements and programs.)

• When you have finished entering or editing your 4GL code, use an appropriate editor command to save your source file and end the text editing session.

Compiling 4GL Source Files

1-55

Working in the RDS Programmer’s Environment

Compiling a Source Module
The .4gl source file module that you create or modify is an ASCII file that must be compiled before it can be executed. After you save your file and exit from the editor, the screen prompts you to choose among Compile, Save-and-exit, or Discard-and-exit options.

• Select the Compile option to compile the module. After you select
Compile, the screen prompts you to select among Object, Runable, and Exit options. What you should do depends on whether your module is a complete program, or whether it is one of several .4gl modules that together comprise a complete program.

• If the module is a complete 4GL program that requires no other modules,
select Runable. This option creates a compiled p-code version of your program module, with the same filename, but with extension .4gi.

• If the module is one module of a multi-module 4GL program, select
Object. This creates a compiled p-code version of your program module, with the same filename, but with extension .4go. See also the procedures for combining program modules, which are described later in this section. If the compiler detects errors after either option, no compiled file is created, and the screen prompts you to select Correct or Exit. Follow the first two steps on the next page after an error.

• Select Correct to resume the previous text editing session, with the
same 4GL source code, but with error messages in the file.

• Edit the file to correct the error, and select Compile again. If an error
message appears, repeat the previous steps, until the module compiles without error.

• After the module compiles successfully, the screen prompts you again to
Compile, or to Save-and-exit, or to Discard-and-exit. Select the second option to save the compiled program. The MODULE Design Menu appears again on your screen.

• If your program requires screen forms, you must select Exit to return to the
INFORMIX-4GL Menu and then select Form to display the FORM Design

Menu. See Chapter 4 for information about designing and creating screen forms.

• If your program displays help messages, you must create a help file and
compile it with the mkmessage utility. See Chapter 8 of the INFORMIX4GL User Guide for more information about implementing help messages in INFORMIX-4GL programs.

1-56

Compiling 4GL Source Files

Working in the RDS Programmer’s Environment

Combining Program Modules
If the module that you compiled is the only module in your program, you are now ready to run your program, and you can skip the steps that are described here. If your new or modified module is part of a multi-module 4GL program, however, you must combine all of the modules into a single program file before you can run the program.

• If you are not at the INFORMIX-4GL Menu, select Exit until that menu
appears. Then select the Program option to display the PROGRAM Design Menu.

• Select the New option if you are creating a new multi-module 4GL
program, or select Modify if you are modifying an existing one. In either case, the screen prompts you for the name of a program.

• Enter the name (without a file extension) of the program that you are
modifying, or the name to be assigned to a new program. Names must begin with a letter, and can include letters, underscores ( _ ), and numbers. After you enter a valid name, the PROGRAM screen appears, with your program name in the first field. If you selected Modify, the names and pathnames of the source-code modules are also displayed. The PROGRAM screen appears below the MODIFY PROGRAM Menu, rather than below the NEW PROGRAM Menu. (Both menus list the same options.)

NEW PROGRAM: 4GL Globals Edit the 4GL sources list.

Other

Program_Runner

Rename

Exit

----------------------------------------------- Press CTRL-W for Help ------Program [ ] Runner [fglgo ] Runner Path [ ] Debugger[fgldb ] Debugger Path [ ] 4gl Source [ ] [ ] [ ] [ ] [ ] 4gl Source Path [ [ [ [ [

] ] ] ] ]

Global Source Global Source Path [ ] [ [ ] [ Other .4go [ ] [ ] Other .4go Path [ [

] ]

] ]

Compiling 4GL Source Files

1-57

Working in the RDS Programmer’s Environment

• To specify new 4GL modules or edit the list of 4GL modules, press
RETURN to select the 4GL option. You can enter or edit the name of a module, without the .4gl file extension. Repeat this step for every module. If the module is not in the current directory or in a directory specified by the DBPATH environment variable, enter the pathname to the directory where the module resides.

• The name of the runner (and of the Debugger, if you have the INFORMIX-4GL Interactive Debugger) are usually as illustrated in the PROGRAM screen, unless your 4GL program calls C functions. A later sec-

tion of this chapter, “RDS Programs That Call C Functions,” explains how to create a customized runner or Debugger, which you can then specify by selecting the Program_Runner option.

• To enter or edit the name or pathname of a Globals module, select the
Globals option and provide the corresponding information.

• If your program includes any .4go modules that you have already compiled, you can select the Other option to enter or edit their filenames and pathnames.

• After you correctly list all of the modules of your 4GL program, select the
Exit option to return to the PROGRAM Design Menu.

• Select the Compile option of the PROGRAM Design Menu. This produces
a file that combines all of your .4gl source files into an executable program. Its filename is the program name that you specified, with extension .4gi. The screen lists the names of your .4gl source modules and displays the PROGRAM Design Menu with the Run option highlighted. See also the section “Program Filename Extensions (C Compiler Version)” later in this chapter for information about the backup files that are produced automatically when you work at the Programmer’s Environment of the INFORMIX-4GL Rapid Development System.

Executing a Compiled RDS Program
You can type r or press RETURN to select the Run option. This option executes the compiled 4GL program. Menus, screen forms, windows, or other screen output are displayed, according to your program logic and your keyboard interaction with the program.

1-58

Compiling 4GL Source Files

Working at the RDS Command Line

Invoking the Debugger
If you are developing or modifying an INFORMIX-4GL program, you have much greater control over program execution by first invoking the INFORMIX-4GL Interactive Debugger. If you have purchased the Debugger, you can invoke it from the MODULE Design Menu or PROGRAM Design Menu of the Programmer’s Environment by selecting the Debug option. See the Guide to the INFORMIX-4GL Interactive Debugger for detailed information on the use of the Debugger as a programmer’s productivity tool.

Working at the RDS Command Line
You can create the same .4gl source files and compiled .4go and .4gi p-code files at the operating system prompt. Figure 1-4 shows the process of creating, compiling, and running or debugging a single-module program from the command line.

Compiling 4GL Source Files

1-59

Working at the RDS Command Line

TEXT EDITOR

.4gl Source File

P-CODE COMPILER fglpc .4go Compiled p-code File P-CODE RUNNER fglgo
Figure 1-4 Creating and Running a Single-Module Program

DEBUGGER fgldb

Here the rectangles represent processes controlled by specific commands, and the circles represent files. Arrows indicate whether a file serves as input or output for a process. This diagram is simplified and ignores the similar processes by which forms, help messages, and any other components of INFORMIX-4GL applications are compiled and executed.

• The cycle begins in the upper left corner with a text editor, such as vi,
to produce a 4GL source module.

• The program module can then be compiled, using the fglpc p-code
compiler. (If error messages are produced by the compiler, find them in the .err file, and edit the .4gl file to correct the errors. Then recompile the corrected .4gl file.)

1-60

Compiling 4GL Source Files

Working at the RDS Command Line

• The following command line invokes the p-code runner:
fglgo filename where filename specifies a compiled 4GL file to be executed. Executing a program that is undergoing development or modification sometimes reveals the existence of run-time errors. If you have the INFORMIX-4GL Interactive Debugger, you can invoke it to analyze and identify run-time errors in your program by entering the command: fgldb filename where filename specifies your compiled 4GL file. You can then recompile and retest the program. When it is ready for use by others, they can use the fglgo runner to execute the compiled program. A correspondence between commands and menu options of the RDS Programmer’s Environment is summarized by the following list:
Command

vi fglpc fglgo fgldb

Invokes UNIX System Editor 4GL P-Code Compiler 4GL P-Code Runner 4GL Interactive Debugger

Menu Option Module New/Modify Compile Run Debug

Creating or Modifying a 4GL Source File
Use your system editor or another text-editing program to create a .4gl source file, or to modify an existing file. See the documentation of your text editor and the other chapters of this manual for details.

Compiling an RDS Source File
You cannot execute a 4GL program until you have compiled each source module into a .4go file. Do this at the system prompt by entering the fglpc command, which compiles your 4GL source code, and generates a file containing tables of information and blocks of p-code. You can then run this compiled code by using the INFORMIX-4GL p-code runner (or the INFORMIX-4GL Interactive Debugger, if you have the Debugger). The INFORMIX-4GL source-code module to be compiled should have the file extension .4gl. The syntax of a fglpc command line follows:

Syntax
fglpc { -V | [ -ansi ] [ -a ] [ -p pathname ] source [ .4gl ] . . . }

Compiling 4GL Source Files

1-61

Working at the RDS Command Line

Explanation
-V -ansi -a -p pathname source.4gl displays the version number of the software. instructs the compiler to check all SQL statements for compliance with ANSI standards. causes your compiled program to check array bounds at run time. stores object (.4go) files and error (.err) files in the directory specified by pathname. is the name of an INFORMIX-4GL source-code module.

Notes
1. The fglpc command reads source.4gl files and creates a compiled version of each, with the filename source.4go. You can specify any number of source files, in any order, with or without their .4gl filename extensions. 2. If you specify the -V option, the screen displays the version number of your SQL and p-code compiler software. Any other command options are ignored. After displaying this information, the program terminates without compiling. 3. If you specify the -ansi option, it must appear first in your list of fglpc command arguments. The -ansi option asks for compile-time warning messages if your source code includes Informix extensions to the ANSI standard for SQL. (Chapter 7 lists the Informix syntax extensions.) 4. If an error or warning occurs during compilation, INFORMIX-4GL creates a file called source.err. Look in source.err to find where the error or warning occurred in your code. 5. You can use the -p pathname option to specify a non-default directory for the .4go and .err files. Otherwise, any files produced by fglpc are stored in your current working directory. 6. Since the -a option requires additional processing, you may want to use this option only for debugging during development.

Examples
The following command compiles a 4GL source file single.4gl, and creates a file called single.4go in the current directory: fglpc single.4gl The next command line compiles two 4GL source files: fglpc -p /u/ken fileone filetwo
1-62 Compiling 4GL Source Files

Working at the RDS Command Line

This command generates two compiled files, fileone.4go and filetwo.4go, and stores them in subdirectory /u/ken. Any compiler error messages are saved in files fileone.err or filetwo.err in the same directory.

Concatenating Multi-Module Programs
If a program has several modules, the compiled modules must all be concatenated into a single file, as represented in Figure 1-5:

TEXT EDITOR

.4gl Source Files

P-CODE COMPILER fglpc .4go p-code Object Files CONCATENATION UTILITY .4gi p-code Executable Files P-CODE RUNNER fglgo
Figure 1-5 Creating and Running a Multi-Module Program Compiling 4GL Source Files 1-63

Working at the RDS Command Line

The UNIX cat command combines the listed files into the file specified after the redirect symbol (>) in a command line of the form
cat file1.4go file2.4go ... fileN.4go > new.4gi

which combines a list of .4go files into a file called new.4gi. Note: The new filename of the combined file must have either a .4go or a .4gi extension. Throughout this manual, extension .4gi designates runable files that have been compiled (and concatenated, if several source modules comprise the program). You may wish to follow this convention in naming files, since only .4gi files are displayed from within the Programmer’s Environment. This convention is also a convenient way to distinguish complete program files from object files that are individual modules of a multi-module program. If your 4GL program calls C functions or INFORMIX-ESQL/C functions, you must follow procedures that are described in the section ‘‘RDS Programs That Call C Functions’’ before you can run your application.

Running RDS Programs
To execute a compiled 4GL program from the command line, you can invoke the p-code runner, fglgo. Its syntax follows:

Syntax
fglgo { -V | [ -a ] filename[.4go|.4gi ] [ args ] }

Explanation:
-V displays the SQL version number and the p-code version number. After displaying this information, the program quits without invoking the p-code runner. causes array bounds checking at run time. is the name of a compiled 4GL file. The filename must have a .4go or .4gi extension. You do not need to enter this extension on the command line. are any arguments required by your 4GL program.

-a filename

args

1-64

Compiling 4GL Source Files

Working at the RDS Command Line

Notes
1. If you do not specify a filename extension in the command line, fglgo looks first for the filename with a .4gi extension, and then for the filename with a .4go extension. 2. To run a 4GL program that calls programmer-defined C functions, you cannot use fglgo. You must instead use a customized p-code runner. The section ‘‘RDS Programs That Call C Functions’’ describes how to create a customized runner.

Examples
To run a compiled program named myprog.4go, enter the following command line at the operating system prompt:
fglgo myprog

or
fglgo myprog.4go

Running Multi-Module Programs
To run a program with multiple modules, you must compile each module and then combine them by an operating system concatenation utility, as described in an earlier section. For example, if mod1.4go, mod2.4go, and mod3.4go are compiled INFORMIX-4GL modules that you want to run as one program, you must first combine them as in the following example:
cat mod1.4go mod2.4go mod3.4go > mods.4gi

You can then run the mods.4gi program by using the command lines:
fglgo mods

or
fglgo mods.4gi

Running Programs with the Interactive Debugger
You can also run compiled 4GL programs with the INFORMIX-4GL Interactive Debugger. This 4GL source-code debugger is a p-code runner with a rich command set for analyzing 4GL programs. You can use the Debugger to locate logical and run-time errors in your 4GL programs and to become more familiar with 4GL programs. The Debugger must be purchased separately from INFORMIX-4GL.

Compiling 4GL Source Files

1-65

Working at the RDS Command Line

If you have the Debugger, you can invoke it at the system prompt by a command line of the form:
fgldb filename

Here filename is any runable 4GL file that you produced by an fglpc command. See Chapter 8 of the Guide to the INFORMIX-4GL Interactive Debugger for the complete syntax of the fgldb command.

RDS Programs That Call C Functions
If your INFORMIX-4GL Rapid Development System program calls programmer-defined C functions, you must create a customized runner to execute the program. You can do this by following two steps: 1. Edit a structure definition file to contain information about your C functions. This file is named fgiusr.c and is supplied with INFORMIX-4GL. 2. Compile and link the fgiusr.c file with the files that contain your C functions. To do this, use the cfglgo command. You can then use the runner produced by the cfglgo command to run the 4GL program that calls your C functions. Both the fgiusr.c file and the cfglgo command are described in the pages that follow. Note: To create a customized runner, you must have a C compiler installed on your system. You do not need a C compiler, however, and you do not need to follow the procedures described in this section, if the only functions that your INFORMIX-4GL Rapid Development System program calls are INFORMIX-4GL or INFORMIX-ESQL/C library functions, or functions written in the INFORMIX-4GL language.

1-66

Compiling 4GL Source Files

Working at the RDS Command Line

Editing the fgiusr.c File
With your INFORMIX-4GL software, you receive a file named fgiusr.c. This file is located in the etc subdirectory of the directory in which you install INFORMIX-4GL (that is, in INFORMIXDIR/etc). The following listing shows the fgiusr.c file in its unedited form:
/********************************************************** * * * INFORMIX SOFTWARE, INC. * * * * Title: fgiusr.c * * Sccsid: @(#)fgiusr.c 4.2 8/26/87 10:48:37 * * Description: * * definition of user C functions * * * *********************************************************** */ /******************************************************* * This table is for user-defined C functions. * * Each initializer has the form: * * "name", name, nargs * * Variable # of arguments: * * set nargs to -(maximum # args) * * Be sure to declare name before the table and to leave the * line of 0’s at the end of the table. * * Example: * * You want to call your C function named "mycfunc" and it expects * 2 arguments. You must declare it: * * int mycfunc(); * * and then insert an initializer for it in the table: * * "mycfunc", mycfunc, 2 ********************************************************* */ #include "fgicfunc.h" cfunc_t usrcfuncs[] = { 0, 0, 0 };

The fgiusr.c file is a C language file that you can edit to declare any number of programmer-defined C functions.

Compiling 4GL Source Files

1-67

Working at the RDS Command Line

To edit fgiusr.c, you can copy the file to any directory. (Unless this is your working directory at compile time, you must specify the full pathname of the edited fgiusr.c file when you compile.) Edit fgiusr.c to specify the following:

• A declaration for each function: •
int function-name( ); Three initializers for each function:
" function-name ", function-name, [ - ] integer,

The symbols ( ) ; must follow function-name in the declaration. The first initializer is a character pointer (the function name between double quotation marks). The second is a function pointer (the name without quotes). The third is an integer (for the number of arguments expected by the function). If the number of arguments expected by the function can vary, make the third argument the maximum number of arguments, prefixed with a minus ( - ) sign. You must use commas ( , ) to separate the three initializers. Insert a set of initializers for each C function that you declare. A line of three zeroes indicates the end of the structure. Here is an example of an edited fgiusr.c file: #include "fgicfunc.h" int function-name(); cfunc_t usrcfuncs[] = { " function-name",function-name,1, 0,0,0 } Here the 4GL program will be able to call a single C function called function-name that has one ( 1 ) argument. If you have several 4GL programs that call C functions, you can use fgiusr.c in either of two ways:

• You can create one customized p-code runner. In this case, you can edit
fgiusr.c to specify all the C functions called from all your 4GL programs. After you create one comprehensive runner, you can use it to execute all your 4GL applications.

• You can create several application-specific runners. In this case, you can
either make a copy of the fgiusr.c file (with a new name) for each custom1-68 Compiling 4GL Source Files

Working at the RDS Command Line

ized runner, or you can re-edit fgiusr.c to contain information on the C functions for a specific application before you compile and link. If you create several runners, you must know which customized runner to use with each 4GL application. In some situations the first method is more convenient, since users do not have to keep track of which runner supports each 4GL application.

Creating a Customized Runner
You can use the cfglgo command to create a customized runner. You can use cfglgo to compile C modules and INFORMIX-ESQL/C modules that contain functions declared in an edited fgiusr.c file.

Syntax
cfglgo { -V | fgiusr.c cfile. { ec | c | o } [ . . . ] [ -o newfglgo ] }

Explanation
-V fgiusr.c cfile displays the version number of the software. is the name of the file that you edited to declare C and/or
INFORMIX-ESQL/C functions.

is the name of a source file containing INFORMIX-ESQL/C or C functions to be compiled and linked with the new runner; or the name of an object file previously compiled from a .c or .ec file. specifies the name of the customized runner.

-o newfglgo

Notes
1. The cfglgo command compiles and links the edited fgiusr.c file with your C program files into an executable program that can run your 4GL application. 2. You can rename an edited structure definition file. If you do so, specify its new filename in place of fgiusr.c. 3. If you do not specify the -o newfglgo option, the new runner is given the default name a.out. 4. You can specify any number of uncompiled or compiled C or INFORMIX-ESQL/C files in a cfglgo command line. 5. You must have the INFORMIX-ESQL/C product to compile INFORMIX-ESQL/C files with cfglgo.
Compiling 4GL Source Files 1-69

Working at the RDS Command Line

6. If the fgiusr.c file to be linked is not in the current directory, you must specify a full pathname. 7. The customized runner can also run 4GL programs that do not call C functions. 8. The -V option displays the release version numbers of your p-code and SQL software and returns the system prompt. All other arguments are ignored, and no other output is produced.

Examples
The following example 4GL program calls the C function prdate( ): prog.4gl:
main . . . call prdate() . . . end main

The function prdate( ) is defined in file cfunc.c, as shown here: cfunc.c:
#include <stdio.h> #include <time.h> prdate() { /* This program timestamps file FileX */ long cur_date; extern int errno; FILE *fptr; time(&cur_date); fptr = fopen("time_file","a"); fprintf(fptr,"FileX was accessed %s", ctime(&cur_date)); fclose(fptr); }

1-70

Compiling 4GL Source Files

Working at the RDS Command Line

The C function is declared and initialized in the following fgiusr.c file: fgiusr.c:
1 #include "fgicfunc.h" 2 3 int prdate(); 4 cfunc_t usrcfuncs[] = 5 { 6 "prdate", prdate, 0, 7 0, 0, 0 8 };

An explanation of this example of an fgiusr.c file follows: line 1: line 3: line 4: line 6: line 7: The file ‘‘fgicfunc.h’’ is always included. This line already exists in the unedited fgiusr.c file. This is the declaration of the function prdate( ). You must add this line to the file. This line already exists in the unedited file. It declares the structure array usrcfuncs. This line contains the initializers for function prdate( ). Since it expects no arguments, the third value is zero. The line of three zeros indicates that no more functions are to be included.

In this example, you can use the following commands to compile the 4GL program, to compile the new runner, and to run the program: To compile the example 4GL program:
fglpc prog.4gl

To compile the new runner:
cfglgo fgiusr.c cfunc.c -o newfglgo

To run the 4GL program:
newfglgo prog.4go

Compiling 4GL Source Files

1-71

RDS Program Filename Extensions

Running Programs That Call C Functions
After you create a customized runner, you can use it to execute any 4GL program whose C functions you correctly specified in the edited fgiusr.c file. The syntax of a customized runner (apart from its name) is the same as the syntax of fglgo, which was described in an earlier section of this chapter, “Running RDS Programs.” You can also create a customized Debugger to run a 4GL program that calls C functions. See Appendix C of the Guide to the INFORMIX-4GL Interactive Debugger for details and an example of how to create a customized Debugger. You cannot create a customized runner or a customized Debugger from the menus and screen forms of the Programmer’s Environment. You must exit to the system prompt and follow the procedures that were just described if you are developing a 4GL program that calls user-defined C functions. Then you can return to the Programmer’s Environment and use the Program_Runner option of the MODIFY PROGRAM Menu or NEW PROGRAM Menu to specify the name of a customized runner or Debugger.

RDS Program Filename Extensions
Source, runable, error, and backup files generated by INFORMIX-4GL are stored in the current directory and are labeled with a filename extension. The following list shows the file extensions for the source, runable, and error files. These files are produced during the normal course of using the INFORMIX-4GL Rapid Development System. file.4gl file.4go file.4gi file.err is an INFORMIX-4GL source file. is an INFORMIX-4GL file that has been compiled to p-code. is an INFORMIX-4GL file that has been compiled to p-code. is an INFORMIX-4GL source error file, created when an attempt to compile a module fails or produces a warning. The file contains the 4GL source code plus compiler syntax warnings or error messages. is an INFORMIX-4GL object error file, created when an attempt to compile or to link a non-INFORMIX-4GL source-code or object module fails. The file contains 4GL source code and annotated compiler errors.

file.erc

form.per is a FORM4GL source file. form.frm is a FORM4GL object file. form.err
1-72 Compiling 4GL Source Files

is a FORM4GL source error file.

RDS Program Filename Extensions

The last three files do not exist unless you create or modify a screen form specification file, as described in Chapter 4. The next page lists the corresponding file extensions for the backup files that INFORMIX-4GL automatically creates when you use the Programmer’s Environment to process 4GL source files. The following list identifies backup files that are produced when you use INFORMIX-4GL from the Programmer’s Environment. file.4bl file.4bo file.4be file.pbr file.fbm is an INFORMIX-4GL source backup file, created during the modification and compilation of a .4gl program module. is an object backup file, created during the compilation of a .4go program module. is an object backup file, created during the compilation of a .4gi program module. is a FORM4GL source backup file. is a FORM4GL object backup file.

Under normal conditions, INFORMIX-4GL creates the backup files and intermediate files as necessary, and deletes them upon a successful compilation. If you interrupt a compilation, you may find one or more of the files in your current directory. If you compile with a fglpc command line that includes the p pathname option, INFORMIX-4GL creates the .4gi, .4go, .err, and corresponding backup files in the directory specified by pathname, rather than in your current directory. During the compilation process, INFORMIX-4GL stores a backup copy of the file.4gl source file in file.4bl. The time stamp is modified on the (original) file.4gl source file, but not on the backup file.4bl file. In the event of a system crash, you may need to replace the modified file.4gl file with the backup copy contained in the file.4bl file. The Programmer’s Environment does not allow you to begin modifying a .4gl or .per source file if the corresponding backup file already exists in the same directory. After an editing session terminates abnormally, for example, you must delete or rename any backup file before you can resume editing your 4GL module or form from the Programmer’s Environment. This concludes the description of the Rapid Development System. Except as otherwise noted, the descriptions of INFORMIX-4GL elsewhere in this manual describe features that are identical in both the C Compiler Version and Rapid Development System implementations of INFORMIX-4GL.

Compiling 4GL Source Files

1-73

RDS Program Filename Extensions

1-74

Compiling 4GL Source Files

Chapter

INFORMIX-4GL Programming
Chapter Overview 3 Language Conventions 3 Comments 3 INFORMIX-4GL Identifiers 4 Scope of Identifiers 4 Constants 5 String Constants 5 Integer Constants 5 Floating Number Constants 5 Date and Time Constants 6 Program Variables 6 Data Types 7 SMALLINT 7 INTEGER 7 DECIMAL [ (m [, n ] ) ] 7 SMALLFLOAT 8 FLOAT [ ( n ) ] 8 MONEY [ ( m [ , n ] ) ] 8 CHAR [ ( n ) ] 8 DATE 9 DATETIME 9 INTERVAL 9 LIKE table.column 9 RECORD 9 ARRAY [i, j, k] OF type 10 Data Conversion 10

2

Operators and Expressions 11 Number Expressions 11 String Expressions 12 Date and Time Expressions 12 Boolean Expressions 13 Expressions in INFORMIX-4GL Statements Binding to Database and Forms 14 The THRU Keyword and the .* Notation 15 INFORMIX-4GL Statements 16 Variable Definition 17 Assignment 17 Program Organization 17 Program Flow 18 Screen Interaction 19 Report Generation 21 Error and Exception Handling Error Handling 22 Exception Handling 23 Data Validation 23

13

21

Built-in Functions 24 ASCII 25 CLIPPED 27 COLUMN 29 CURRENT 30 DATE 32 DATE( ) 33 DAY( ) 34 EXTEND( ) 35 LENGTH( ) 38 MDY( ) 39 MONTH( ) 40 TIME 41 TODAY 42 UNITS 43 USING 44 Formatting Number Expressions 44 Formatting DATE Expressions 46 WEEKDAY( ) 53 YEAR( ) 54 C Functions 55

2-2

INFORMIX-4GL Programming

Chapter Overview
An INFORMIX-4GL program consists of one or more source files, each containing a series of English-like statements that obey a well-defined syntax. This chapter describes the syntax rules and gives an overview of those statements that do not apply directly to a database. It lists the built-in 4GL functions and describes how to write C functions that can be called by INFORMIX-4GL programs, if you have a C compiler.

Language Conventions
The INFORMIX-4GL programming language contains identifiers, keywords, constants, operators, and expressions. It makes no distinction between uppercase and lowercase letters. It is completely free-form, like C or Pascal, and ignores any extra spaces, tabs, linefeeds, and comments. When necessary, it uses the keyword END in association with the statement type to terminate a statement. Apart from this, it has no statement terminators such as the semicolon.

Comments
For clarity and to simplify program maintenance, it is recommended that you document your code by including comments in your 4GL source files. You can also use comment symbols during program development to disable statements without deleting them. You can indicate comments in any of three ways:

• A comment can begin with the left brace ( { ) and end with the right brace
( } ). You cannot use braces to nest comments.

• You can also use the pound sign ( # ) to begin a comment. The comment
terminates at the end of the line.

INFORMIX-4GL Programming

2-3

INFORMIX-4GL Identifiers

• You can also use a pair of hyphens or minus signs (--) to begin a comment that terminates at the end of the line. (Use of this comment indicator conforms to the ANSI standard.) All text between the braces (or from the # or -- indicator to the end of the line) is ignored.

INFORMIX-4GL Identifiers
INFORMIX-4GL programs can reference constants, local, module, and global

program variables, screen forms, labels, windows, functions, and reports. With the exception of constants, each of these must have an INFORMIX-4GL identifier as a name. An identifier is a sequence of letters, digits, and underscores ( _ ). The first character must be a letter or an underscore. Only the first eight characters are significant, and the case of letters is ignored. Identifiers must not be the same as keywords (which are listed in Appendix D).
INFORMIX-4GL identifiers can be the same as SQL identifiers, but such use requires special attention when you use the identifier in an SQL statement. (See Chapter 3 for a discussion of SQL statements, objects, cursors, and identifiers.)

Scope of Identifiers
Program variables can be either local, modular, or global in their scope of reference.

• Local variables must be defined within a MAIN, FUNCTION, or REPORT
program block. They cannot be referenced by statements outside that program block.

• Module variables must be defined before the first program block (that is,
before the MAIN statement or before any REPORT or FUNCTION statement). They can be referenced only by statements in the same module.

• Global variables must be defined either prior to the MAIN statement
(and in a DEFINE statement preceded by a GLOBALS statement and followed by an END GLOBALS statement) or in a separate globals file. Other program files using these variables must include the statement GLOBALS ‘‘globals-filename’’ (where globals-filename contains the definitions of the global variables).

2-4

INFORMIX-4GL Programming

Constants

Forms, cursors, functions, reports, windows, and some 4GL statements have identifiers that are not program variables. The scope of reference for identifiers of forms, windows, functions, and reports is the entire program. The scope of the identifiers of cursors and PREPAREd statements is from where you DECLARE or PREPARE them until the end of the same module.

Constants
4GL supports string, integer, floating number, and date and time constants. INFORMIX-4GL recognizes three predefined constants: TRUE = 1, FALSE = 0, and NOTFOUND = 100. It also permits the assignment of the value NULL to variables and to database columns. NULL values are distinct from blank

strings or zeros for number variables and columns, and represent unknown values. See the section “NULL Values” in Chapter 3 for details about the behavior of NULL values in expressions.

String Constants
String constants are sequences of up to 80 characters enclosed within double quotes. The constant must be written on a single line (no embedded new lines). You can create longer string variables by concatenating string constants. To include a double quote in a string, precede the double quote with the backslash or repeat the double quote, as in these two equivalent strings:
"Enter \"y\" to select this row" "Enter ""y"" to select this row"

The single quote has no special significance in string constants.

Integer Constants
You must express integer constants in decimal notation without embedded commas and without a decimal point. You can precede the integer with a minus or plus sign, but there can be no space, tab, or new line between the sign and the first digit:
15 -12 13938

Floating Number Constants
Non-integer number constants are expressed only in base 10 with a decimal point. You can use exponential notation as well:
123.456 = 1.23456e2 = 123456.0e-3

INFORMIX-4GL Programming

2-5

Program Variables

Date and Time Constants
String constants that evaluate to DATE values must be enclosed within double quotation marks and can be expressed either with the format mm/dd/yy or with mm/dd/yyyy. The mm stands for the month (1 or 01 for January, 2 or 02, for February, and so on). The dd stands for the day of the month (from 1 to the maximum for that month). Both yy and yyyy stand for the year. When you use only two digits for the year, INFORMIX-4GL assumes that you intend to enter a year beginning with the digits ‘‘19.’’ Values of data types DATETIME or INTERVAL can appear as constants within double quotation ( " ) marks, as in:
"1989-11-23 19:30:00"

or as unquoted literals of the form:
type (values) qualifier

where type is the keyword DATETIME or INTERVAL, values are a list of calendar date values and/or time-of-day values for DATETIME, or else date or time values for INTERVAL; and qualifier identifies the largest and smallest units that the values describe. The following example specifies an instant in time on March 6th, 1989, and illustrates the delimiters that separate fields within the values:
DATETIME (89-3-6 09:55:30.825) YEAR TO FRACTION(3)

You can prefix an INTERVAL literal with ‘‘+’’ or ‘‘-’’ to indicate a positive or negative interval. If the qualifier is only a single field, an INTERVAL can also be of the form:
expression UNITS field

Here expression is a number expression, and field is one of the keywords YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, or FRACTION (n). (The last designates n decimal-place fractions of a second, for 1 ≤ n ≤ 5.) For example, this means ‘‘six months’’:
6 UNITS MONTH

Note: INFORMIX-OnLine supports additional data types. Refer to the INFORMIX-OnLine Programmer’s Manual for more information.

Program Variables
Information transfer among a 4GL screen, report, and database occurs through named memory locations called program variables. You must define the data storage required by a program variable before you can
2-6 INFORMIX-4GL Programming

Data Types

use that variable in an INFORMIX-4GL program. You do this by assigning an identifier to the variable and associating it with a data type, using the DEFINE statement. (See Chapter 7 for details.)

Data Types
INFORMIX-4GL variables must have one of the following data types: SMALLINT INTEGER INT DECIMAL [ (m [ , n ] ) ] DEC [ ( m [ , n ] ) ] NUMERIC [ (m [ , n ] ) ] SMALLFLOAT REAL RECORD [ LIKE table. * ] FLOAT [ ( n ) ] DOUBLE PRECISION [ ( n ) ] MONEY [ (m [ , n ] ) ] CHAR [ ( n ) ] CHARACTER [ (n ) ] DATE DATETIME qualifier INTERVAL qualifier

ARRAY [ i , j , k ] OF type

SMALLINT
This data type includes whole numbers in the range -32,767 to +32,767.

INTEGER
This data type includes whole numbers in the range -2,147,483,647 to +2,147,483,647. You can use the INT keyword as a synonym for INTEGER.

DECIMAL [ (m [, n ] ) ]
This data type includes decimal floating-point numbers with a total of m (≤ 32) significant digits (the precision) and n (≤ m) digits to the right of the decimal point (the scale). When you give values for both m and n, the decimal variable obeys fixed-point arithmetic. All numbers with an absolute value less than 0.5 × 10-n have the value zero. The largest absolute value of a variable of type DECIMAL that can be stored without an error is 10m-n -10-n. The second parameter is optional. If it is missing, INFORMIX-4GL treats the variable as a floating decimal. DECIMAL(m) variables have a precision of m, and a range in absolute value from 10-128 to 10126 When printed without formatting instructions, DECIMAL(m) variables have two decimal places to the
INFORMIX-4GL Programming 2-7

Data Types

right of the decimal point (and an exponent, if necessary). If you designate no range or precision parameters, the default is DECIMAL(16), a floating decimal. You can also use the keywords DEC or NUMERIC as synonyms for DECIMAL.

SMALLFLOAT
This data type includes binary floating-point numbers corresponding to the float data type of the C language. You can use the keyword REAL as a synonym for SMALLFLOAT.

FLOAT [ ( n ) ]
This data type includes floating-point numbers corresponding to the double C data type. Here (n), a whole number between 1 and 14, is an optional parameter to specify the precision. INFORMIX-4GL does not use this parameter, which is provided for compatibility with the ANSI standard. You can use the keywords DOUBLE PRECISION as a synonym for FLOAT.

MONEY [ ( m [ , n ] ) ]
Like the DECIMAL data type, the MONEY data type can also take two parameters. The range of values for columns of type MONEY(m, n) is the same as for columns of type DECIMAL(m, n), but variables of type MONEY are displayed with a currency symbol (by default, the dollar sign). The type MONEY(m) is defined as DECIMAL(m, 2) and, if no parameter is given, MONEY is taken to be DECIMAL(16, 2). Regardless of the number of parameters, INFORMIX-4GL always treats the data type MONEY as a fixed decimal number.

CHAR [ ( n ) ]
These are character strings of length n (where 1 ≤ n ≤ 32,767). If you use the keyword CHAR and do not specify a length, INFORMIX-4GL interprets this to mean CHAR(1). You can refer to substrings of CHAR type program variables in LET, ERROR, MESSAGE, and PROMPT statements with the notation charvariable[m,n], which selects the mth through the nth components of the variable char-variable. (The square brackets are literal, not symbols to indicate an option.) You can use the keyword CHARACTER as a synonym for CHAR.

2-8

INFORMIX-4GL Programming

Data Types

DATE
These are dates from a DATE column or expression, or entered as a character string in one of the formats described earlier in the DATE subsection of ‘‘Date and Time Constants.’’ INFORMIX-4GL stores a DATE variable as an integer, whose value is the number of days since December 31, 1899.

DATETIME
These are instants in time, including both the date and the time-of-day specifications. A DATETIME value specifies a contiguous sequence of the fields: YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, and FRACTION (of a second). A value is entered as a character string, in one of the formats described earlier in the section ‘‘Date and Time Constants.’’ Values are stored internally as decimal numbers with a scale of zero, with a precision factor corresponding to the number of digits implied by the fields. See Appendix J, “Working with DATETIME and INTERVAL Data.”

INTERVAL
This data type includes signed intervals of time, measured in one or more of the same units as DATETIME. A value is entered as a character string in one of the formats described earlier in the section ‘‘Date and Time Constants.’’ INTERVAL values specify a contiguous sequence from one of these lists of fields: YEAR and MONTH, or DAY, HOUR, MINUTE, SECOND, and FRACTION (of a second), but you can specify a non-default precision for a field. Internal storage is the same as for DATETIME values. See also Appendix J, “Working with DATETIME and INTERVAL Data.”

LIKE table.column
You can define the data type of a variable indirectly by indicating that it should have the same data type as a column in the database. If the column has type SERIAL, INFORMIX-4GL assigns it the data type INTEGER but enforces none of the other restrictions on SERIAL types. (Chapter 3 contains the definition of the SERIAL data type.)

RECORD
This data type describes a set of variables of possibly differing data types, including other records. You can refer to individual elements as record_name.element_name and often to record-name.* for the entire set. (But see “The THRU Keyword and the .* Notation,” later in this chapter for limitations on using record-name.*.) You can define a record by listing its elements
INFORMIX-4GL Programming 2-9

Data Conversion

and their types, or by defining it to be LIKE table.* , where table is a table in the database. If defined LIKE table.*, the elements of the record have the same names as the columns of table, and the same corresponding data types.

ARRAY [i, j, k] OF type
This data type describes i × j × k variables of the same data type. ARRAY variables can have from one to three dimensions. You can have arrays of records, but not arrays of arrays. Here the square brackets ( [ ] ) are required and do not represent an option. If char-array[i,j,k] is an array of CHAR type, you can select a substring of one of its components with the chararray[i,j,k][m,n] notation. In this example, i,j,k are indexes into the array, m is the starting position of the substring, and n is the stopping position of the substring. Note: INFORMIX-OnLine supports additional data types. Refer to the INFORMIX-OnLine Programmer’s Manual for more information.

Data Conversion
INFORMIX-4GL performs data-type conversion without objection when the process makes sense. If you assign a number expression to a CHAR variable, INFORMIX-4GL converts the resulting number to a string. If you use a string representation of a number or a date in an arithmetic expression, INFORMIX-4GL converts the string or date to an appropriate number. INFORMIX-4GL produces an error message only if it could not make the conversion.

For example, it converts the string ‘‘123.456’’ to the number 123.456 in an addition, but adding the string ‘‘John’’ to a number produces an error.
INFORMIX-4GL carries out all arithmetic in an arithmetic expression in type DECIMAL. The type of the resulting variable determines the format of the

stored or printed result. The following rules apply to the precision and scale of the DECIMAL variable that results from an arithmetic operation on two numbers:

• All operands, if not already DECIMAL, are converted to DECIMAL, and the
resulting number is DECIMAL.
Convert Type FLOAT SMALLFLOAT INTEGER SMALLINT To DECIMAL(16) DECIMAL(8) DECIMAL(10,0) DECIMAL(5,0)

• The precision and scale of the result of an arithmetic operation depend on
the precision and scale of the operands and on the type of arithmetic
2-10 INFORMIX-4GL Programming

Operators and Expressions

expression. The rules are summarized in the table at the end of this section for arithmetic operations on operands with definite scale. When one of the operands has no scale (floating decimal), the result is a floating decimal.

• In addition and subtraction, INFORMIX-4GL adds trailing zeros to the
operand with the smallest scale until the scales are equal.

• If the type of the result of an arithmetic operation requires the loss of significant digits INFORMIX-4GL reports an error.

• Leading or trailing zeros are not considered significant digits, and do not
contribute to the determination of precision and scale. In this table, p1 and s1 are the precision and scale of the first operand, and p2 and s2 are the precision and scale of the second operand.
Operation Addition and Subtraction Multiplication Division Precision and Scale of Result Precision: MIN(32, MAX(p1 - s1, p2 - s2) + MAX(s1, s2) + 1) Scale: MAX(s1, s2) Precision: Scale: Precision: Scale: MIN(32, p1+ p2) s1 +s2 32 32 - p1 + s1 - s2 (This cannot be negative.)

Operators and Expressions
INFORMIX-4GL expressions can be categorized as number, string, date and time, and Boolean. Number expressions can be either integer (evaluating to INTEGER or SMALLINT) or non-integer (evaluating to FLOAT, SMALLFLOAT, MONEY, or DECIMAL). Because of the automatic conversion capability of INFORMIX-4GL, DATE type variables can occur in integer, string, or date and time expressions. Number variables can occur in number, string, or date and time expressions.

Number Expressions
A number expression consists of a number constant, variable, column name, or function that returns a number value; or one of these, connected to a number expression by one of these arithmetic operators:

INFORMIX-4GL Programming

2-11

Operators and Expressions

Operator ** * / mod + -

Operation Exponentiation Multiplication Division Modulus Addition Subtraction

String variables that are character representations of numbers are converted to numbers when used in number expressions. A string that is not a character representation of a number causes an error if used in a number expression.

String Expressions
A string expression is a string constant, a CHAR type variable or column, or a function returning a CHAR type; or any combination of these, combined or altered by the following string operators:
Operator , [m,n] CLIPPED USING WORDWRAP Operation Concatenation Substring where m is the starting position and n is the ending position Drop trailing blanks Formatting Display long strings in multiple lines

Number constants, variables, and columns are converted to their character representation when used in string expressions. See the description of the USING function near the end of this chapter for information about formatting numbers and dates. The WORDWRAP function is used only in 4GL reports, and is described in Chapter 5. The next page lists 4GL Boolean operators on string expressions.

Date and Time Expressions
Date and time expressions are constants, variables, column names, string literals, or expressions with the UNITS, TODAY, or CURRENT keywords that evaluate to a DATE, DATETIME, or INTERVAL value. They can also be any date or time expression combined with another date or time expression (or with a number) by an arithmetic operator, as summarized in the “Operations on DATETIME and INTERVAL Values” section of Appendix J. Some arithmetic operations involving date and time values require that you use the EXTEND function to adjust the precision of the date or time value. You can read more about EXTEND later in this chapter.
2-12 INFORMIX-4GL Programming

Operators and Expressions

Boolean Expressions
A Boolean expression evaluates to TRUE or FALSE (or UNKNOWN, if NULL values are involved) and can take any of the following forms:

• expr rel-op expr
Here expr is an expression and rel-op is a relational operator:
Operator = != or <> > >= < <= Operation Equal to Not equal to Greater than Greater than or equal to Less than Less than or equal to

(For string expressions, greater than means ‘‘after’’ in the ASCII collating order, as listed in Appendix H. Lowercase letters are after uppercase letters, which are after numerals. For DATE and DATETIME values, greater than means ‘‘later’’ in time.)

• • • • • • •

string-expr [ NOT ] LIKE string-expr [ ESCAPE " esc-char " ] string-expr [ NOT ] MATCHES string-expr expr IS [ NOT ] NULL expr [ NOT ] BETWEEN expr AND expr expr [ NOT ] IN ( { items | SELECT-statement } ) expr rel-op { ALL | ANY | SOME } ( SELECT-statement )
EXISTS ( SELECT-statement )

[ ESCAPE " esc-char " ]

The last four expressions apply only in WHERE clauses of SELECT statements. (See “The SELECT Statement” near the end of Chapter 7 for details and for an explanation of the ESCAPE keyword.) Boolean expressions can be compounded with the operators NOT, AND, and OR:
[ NOT ] Boolean-expr [ { AND | OR } Boolean-expr ]

Expressions in INFORMIX-4GL Statements
For the CASE, IF, and WHILE statements in INFORMIX-4GL, TRUE is any non-zero number and FALSE is zero. In these statements you can use a number expression where a Boolean expression is called for. You can use a Boolean expression where a number expression would be expected, yielding 1 or 0. You can use a string expression that is a representation of a number

INFORMIX-4GL Programming

2-13

Binding to Database and Forms

anywhere that a number expression is allowed. If you use a string expression where a Boolean expression is expected and the string expression does not represent a number, it will be evaluated as zero or FALSE. A Boolean expression containing a NULL value has an UNKNOWN truth value, but it is treated as FALSE in INFORMIX-4GL statements. This can lead to unfamiliar consequences. If a is a Boolean expression, the compound expression a OR NOT a would be tautologically TRUE in two-valued logic. If a contains a NULL value (and does not contain the IS NULL keywords), its truth value is UNKNOWN. The truth value of NOT a is also UNKNOWN. INFORMIX-4GL treats both these and their combination with OR as FALSE. If there is any chance that a variable may have a NULL value, you should test it before using it in a Boolean expression. See the section “NULL Values” in Chapter 3 for more details.

Binding to Database and Forms
Regardless of how you have defined them, there is no implicit relationship between program variables, screen fields, and database columns. Even when a variable lname is defined to be LIKE customer.lname, changes to the program variable do not imply any change in the column value. Similarly, even if you created screen field customer.lname using the same database column as a model, there is no inherent connection between the program variable and the field. You must indicate the binding explicitly in any 4GL statement that connects program variables to screen forms or to database columns. The following two statements take input from the screen and insert the value entered on the screen into the database. Here the @ sign tells INFORMIX-4GL that the first lname is the name of a database column.
INPUT lname FROM customer.lname INSERT INTO customer (@lname) VALUES (lname)

Some statements permit temporary binding through the identity of the variable name and the screen field name. (See the individual statement descriptions in Chapter 7 for the appropriate syntax.) The following statement could replace the previous INPUT statement:
INPUT BY NAME lname

2-14

INFORMIX-4GL Programming

The THRU Keyword and the .* Notation

The THRU Keyword and the .* Notation
INFORMIX-4GL provides two devices to simplify the writing of 4GL statements that refer to elements of a record or columns of a table. One of these devices involves the keyword THRU (or THROUGH, its synonym), and the other involves the .* notation. INITIALIZE pr_rec.element4 THRU pr_rec.element8 TO NULL DISPLAY pr_rec.* TO sc_rec.*

The INITIALIZE statement above sets to NULL the values of program variables pr_rec.element4, pr_rec.element5, pr_rec.element6, pr_rec.element7, and pr_rec.element8. The DISPLAY statement lists the entire record pr_rec on the screen fields described by the screen record sc_rec. (Chapter 4 describes screen records.) With one exception, discussed at the end of this section, these devices are a shorthand for writing out a partial or full list of record elements or the columns of a table, with comma ( , ) separating individual items. The order of the items in the list is the order they had when defined. There are, however, the following limitations on their use:

• You cannot use THRU in reference to columns of database tables. There is
no shorthand for a partial listing of columns of a table.

• In the definition of a screen record, THRU runs through all the fields in the
order that they are listed in the ATTRIBUTES section of the form specification file, from the field first named to the last. An example follows:
ATTRIBUTES ... f002=tab1.aa; f003=tab1.bb; f004=tab1.cc; f005=tab2.aa; f006=tab2.bb; f007=tab3.aa; f008=tab3.bb; f009=tab3.cc; ... INSTRUCTIONS SCREEN RECORD sc_rec (tab1.cc THRU tab3.bb)

INFORMIX-4GL Programming

2-15

INFORMIX-4GL Statements

The previous excerpt from a form specification file leads to the following list of elements of sc_rec:
tab1.cc tab2.aa tab2.bb tab3.aa tab3.bb

• You cannot use THRU to indicate a partial list of screen record elements
when displaying to a form or inputting from a form.

• You cannot use either THRU or the .* notation on a record that contains an
array among its elements. For example, you cannot use myrec.* to refer to all the elements of a record defined as follows:
DEFINE myrec RECORD ri INTEGER, ra ARRAY[2] OF INTEGER END RECORD

• You can use the .* or THRU notation, however, for records that contain
records as elements.

• You cannot use THRU or the .* notation in the argument list when defining
a function or report program block. You can, however, list a record as an argument of a function or of a report. The exception to .* expanding to a list occurs when you use it in a 4GL UPDATE statement. The notation
UPDATE table1 SET table1.* = pr_rec.*

is expanded by INFORMIX-4GL to the proper syntax
UPDATE table1 SET table1.col1 = pr_rec.element1, table1.col2 = pr_rec.element2, ...

but with all SERIAL columns omitted. (The SERIAL data type is described in Chapter 3.)

INFORMIX-4GL Statements
Eight statement types in INFORMIX-4GL do not deal with the database. These statement types are listed in the sections that follow:

2-16

INFORMIX-4GL Programming

Variable Definition

Variable Definition
You must define all program variables before you can use them.
DEFINE

associates an INFORMIX-4GL identifier with a data type. DEFINE statements must be the first statements within a program block (to define local variables) or must be within a GLOBALS statement (to define global variables). Variables defined after the GLOBALS section (if it is present) and before MAIN, the first FUNCTION, or first REPORT section of a program module have modular scope.

Assignment
You can assign values directly to program variables with one of two statements:
LET

assigns the value of an expression to a simple program variable or to a component of an array or a record. You cannot use a single LET statement to assign values to an entire record or an array. assigns default or NULL values to a program variable. Through the upscol utility, described in Appendix E, you can set default values for any columns in your database that are not DATETIME or INTERVAL. You can then use the INITIALIZE statement to assign these default values to simple or record variables.

INITIALIZE

Program Organization
INFORMIX-4GL programs can have three different types of program blocks: MAIN, FUNCTION, and REPORT. Programs can also contain global declara-

tion statements.
MAIN

contains one or more INFORMIX-4GL statements and must occur once, and only once, in every INFORMIX-4GL program. INFORMIX-4GL passes program control initially to the MAIN program block when you execute your program. The last statement in the MAIN program block must be the END MAIN statement. After INFORMIX-4GL executes the END MAIN statement, it terminates the program. contains a sequence of INFORMIX-4GL statements that perform a desired task and terminates with the END FUNCTION statement. A function can return zero or more values to the
INFORMIX-4GL Programming 2-17

FUNCTION

Program Flow

routine that called it. You can pass the values of variables to functions as parameters.
REPORT GLOBALS

contains format and output specifications for a report. identifies those program variables that have a global scope of reference.

A program must contain only one MAIN statement, and can have at most one GLOBALS statement that includes DEFINE statements. No restrictions apply to the number of FUNCTION or REPORT program blocks that can appear in a program or in a module. (A module is a system file that contains one or more program segments.) You can place all program blocks in a single module, or put each function in a separate module, or use any combination in between. A GLOBALS statement containing DEFINE statements must either be in a module by itself or be the first statement (or the second if a DATABASE statement also appears in the module) in the module containing the MAIN program block. Any module containing routines that refer to global variables must begin with a GLOBALS statement giving the pathname of the module that defines the global variables. (See the GLOBALS statement in Chapter 7 for full details.) Modules can be compiled separately and linked later, permitting you to create a library of INFORMIX-4GL functions and to call them from different modules. In addition, your program can call C functions. See the section “C Functions,” later in this chapter, for the rules governing C functions called by INFORMIX-4GL programs.

Program Flow
INFORMIX-4GL has many statements that control the flow of a program. These statements are included in INFORMIX-4GL because they simplify

the programming process.
CALL

is used to call a function that returns zero or more values. You can only use a function that returns a single value within an expression. begins an indexed loop of statements (ended by END FOR) that will be executed until the index reaches a programmersupplied value. begins a loop of statements (ended by END FOREACH) that will be executed for each row that is returned by a query of the database.

FOR

FOREACH

2-18

INFORMIX-4GL Programming

Screen Interaction

WHILE

begins a loop of statements (ended by END WHILE) that will be executed until a programmer-supplied Boolean expression becomes false. permits a premature cycling of a loop or menu. permits a premature exit from a FOR, FOREACH, WHILE, MENU, INPUT, or CASE statement, or from the entire program. executes one or more statements conditionally (ended by END IF). executes a different sequence of statements (ended by END CASE) depending upon the current value of an expression. passes program control immediately to a designated place in the program. marks the place in the program where a GOTO statement can pass control. causes the program to pause for a specified length of time. executes an operating system program and returns control to the INFORMIX-4GL program.

CONTINUE EXIT

IF CASE GOTO LABEL SLEEP RUN

Screen Interaction
The next 18 statements allow the program to interact with the screen. The first statement constructs a menu; the next five statements provide control over clearing the screen, printing messages, retrieving user input, and setting up default values for screen parameters, special keys, and help files. The next three statements are window management statements. The last nine statements handle the entry and retrieval of data from screen forms.
MENU

creates a ring menu with help lines, associated help screens, and a description of program behavior for each menu option. optionally clears specific screen fields, all screen fields, the entire screen, or a window. prints a message in reverse video on the Error line and rings the terminal bell. prints a message on the Message line. prints a message on the Prompt line and returns the user’s response.

CLEAR ERROR MESSAGE PROMPT

INFORMIX-4GL Programming

2-19

Screen Interaction

OPTIONS

OPEN WINDOW

CURRENT WINDOW CLOSE WINDOW OPEN FORM DISPLAY FORM CLOSE FORM CONSTRUCT

specifies the Message, Prompt, Form, and Comment lines relative to the screen or current window, as well as any key and help file designations. You can also specify a new Error line with the OPTIONS statement, but the error line remains relative to the screen. creates a window, with or without a border, at a given location and makes it available for use. You can explicitly specify the size of the window or let INFORMIX-4GL determine the size of the window from a given screen form. specifies the current or ‘‘topmost’’ window. All input and output is done in the current window. closes the window that you specify, restoring the ‘‘topmost’’ window (of those that remain) as the current window. opens the compiled screen form and associates an INFORMIX-4GL identifier with the form. displays the named form on the screen or in a window, displacing whatever was on the screen or window below the Form line. closes the file containing the named screen form and releases its association with the INFORMIX-4GL identifier. takes user input from a screen form and creates a character string that can be used as the WHERE clause of a SELECT statement. This is the INFORMIX-4GL mechanism for performing a query-by-example. displays expressions and variables in fields of a screen form, at a specific position on the screen, in a window, or on the next line. displays a program array to a screen array and allows scrolling through the array. takes user-entered data from a screen form and puts the data into program variables. You can specify sequences of statements to be executed during the INPUT statement before or after the cursor enters any field or after the user indicates that entry is complete. You can also trap function or control keys and specify an appropriate sequence of statements. is an extension of the INPUT statement that takes data entered by a user into a screen array and puts the information into an array of program variables. The user can scroll through the array, insert new rows into the array, and delete rows from the array by using function keys.

DISPLAY

DISPLAY ARRAY INPUT

INPUT ARRAY

2-20

INFORMIX-4GL Programming

Report Generation

SCROLL

moves data in a screen array up or down.

Report Generation
There are three statements in INFORMIX-4GL that control report writing. signals INFORMIX-4GL to initialize the report. Optionally, START you can specify the output device in the START REPORT REPORT statement. passes a row of the report variables to the report. This stateOUTPUT TO ment is usually found within a FOREACH loop where the REPORT report row is the current row of a query. handles the end of report summaries and, if necessary, secFINISH ond passes through the data so that aggregate values can be REPORT calculated.

Error and Exception Handling
INFORMIX-4GL allows you to trap run-time errors and warnings, and userentered Interrupt (usually DEL or CTRL-C) and Quit (CTRL-\) signals. For non-MODE ANSI databases, the default effects are that errors, Interrupts, and Quits cause immediate program termination, while warnings are ignored. (In a MODE ANSI database, processing continues by default after an error though not after an Interrupt or Quit.) You can change these defaults with the following commands: WHENEVER

allows you to trap errors, warnings, and NOTFOUND conditions, and to instruct INFORMIX-4GL to call a function, go to a statement, terminate the program, or ignore the problem. In the last case (WHENEVER ERROR CONTINUE), you must test for errors explicitly after every statement where an error would produce difficulties in your program. allows you to prevent INFORMIX-4GL from terminating a program when the user presses the Interrupt or Quit keys. If you choose this option, the Interrupt and/or Quit keys will terminate INPUT, INPUT ARRAY, CONSTRUCT, and PROMPT statement but will not terminate the program. You must explicitly check the global variables int_flag and quit_flag to determine whether the user has pressed the Interrupt or Quit keys after these statements.

DEFER

INFORMIX-4GL Programming

2-21

Error and Exception Handling

Error Handling
INFORMIX-4GL sets the global variable status following the execution of every SQL or form-related INFORMIX-4GL statement. status is zero when the statement executes correctly, negative when there is an error, and equal to NOTFOUND (= 100) when you attempt a FETCH outside the range of the active list of rows, or when a SELECT statement can find no rows. (See Chapter 3 for more information on the FETCH and SELECT statements.)

Three library functions, described later in this section, are available to the INFORMIX-4GL programmer to identify errors from the status variable. (Chapter 6 describes all the 4GL library functions.) The WHENEVER statement is designed to trap errors, warnings, and the NOT FOUND condition in the execution of other statements. INFORMIX-4GL indicates errors, warnings, and NOT FOUND conditions by supplying values for the global record SQLCA. See Chapter 3 for a description of the SQLCA record, and Chapter 7 for syntax of WHENEVER. The WHENEVER statement has the effect of writing an IF statement after each subsequent SQL statement in the source-code module to test for an exceptional condition, and specifies an action to take if the condition is detected. Without a WHENEVER statement, the default action after a warning or NOT FOUND is CONTINUE. For errors, however, the default depends on your type of database. Your 4GL compiler identifies the database that your program declares in the DATABASE statement that precedes the first program block (the MAIN program block, or the first function or report program block). If this database is MODE ANSI at compile-time, the default action after an error is CONTINUE. Otherwise, the default action for ERROR is STOP. The scope of a WHENEVER ERROR statement is the module in which it occurs, and from the position of the WHENEVER ERROR statement to the next WHENEVER ERROR statement in the module (or to the end of the module, if no more WHENEVER ERROR statements appear in the module). The scope of reference of WHENEVER WARNING and WHENEVER NOT FOUND statements are similar, extending to the end of the module, or else to the next WHENEVER statement that specifies the same condition in the same source code module. If you do not specify WHENEVER ERROR CONTINUE, then the startlog( ) function causes the routine name, the error code, and the corresponding error message to be written to a designated error file every time an error occurs. The syntax for startlog( ) is
CALL startlog ( filename ) 2-22 INFORMIX-4GL Programming

Data Validation

where filename is a quoted string that specifies the name of the error log file, or a CHAR variable that evaluates to the name of the error log file. If you do not want the error log file to reside in the current directory, you must specify a pathname. Another library function, errorlog("message"), appends the quoted string or CHAR variable message to the error log. This function allows you to write directly to the error log file. Chapter 6 describes these and three other 4GL library functions that deal with errors: err_print( ) err_get( ) err_quit( ) If passed the error code, prints the message on the Error line. If passed the error code, returns the message to a string variable. If passed the error code, prints the message on the Error line, and exits from the program.

Exception Handling
You can also trap Interrupt (usually DEL or CTRL-C) and Quit signals (CTRL-\) that users send to your INFORMIX-4GL program. The syntax is
DEFER { INTERRUPT | QUIT }

The DEFER keyword means that a global flag (int_flag for INTERRUPT and quit_flag for QUIT) is set to non-zero and can be checked by the program. It is the programmer’s responsibility to reset the flags to zero. The default for either an Interrupt or a Quit signal is to cause the INFORMIX-4GL program to stop immediately. If the user enters an Interrupt during an INPUT or INPUT ARRAY statement and you have executed the DEFER INTERRUPT statement, the program control leaves the INPUT statement and INFORMIX-4GL sets int_flag. You can enter the DEFER INTERRUPT statement only once in a program, and then only in the MAIN program block. This restriction applies to the DEFER QUIT statement as well.

Data Validation
You can ensure that data entered through a form conform to appropriate limits or have permitted values by setting up the INCLUDE attribute in the form specification or in the syscolval table. (See in Chapter 4 for a discussion

INFORMIX-4GL Programming

2-23

Built-in Functions

of these concepts.) If your program inserts data into the database from sources other than a form, you can check that the data meets these same restrictions by using the VALIDATE statement. VALIDATE issues an error if the value of a program variable is not consistent with limitations set for the corresponding column in syscolval.

If the current database is not MODE ANSI, then the upscol utility creates a single syscolval table that can specify acceptable values or ranges of values for any or all database columns. The VALIDATE statement enforces the limitations specified in this table. In a MODE ANSI database, however, each user of upscol creates an individual owner. syscolval table. When INFORMIX-4GL subsequently processes a VALIDATE statement of the form:
VALIDATE variable-list LIKE [ owner. ] table. column

it compares variable-list to the syscolval table belonging to the owner of the table. (The owner prefix can be omitted if the user who compiled the current 4GL program is the owner.) If owner. syscolval does not exist, the VALIDATE statement takes no action.

Built-in Functions
In addition to functions that you create with a FUNCTION statement and C functions that you can call, INFORMIX-4GL provides a number of pre-defined functions, operators, and keyword expressions. You can use the following functions, operators, and keywords in expressions.
ASCII CLIPPED COLUMN CURRENT DATE DATE( ) DAY( ) EXTEND( ) LENGTH( ) MDY( ) MONTH( ) TIME TODAY UNITS USING WEEKDAY( ) YEAR( )

These are described in the sections that follow. There are additional functions that can be used only within REPORT program blocks (described in Chapter 4) and INFORMIX-4GL library functions that cannot be used in SQL statements (described in Chapter 6). Note: INFORMIX-OnLine supports additional functionality. Refer to the INFORMIX-OnLine Programmer’s Manual for more information.
2-24 INFORMIX-4GL Programming

ASCII

ASCII
Overview
This function evaluates an integer argument as the corresponding ASCII character.

Syntax
ASCII num-expr

Explanation
ASCII

is a required keyword.

num-expr is a number expression.

Notes
INFORMIX-4GL evaluates this function as a single character. You can use it to display CTRL characters.

Examples
The following DISPLAY statement rings the terminal bell (ASCII value of 7).
DEFINE bell CHAR(1) LET bell = ASCII 7 DISPLAY bell

The next REPORT program block fragments show how to implement special printer or terminal functions. They assume that, when the printer receives the sequence of ASCII characters 9, 11, and 1, it will start printing in red, and

INFORMIX-4GL Programming

2-25

Examples

when it receives 9, 11, and 0, it will revert to black printing. The values used in the example are hypothetical; refer to your printer or terminal manual for information on your printer or terminal.
FORMAT FIRST PAGE HEADER LET red_on = ASCII 9, ASCII 11, ASCII 1 LET red_off = ASCII 9, ASCII 11, ASCII 0 ON EVERY ROW ... PRINT red_on, "Your bill is overdue.", red_off ...

Caution: INFORMIX-4GL cannot distinguish printable and non-printable ASCII characters. Be sure to account for the non-printing characters when using the COLUMN function to format your page. Since various devices differ in outputting spaces with CTRL characters, you may have to use trial and error to line up columns when you output CTRL characters.

2-26

INFORMIX-4GL Programming

CLIPPED

CLIPPED
Overview
CLIPPED displays the character expression that precedes it without any trailing blanks.

Syntax
char-expr CLIPPED

Explanation
char-expr is a required character expression.
CLIPPED

is a required keyword.

Notes
1. You normally use CLIPPED after a variable name in a LET or DISPLAY statement, or in a PRINT section of a REPORT program block. 2. CLIPPED affects the value of a character variable when it is used as an expression. CLIPPED does not affect the value when it is stored in a variable (unless you are concatenating CLIPPED values together). For example, if CHAR variable b contains a string that is shorter than the data type of a, the following LET statement pads a with trailing blanks, despite the CLIPPED keyword:
LET a = b CLIPPED

The following statement displays b without trailing blanks:
DISPLAY b CLIPPED AT 1,12

INFORMIX-4GL Programming

2-27

Example

Example
The following example is from a REPORT program block that prints mailing labels.
FORMAT ON EVERY ROW IF (city IS NOT NULL) AND (state IS NOT NULL) THEN PRINT fname CLIPPED, 1 SPACE, lname PRINT company PRINT address1 IF (address2 IS NOT NULL) THEN PRINT address2 END IF PRINT city CLIPPED, ", " , state, 2 SPACES, zipcode SKIP TO TOP OF PAGE END IF

2-28

INFORMIX-4GL Programming

COLUMN

COLUMN
Overview
The COLUMN function returns a string of spaces long enough to begin the next item in the designated column.

Syntax
COLUMN integer-expr

Explanation
COLUMN

is a required keyword. is a required positive integer expression that specifies the initial column number of the next item to be printed.

integer-expr

Notes
1. In REPORT program blocks, INFORMIX-4GL calculates the column number by adding integer-expr to the left margin that you set in the OUTPUT section. Otherwise, the column number is counted from the left edge of your screen. 2. If INFORMIX-4GL has already printed past the column specified by integer-expr, INFORMIX-4GL ignores the COLUMN expression. 3. If you use the COLUMN function in a DISPLAY statement, you must specify an integer instead of an integer expression after the COLUMN keyword.

Example
PAGE HEADER PRINT "NUMBER", COLUMN 12, "NAME", COLUMN 35, "CITY", COLUMN 57, "ZIP", COLUMN 65, "PHONE" SKIP 1 LINE ON EVERY ROW PRINT customer_num, COLUMN 12, fname CLIPPED, 1 SPACE, lname CLIPPED, COLUMN 35, city CLIPPED, ", ", state, COLUMN 57, zipcode, COLUMN 65, phone

INFORMIX-4GL Programming

2-29

CURRENT

CURRENT
Overview
The CURRENT function returns a DATETIME value with the date and time of day of the current instant.

Syntax
CURRENT [ first TO last ]

Explanation
CURRENT is a required keyword.

first
TO

is a qualifier that specifies the first field to be returned. is a required keyword if you specify first and last. is a qualifier that specifies the last field to be returned.

last

Notes
1. The value returned is the date and time (from the system clock) when the CURRENT function executes. 2. You can use the CURRENT function in any context in which you can use a DATETIME literal. 3. The first qualifier must specify a field that is more significant than or equal to the last qualifier. 4. If the function is executed more than once in a statement, identical values may be returned at each point of the call. You cannot rely on CURRENT to provide distinct values each time that it executes in the same statement. 5. INFORMIX-4GL may not execute the CURRENT function in the physical order in which it appears in a statement. You should not use the function to mark the start, the end, or any specific point in the execution of the 4GL statement. 6. If no first TO last qualifiers are specified, the default qualifiers are YEAR TO FRACTION(3).

2-30

INFORMIX-4GL Programming

Examples

7. The following qualifiers are valid:
Identifier YEAR MONTH DAY HOUR MINUTE SECOND FRACTION (n) Qualified Data A number of years. A number of months. A number of days. A number of hours. A number of minutes. A number of seconds. A decimal fraction of a second with n (up to 5) digits of precision. The default precision is 3 digits (thousandths of a second).

Examples
-- SQL statement SELECT prog_title from tv_programs where air_date > CURRENT YEAR TO DAY ATTRIBUTES -- FORM4GL field timestamp = formonly.tmstmp type DATETIME HOUR TO SECOND, default = CURRENT HOUR TO SECOND; PAGE HEADER -- Report control block print column 40, CURRENT MONTH TO MONTH, column 42, "/", column 43, CURRENT DAY TO DAY, column 45, "/", column 46, CURRENT YEAR TO YEAR

Note: The last example would not produce the correct results if its execution spanned midnight.

INFORMIX-4GL Programming

2-31

DATE

DATE
Overview
The DATE function returns a character string that has the format ‘‘Wed Sep 20 1989’’ and whose value is the current date.

Syntax
DATE

Explanation
DATE

is a required keyword.

Note
This function reads the current date from the system clock.

Example
The following example displays the current calendar date:
DEFINE p_date CHAR(15) LET p_date = DATE . . . DISPLAY "Today is ", p_date AT 5,14

2-32

INFORMIX-4GL Programming

DATE( )

DATE( )
Overview
The DATE( ) function returns a type DATE value, corresponding to the expression with which you call it.

Syntax
DATE ( expr )

Explanation
DATE

is a required keyword. is a required expression that can be converted to a type DATE value.

expr

Note
The expr is usually of type CHAR, DATETIME, or INTEGER.

Examples
The following example uses DATE to convert a string to a date:
WHERE end_date > DATE("12/13/1989")

This expression returns the 100th day after December 31, 1899:
DATE(100)

INFORMIX-4GL Programming

2-33

DAY( )

DAY( )
Overview
The DAY( ) function returns an integer that represents the day of the month, when you call it with a type DATE argument.

Syntax
DAY ( dtime-expr )

Explanation
DAY

is a required keyword. is a required expression whose value is of type DATE or DATETIME.

dtime-expr

Examples
The first example extracts the day of the month from a DATETIME literal expression:
DEFINE d_var INTEGER, date_var DATETIME YEAR TO SECOND LET date_var = DATETIME (89-12-09 18:47:32) YEAR TO SECOND LET d_var = DAY(date_var) DISPLAY "The day of the month is: ", d_var USING "##"

The next example uses the DAY ( ) function with the CURRENT function to display the day of the month:
DEFINE dayvar CHAR(2) LET dayvar = DAY(CURRENT) DISPLAY "The day of the month is: ", dayvar USING "##"

2-34

INFORMIX-4GL Programming

EXTEND( )

EXTEND( )
Overview
The EXTEND function adjusts the precision of a DATETIME value.

Syntax
EXTEND ( value [ , first TO last ] )

Explanation
EXTEND

is a required keyword. is a DATE or DATETIME value (column name, variable, or expression) of any valid precision. is an optional qualifier that specifies the first field in the result. (See Note 5.) is a required keyword if you include first and last qualifiers. is an optional qualifier that specifies the last field in the result. (See Note 6.)

value first
TO

last

Notes
1. The value can also be a DATETIME literal, or a character string that consists of valid and unambiguous DATETIME values and separators. It cannot be a string constant in DATE format. 2. If no first TO last qualifiers are specified, the default qualifiers are YEAR TO FRACTION(3). 3. The first qualifier must specify a field that is more significant than or equal to the last qualifier. 4. If the value contains fields not specified by the qualifiers, the unwanted fields are discarded. 5. If the first qualifier specifies a field to the left of (that is, more significant than) what exists in value, the new fields are filled with values returned by the CURRENT function. 6. If the last qualifier specifies a field to the right of (that is, less significant than) what exists in value, the new fields are filled in with constant values.

INFORMIX-4GL Programming

2-35

Examples

A missing MONTH or DAY is filled in with 1, and the missing fields HOUR to FRACTION are filled in with 0. 7. The following qualifiers are valid:
Identifier YEAR MONTH DAY HOUR MINUTE SECOND FRACTION (n) Qualified Data A number of years. A number of months. A number of days. A number of hours. A number of minutes. A number of seconds. A decimal fraction of a second with n (up to 5) digits of precision. The default precision is 3 digits (thousandths of a second)

8. If an INTERVAL value includes a field that is not present in a DATETIME or DATE value, you cannot combine the two values with the addition ( + ) or subtraction ( - ) operators. You must first use the EXTEND function to return an adjusted DATETIME value on which to perform the arithmetic operation.

Examples
In the first example, the EXTEND function returns the MONTH and DAY fields from a column that contains YEAR, MONTH, and DAY data. In this instance, the YEAR field is not returned.
SELECT EXTEND(air_date, MONTH TO DAY) FROM tv_programs;

In the next example, the EXTEND function returns a YEAR from CURRENT; it retains the MONTH, DAY, and HOUR values that are already in start_date, and it supplies a MINUTE value of zero.
UPDATE class_sched SET start_date = EXTEND(DATETIME(9-6 9)MONTH TO HOUR, YEAR TO MINUTE);

In the following example, the INTERVAL variable how_old includes fields that are not present in the DATETIME variable t_stamp, so the EXTEND function is required in the expression that calculates the sum of their values.
DEFINE t_stamp DATETIME YEAR TO HOUR DEFINE age DATETIME DAY TO MINUTE DEFINE how_old INTERVAL DAY TO MINUTE LET t_stamp = "1989-12-04 17" LET how_old = INTERVAL (28 9:25) DAY TO MINUTE LET age = EXTEND(t_stamp, DAY TO MINUTE) + how_old 2-36 INFORMIX-4GL Programming

Examples

Appendix J, “Working with DATETIME and INTERVAL Data,” provides more information on using date and time expressions with arithmetic operators.

INFORMIX-4GL Programming

2-37

LENGTH( )

LENGTH( )
Overview
This function returns the number of bytes in its string argument after deleting all trailing spaces.

Syntax
LENGTH ( str )

Explanation
str is a string constant, CHAR variable, or database column.

Notes
1. In a SELECT or UPDATE statement, with str the identifier of a character column, this function returns the number of bytes in the CLIPPED data value. 2. The LENGTH function must be within an SQL statement if str is a database column.

Examples
These statements center a report title on an 80-column page:
LET title = "Invoice for ", fname CLIPPED, " ", lname CLIPPED LET offset = (80 - length(title))/2 PRINT COLUMN offset, title

The next statement retrieves the value in column1 and the length in bytes of the string in column2 (excluding trailing blanks).
SELECT column1, LENGTH(column2) FROM mytable

Note: In INFORMIX-OnLine, this statement supports additional data types. Refer to the INFORMIX-OnLine Programmer’s Manual for more information.

2-38

INFORMIX-4GL Programming

MDY( )

MDY( )
Overview
The MDY( ) function returns a type DATE value when you call it with three expressions that evaluate to integers representing the month, day of the month, and year.

Syntax
MDY ( expr1, expr2, expr3 )

Explanation
MDY

is a required keyword. is an expression that evaluates to an integer representing the number of the month (1-12). is an expression that evaluates to an integer representing the number of the day of the month (1-28, 29, 30, or 31, depending on the month). is an expression that evaluates to a four-digit integer representing the year.

expr1 expr2

expr3

Notes
1. Enclose the list of integer expressions expr1, expr2, and expr3 in parentheses, separated by commas. 2. The value of expr3 cannot be the abbreviation for the year. For example, 89 is a year in the first century.

INFORMIX-4GL Programming

2-39

MONTH( )

MONTH( )
Overview
The MONTH( ) function returns an integer corresponding the month portion of its type DATE or DATETIME argument.

Syntax
MONTH ( dtime-expr )

Explanation
MONTH

is a required keyword. is a required expression of type DATE or DATETIME.

dtime-expr

Notes
1. This function extracts the month from a DATE or DATETIME value, returning an integer m in the range 1 <= m <= 12. 2. The dtime-expr cannot be an INTERVAL argument.

Examples
If the program variable then contains a DATE or DATETIME value, the Boolean expression
MONTH(then) > 9

is TRUE if then is a date in October, November, or December. The values of the year and of the day of the month in expr are ignored.

2-40

INFORMIX-4GL Programming

TIME

TIME
Overview
TIME evaluates as a character string whose value is the current time-of-day from the system clock.

Syntax
TIME

Explanation
TIME

is a required keyword.

Note
The value of TIME is a character string, representing the current time in the format hh:mi:ss, based on a 24-hour clock.

Example
DEFINE p_time char(15) LET p_time = TIME DISPLAY "The time is ", p_time

INFORMIX-4GL Programming

2-41

TODAY

TODAY
Overview
TODAY evaluates as type DATE with a value of the current date, as supplied

by the operating system.

Syntax
TODAY

Explanation
TODAY

is a required keyword.

Example
The following example is from a REPORT program block:
SKIP 1 LINE PRINT COLUMN 15, "FROM: ", begin_date USING "mm/dd/yy", COLUMN 35, "TO: ", end_date USING "mm/dd/yy" PRINT COLUMN 15, "Report run date: ", TODAY USING "mmm dd, yyyy" SKIP 2 LINES PRINT COLUMN 2, "ORDER DATE", COLUMN 15, "COMPANY", COLUMN 35, "NAME", COLUMN 57, "NUMBER", COLUMN 65, "AMOUNT"

2-42

INFORMIX-4GL Programming

UNITS

UNITS
Overview
The UNITS keyword returns an INTERVAL value with one qualifier.

Syntax
expr UNITS qualifier

Explanation
expr
UNITS

is a number expression. is a required keyword. is the name of an INTERVAL field.

qualifier

Notes
1. The expr can be a program variable, a constant, an expression, a column name, or a function that evaluates to a number. 2. An expression that includes the UNITS keyword can be added to or subtracted from a DATETIME or INTERVAL expression, provided that the UNITS operand follows the arithmetic operator (either + or - ) as the second operand. 3. The qualifier can be any one of the following field keywords:
YEAR HOUR MONTH MINUTE DAY SECOND FRACTION ( n )

Example
LET fortnite = CURRENT + 14 UNITS DAY

INFORMIX-4GL Programming

2-43

USING

USING
Overview
The USING operator specifies a format for number, MONEY, or DATE expressions. With a number or MONEY expression, you can use USING to line up decimal points or currency symbols, to right- or left-justify numbers, to put negative numbers in parentheses, and to perform other formatting tasks. USING can convert a DATE value to a variety of formats.

Syntax
expr USING "format-string"

Explanation
expr
USING

is a required expression that specifies what USING is to format. is a required keyword. is a required quoted string that specifies how USING is to format expr.

format-string

Formatting Number Expressions
The format-string consists of combinations of the following characters: * & # < , . - + ( ) $. The characters - + ( ) $ will float. When a character ‘‘floats,’’ INFORMIX-4GL displays multiple leading occurrences of the character as a single character as far to the right as possible, without interfering with the number that is being displayed. Refer to the following list for an explanation of these characters. * & # < , This character fills with asterisks ( * ) any positions in the display field that would otherwise be blank. This character fills with zeros any positions in the display field that would otherwise be blank. This character does not change any blank positions in the display field. You can use this to specify a maximum width for a field. This character causes numbers in the field to be left-justified. This character is a literal. USING displays it as a comma (but displays no comma unless there is a number to the left of it).

2-44

INFORMIX-4GL Programming

Explanation

. -

This character is a literal. USING displays it as a period. You can only have one period in a format string. This character is a literal. USING displays it as a minus sign when expr is less than zero, and otherwise as a blank. When you group several minus signs in a row, a single minus sign floats to the rightmost position without interfering with the number being printed. This character is a literal. USING displays it as a plus sign when expr is greater than or equal to zero, and as a minus sign when it is less than zero. When you group several plus signs in a row, a single plus sign floats to the rightmost position without interfering with the number being printed. This character is a literal. USING displays it as a left parenthesis before a negative number. It is the accounting parenthesis that is used in place of a minus sign to indicate a negative number. When you group several parentheses in a row, a single left parenthesis floats to the rightmost position without interfering with the number being printed. This is the accounting parenthesis that is used in place of a minus sign to indicate a negative number. One of these characters generally closes a format string that begins with a left parenthesis. This character is a literal. USING displays it as a dollar sign. When you group several dollar signs in a row, a single dollar sign floats to the rightmost position without interfering with the number being printed.

+

(

)

$

Refer to the ‘‘Examples’’ section for examples of formatting number expressions. Since format strings interact with data to produce visual effects, some readers may find that the examples are easier to follow than the descriptions of format string characters listed previously.

INFORMIX-4GL Programming

2-45

Notes

Formatting DATE Expressions
The format-string for a date can be a combination of the characters m, d, and y, as shown in Figure 2-1. The format-string can also include literals. (See the following examples.)
dd ddd mm mmm day of the month as a 2-digit number (01-31) day of the week as a 3-letter abbreviation (Sun through Sat) month as a 2-digit number (01-12) month as a 3-letter abbreviation (Jan through Dec)

Figure 2-1

yy year as a 2-digit number in the 1900s (00-99) yyyy year as a 4-digit number (0001-9999) Combinations of DATE Format Strings

Notes
1. The format-string must appear between quotation ( " ) marks. 2. Although USING is generally used as part of a DISPLAY or PRINT statement, you can also use it with LET. 3. If you attempt to display a number that is too large for the display field, INFORMIX-4GL fills the field with asterisks ( * ) to indicate an overflow.

Examples
The following example prints the balance field using a format string that allows values up to $9,999,999.99 to be formatted correctly.
DISPLAY "The current balance is ", 23485.23 USING "$#,###,##&.&&"

Following is the result of executing this DISPLAY statement with the value 23,485.23:
The current balance is $ 23,485.23

The format string in this example fixes the currency symbol. This example also uses the # and & fill characters. The # character provides blank fill for unused character positions, while the & character provides zero filling. This format ensures that even if the number is zero, any positions marked with & will appear as zero, not blank. If dollar signs are used instead of # characters, as in:
DISPLAY "The current balance is ", 23485.23 USING "$$,$$$,$$&.&&"

2-46

INFORMIX-4GL Programming

Examples

the currency symbol floats with the size of the number, so that it appears immediately to the left of the most significant digit in the display, as shown here:
The current balance is $23,485.23

The following examples show valid conversions for December 25, 1989:
Format String "mmddyy" "ddmmyy" "yymmdd" "yy/mm/dd" "yy mm dd" "yy-mm-dd" "mmm. dd, yyyy" "mmm dd yyyy" "yyyy dd mm" "mmm dd yyyy" "ddd, mmm. dd, yyyy" "(ddd) mmm. dd, yyyy" Formatted Result 122589 251289 891225 89/12/25 89 12 25 89-12-25 Dec. 25, 1989 Dec 25 1989 1989 25 12 Dec 25 1989 Mon, Dec. 25, 1989 (Mon) Dec. 25, 1989

The following example is from a REPORT program block:
ON LAST ROW SKIP 2 LINES PRINT "Number of customers in ", state, " are ", COUNT(*) USING "<<<<<" PAGE TRAILER PRINT COLUMN 35, "page ", PAGENO USING "<<<<"

INFORMIX-4GL Programming

2-47

Examples

The following example is from a more complex REPORT program block and illustrates several different formats:
SKIP 1 LINE PRINT COLUMN 15, "FROM: ", begin_date USING "mm/dd/yy", COLUMN 35, "TO: ", end_date USING "mm/dd/yy" PRINT COLUMN 15, "Report run date: ", TODAY USING "mmm dd, yyyy" skip 2 lines PRINT COLUMN 2, "ORDER DATE", COLUMN 15, "COMPANY", COLUMN 35, "NAME", COLUMN 57, "NUMBER", COLUMN 65, "AMOUNT" BEFORE GROUP OF days SKIP 2 LINES AFTER GROUP OF number PRINT COLUMN 2, order_date, COLUMN 15, company CLIPPED, COLUMN 35, fname CLIPPED, 1 SPACE, lname CLIPPED, COLUMN 55, number USING "####", COLUMN 60, GROUP SUM (total_price) USING "$$,$$$,$$$.&&" AFTER GROUP OF days SKIP 1 LINE PRINT COLUMN 21, "Total amount ordered for the day: ", GROUP SUM (total_price) USING "$$$$,$$$,$$$.&&" SKIP 1 LINE PRINT COLUMN 15, "=====================================================" ON LAST ROW SKIP 1 LINE PRINT COLUMN 15, "======================================================" SKIP 2 LINES PRINT "Total Amount of orders: ", SUM (total_price) USING "$$$$,$$$,$$$.&&" PAGE TRAILER PRINT COLUMN 28, PAGENO USING "page <<<<"

The displays on the next three pages illustrate the full power of the USING operator.

2-48

INFORMIX-4GL Programming

Examples

Format String "#####" "&&&&&" "$$$$$" "*****" "<<<<<"

Data Value 0 0 0 0 0

Formatted Result bbbbb 00000 bbbb$ ***** bbbbb (null string) 12,345 1,234 123 12 12,345 b1,234 bbb123 bbbb12 bbbbb1 bbbbb1 bbbbbb 12,345 01,234 000123 000012 000001 000000 ****** (overflow) $1,234 bb$123 bbb$12 bbbb$1 bbbbb$ 12,345 *1,234 ***123 ****12 *****1 ******

"<<<,<<<" "<<<,<<<" "<<<,<<<" "<<<,<<<" "##,###" "##,###" "##,###" "##,###" "##,###" "##,###" "##,###" "&&,&&&" "&&,&&&" "&&,&&&" "&&,&&&" "&&,&&&" "&&,&&&" "$$,$$$"

12345 1234 123 12 12345 1234 123 12 1 -1 0 12345 1234 123 12 1 0 12345

"$$,$$$" "$$,$$$" "$$,$$$" "$$,$$$" "$$,$$$" "**,***" "**,***" "**,***" "**,***" "**,***" "**,***"

1234 123 12 1 0 12345 1234 123 12 1 0

Here the character b represents a blank or space.

INFORMIX-4GL Programming

2-49

Examples

Format String "##,###.##" "##,###.##" "##,###.##" "##,###.##" "##,###.##" "##,###.##" "##,###.##" "##,###.##" "##,###.##" "&&,&&&.&&" "&&,&&&.&&" "&&,&&&.&&" "&&,&&&.&&" "$$,$$$.$$" "$$,$$$.$$" "$$,$$$.##" "$$,$$$.##" "$$,$$$.&&" "$$,$$$.&&" "-##,###.##" "-##,###.##" "-##,###.##" "--#,###.##" "---,###.##" "---,-##.##" "---,--#.##" "-##,###.##" "-##,###.##" "-##,###.##" "-##,###.##" "--#,###.##" "---,###.##" "---,-##.##" "---,---.##" "---,---.--"

Data Value 12345.67 1234.56 123.45 12.34 1.23 0.12 0.01 -0.01 -1 12345.67 1234.56 123.45 0.01 12345.67 1234.56 0.00 1234.00 0.00 1234.00 -12345.67 -123.45 -12.34 -12.34 -12.34 -12.34 -1.00 12345.67 1234.56 123.45 12.34 12.34 12.34 12.34 1.00 -.01

Formatted Result 12,345.67 b1,234.56 bbb123.45 bbbb12.34 bbbbb1.23 bbbbb0.12 bbbbbb.01 bbbbbb.01 bbbbb1.00 12,345.67 01,234.56 000123.45 000000.01 ********* (overflow) $1,234.56 $.00 $1,234.00 $.00 $1,234.00 -12,345.67 -bbb123.45 -bbbb12.34 -bbb12.34 -bb12.34 -12.34 -1.00 12,345.67 1,234.56 123.45 12.34 12.34 12.34 12.34 1.00 -.01

Here the character b represents a blank or space.

2-50

INFORMIX-4GL Programming

Examples

Format String "----,---.&&" "-$$$,$$$.&&" "-$$$,$$$.&&" "-$$$,$$$.&&" "--$$,$$$.&&" "--$$,$$$.&&" "--$$,$$$.&&" "--$$,$$$.&&" "--$$,$$$.&&" "----,--$.&&" "----,--$.&&" "----,--$.&&" "----,--$.&&" "----,--$.&&" "----,--$.&&" "$***,***.&&" "$***,***.&&" "$***,***.&&" "$***,***.&&" "$***,***.&&" "$***,***.&&" "($$$,$$$.&&)" "($$$,$$$.&&)" "($$$,$$$.&&)" "(($$,$$$.&&)" "(($$,$$$.&&)" "(($$,$$$.&&)" "(($$,$$$.&&)" "(($$,$$$.&&)" "((((,(($.&&)" "((((,(($.&&)" "((((,(($.&&)" "((((,(($.&&)" "((((,(($.&&)" "((((,(($.&&)"

Data Value -.01 -12345.67 -1234.56 -123.45 -12345.67 -1234.56 -123.45 -12.34 -1.23 -12345.67 -1234.56 -123.45 -12.34 -1.23 -.12 12345.67 1234.56 123.45 12.34 1.23 .12 -12345.67 -1234.56 -123.45 -12345.67 -1234.56 -123.45 -12.34 -1.23 -12345.67 -1234.56 -123.45 -12.34 -1.23 -.12

Formatted Result -.01 -$12,345.67 -b$1,234.56 -bbb$123.45 -$12,345.67 -$1,234.56 -bb$123.45 -bbb$12.34 -bbbb$1.23 -$12,345.67 -$1,234.56 -$123.45 -$12.34 -$1.23 -$.12 $*12,345.67 $**1,234.56 $****123.45 $*****12.34 $******1.23 $*******.12 ($12,345.67) (b$1,234.56) (bbb$123.45) ($12,345.67) ($1,234.56) (bb$123.45) (bbb$12.34) (bbbb$1.23) ($12,345.67) ($1,234.56) ($123.45) ($12.34) ($1.23) ($.12)

Here the character b represents a blank or space.

INFORMIX-4GL Programming

2-51

Examples

Format String "($$$,$$$.&&)" "($$$,$$$.&&)" "($$$,$$$.&&)" "(($$,$$$.&&)" "(($$,$$$.&&)" "(($$,$$$.&&)" "(($$,$$$.&&)" "(($$,$$$.&&)" "((((,(($.&&)" "((((,(($.&&)" "((((,(($.&&)" "((((,(($.&&)" "((((,(($.&&)" "((((,(($.&&)"

Data Value 12345.67 1234.56 123.45 12345.67 1234.56 123.45 12.34 1.23 12345.67 1234.56 123.45 12.34 1.23 .12

Formatted Result $12,345.67 $1,234.56 $123.45 $12,345.67 $1,234.56 $123.45 $12.34 $1.23 $12,345.67 $1,234.56 $123.45 $12.34 $1.23 $.12

Here the character b represents a blank or space.

2-52

INFORMIX-4GL Programming

WEEKDAY( )

WEEKDAY( )
Overview
The WEEKDAY( ) function returns an integer that represents the day of the week, when you call it with a type DATE or DATETIME expression.

Syntax
WEEKDAY ( dtime-expr )

Explanation
WEEKDAY

is a required keyword. is a required expression of type DATE.

dtime-expr

Notes
1. WEEKDAY returns an integer in the range 0-6. Zero represents Sunday, 1 represents Monday, and so on. 2. The dtime-expr cannot be a type INTERVAL argument.

Example
LET tag = WEEKDAY(p_orders.order_date)

INFORMIX-4GL Programming

2-53

YEAR( )

YEAR( )
Overview
The YEAR( ) function returns an integer that represents the year (four digits for 1989) when you call it with a type DATE or DATETIME expression.

Syntax
YEAR ( dtime-expr )

Explanation
YEAR

is a required keyword. is a required expression of type DATE or DATETIME.

dtime-expr

Note
The dtime-expr cannot be an INTERVAL argument.

Example
LET y_var = YEAR(TODAY)

2-54

INFORMIX-4GL Programming

C Functions

C Functions
INFORMIX-4GL programs can call C language functions. To provide a transparent function-calling mechanism, INFORMIX-4GL requires that C functions follow a calling convention that allows data to be passed between the INFORMIX-4GL program and the C function.

This calling convention that is described in this section applies to both the C Compiler Version and Rapid Development System implementations of INFORMIX-4GL. If you have the Rapid Development System, see also the section“RDS Programs That Call C Functions” in Chapter 1, which describes the additional procedures that are required to compile and run such programs. The convention uses a stack, which is a data structure that can be accessed in a predefined way by both INFORMIX-4GL programs and C functions. You can perform two classes of operations on a stack: push pop to add a variable to the stack to retrieve a variable from the stack

The stack acts as a LIFO (last-in, first-out) queue. The variable added to the stack by the last push is the next variable to be removed from the stack if you do a pop. The next page lists functions that are provided with INFORMIX-4GL to perform pushes and pops on specific data types. Consider the following INFORMIX-4GL statement:
CALL myfunc (a,b,c)

Part of the calling convention is that function arguments are pushed from left to right onto the stack. INFORMIX-4GL automatically pushes the variables a, b, and c onto the stack, in that order. Another part of the calling convention requires INFORMIX-4GL to automatically pass the number of calling parameters as the only real argument to the C function. This tells the C function how many values to pop. The C functions designed to work with INFORMIX-4GL must obey the calling convention by complementing the actions of INFORMIX-4GL. All compatible C functions have only one argument, which is the number of parameters that INFORMIX-4GL placed on the stack. You use this argument to pop the calling parameters. INFORMIX-4GL supplies the following library of functions to assist this process.

INFORMIX-4GL Programming

2-55

C Functions

Popping Functions popint(&i) popshort(&s) poplong(&l) popflo(&f) popdub(&d) popquote(str, len) popdec(&dm) popdtime(&dt, qual) popinv(&inv, qual)

Pushing Functions retint(i) retshort(s) retlong(l) retflo(&f) retdub(&d) retquote(str) retdec(&dm) retdtime(&dt) retinv(&inv)

Argument Types int i; short s; long l; float f; double d; char *str; int len; dec_t dm; dtime_t dt; int qual; intrvl_t inv; int qual;

Note: INFORMIX-OnLine supports additional functionality. Refer to the INFORMIX-OnLine Programmer’s Manual for more information. Here len is the buffer size of the string to which str points, and qual is the qualifier of the DATETIME or INTERVAL value that will be received by destination variable dt or inv. Your first step in a C function is to pop all the arguments in the reverse order from the order in the call. If the call is to myfunc, you must first pop c, and then b, and finally a. You must use the library function that is appropriate for the data type of the receiving variable. After the function is called, INFORMIX-4GL restores the stack pointer to its original state. To return values from the C function to the INFORMIX-4GL program, you must push the values onto the stack. They must be pushed in the same order as they appear in the RETURNING clause of your INFORMIX-4GL statement. For example, if the statement is
CALL ... RETURNING x, y

you must push x before pushing y within your C function. You must use the library function that matches the data type to execute the push. The last statement that your C function executes must be a return, where the only parameter is the number of variables that are being returned. Make sure that the variables returned by your C function match, both in number and in data type, the argument list in the RETURNING clause of the INFORMIX-4GL statement. If you do not return the correct data types, your program can execute unpredictably. Failure to return the expected number of arguments causes an error.

2-56

INFORMIX-4GL Programming

Examples

When using the C library functions, you must be aware of the following factors:

• If you use the retquote(str) function, you must null-terminate the string. • The string str in popquote will be null-terminated, so you should allow
for that in the value of m.

• The dec_t structure is defined in Appendix F, along with a number of
useful functions that you can use to convert DECIMAL variables to other number data types and back again within your C functions. (They are not necessary within an INFORMIX-4GL program, since their functionality is already supported by INFORMIX-4GL.)

Examples
The first example (which only schematically represents actual C code) shows the basic structure for C functions that you can call from an INFORMIX-4GL program.
myfunc(n) int n; { /* n specifies how many 4gl parameters * were passed by the calling 4gl statement */ test that the value of n is correct pop n 4gl parameters in reverse order, right to left ... code push x returning 4gl parameters, left to right return(x) /* must return the number x, specifying how many 4gl * variables are "RETURNING" */

}

INFORMIX-4GL Programming

2-57

Examples

The following INFORMIX-4GL program calls the C language function sndmsg, which converts a string into EBCDIC and sends it to a remote computer. Two arguments are explicitly passed to the function: the source string and its length. INFORMIX-4GL automatically passes the number of arguments to the function.
MAIN DEFINE chartype CHAR(80), msg_status INTEGER, return_code INTEGER LET chartype = "234" # # # # # sndmsg requires two arguments and returns two arguments, as defined by the C language function. You must ensure that the order and data types of all arguments are compatible between the 4gl calling program and the called function. CALL sndmsg(chartype, 4) RETURNING msg_status, return_code IF return_code <> 0 THEN DISPLAY "Error code: ", return_code END IF DISPLAY msg_status END MAIN

The function sndmsg checks that the correct number of arguments are passed. INFORMIX-4GL cannot guarantee recovery of the stack if a function is called with the wrong number of arguments, since that is a failure to follow the calling convention between INFORMIX-4GL and C functions. The sndmsg function terminates the program if the wrong number of arguments is passed.

2-58

INFORMIX-4GL Programming

Examples

If the correct number of arguments is passed, sndmsg pops the arguments from the stack, using the library functions appropriate for the data type. An annotated listing of the sndmsg program follows:
#include "stdio.h" #include "decimal.h" sndmsg(nargs) /* 4gl syntax is CALL sndmsg (input,len) RETURNING int nargs; { char int int input[80]; msg_number; len, retcode; /* 4gl and C function must agree on data */ /* types and the order that arguments are */ /* placed on the stack */ msg_number, retcode */

/* 4gl passes the number of arguments as an integer */

/* Check that the correct number of arguments are passed */ if (nargs != 2) { fprintf (stderr, "sndmsg: wrong number of arguments"); exit(1); /* No recovery from this error */ } /* Pop rightmost argument */ popint(&len); /* Pop next argument popquote(input,len); /* Finished with function calling convention */ /* Start function processing */ msg_number =-1; retcode = cvtebcd (&input, len); /* user-written function */ if (retcode != 0) msg_number = sndrmt (input,len); /* user-written function */ /* Finished processing */ /* Return (push) leftmost argument */ retint(msg_number); /* Return next argument */ retint(retcode); /* Finished returning arguments */ /* Return from function giving number of arguments */ return(2); } */

To return values to the program, the C function uses appropriate push functions for the data type and pushes return arguments onto the stack from left to right. The last statement executed by the function returns the number of
INFORMIX-4GL Programming 2-59

Examples

arguments, which is two for sndmsg. A discrepancy between the number of return arguments in the function and the number of arguments expected by the program results in an error.

2-60

INFORMIX-4GL Programming

Chapter

Using SQL
Chapter Overview 5 Relational Databases SQL Identifiers 6 Owner Naming Database Data Types 7 8 10 5

3
14

SQL Statement Summary Data Definition 11 12

Data Manipulation

Cursor Management 13 SELECT Cursors 13 Associating a Cursor with a SELECT Statement Retrieving and Processing Rows 15 The SCROLL Cursor 20 The Cursor WITH HOLD 23 INSERT Cursors 25 Dynamic Management 28 Preparing Statements 29 Statements That Require No Input 30 Statements That Require Input for Values 30 Statements That Require Input for SQL Identifiers 32 Executing PREPAREd Statements 33 The EXECUTE Statement 33 Running PREPAREd SELECT Statements 35 Running PREPAREd INSERT Statements 37 Preparing Multiple SQL Statements 38 The FREE Statement 39

Data Access

40 41

User Status and Privileges

Data Integrity 42 Transactions 42 Databases Without Transactions 43 Databases with Implicit Transactions 43 Databases with Explicit Transactions 44 Using Transactions 44 Transaction Log File Maintenance 45 Audit Trails 45 Creating an Audit Trail 46 Recovering a Table 46 Comparison of Transactions and Audit Trails 47 Locking 47 Row-Level Locking 48 Row-Level Locking in Transactions Table-Level Locking 49 Wait for Locked Row 50 Indexing Strategy 50 Query Optimizer 52 Auto-Indexing 52 Clustered Indexes 52 NULL Values 53 Default Values 54 The NULL in Expressions 54 The NULL in Boolean Expressions 55 The NULL in WHERE Clauses 55 The NULL in ORDER BY Clauses 56 The NULL in GROUP BY Clauses 56 The NULL Keyword in INSERT and UPDATE Statements Views 57 Creating and Deleting Views 58 Querying Through Views 58 Modifying Through Views 59 Privileges with Views 60 Data Constraints Using Views 60

49

57

3-2

Using SQL

Outer Joins

61 62

Table Access by ROWID SQLCA Record 63

TODAY, CURRENT, and USER Functions

65

Using SQL

3-3

3-4

Using SQL

Chapter Overview
Informix Software, Inc. has developed an implementation of SQL that extends the Structured Query Language (SQL) developed by IBM. The Informix Software additions to the language permit you to change databases, to change the names of tables and columns, and to increase the functionality of ANSI standard SQL statements. In the family of Informix Software database products, SQL plays several roles. In INFORMIX-SQL, SQL is both the interactive query language and the language you use to choose the data for ACE, the INFORMIX-SQL report-writing program. You can read about these uses of SQL in the INFORMIX-SQL User Manual. In INFORMIX-ESQL/C, SQL is the database query language that you embed in C programs to create an application. In INFORMIX-4GL, SQL statements are combined with those described in Chapter 2 to form an almost seamless fourth-generation language. This chapter describes SQL and gives an overview of its statements. The full syntax and rules governing SQL statements are located in Chapter 7 of the INFORMIX-4GL Reference Manual.

Relational Databases
SQL statements create and manipulate relational databases. A relational

database consists of one or more tables that, in turn, are constructed of rows and columns. Each row contains a specific set of column values. Databases are created as subdirectories of the current directory. The name of the directory is the database name with the extension .dbs. The database subdirectory contains 11 system catalog tables that define the database dictionary. It also contains the tables that constitute the database. Each of these tables is represented by data files and index files, with the extensions .dat and .idx, respectively. The system catalogs are described in Appendix B.

Using SQL

3-5

SQL Identifiers

You have the option of specifying a MODE ANSI database. A database created or started as MODE ANSI supports implicit transactions and enforces ownernaming. (See the section “Data Integrity” for more information about transactions in a MODE ANSI database. See the section “Owner Naming” for more information about owner-naming.)
INFORMIX-4GL provides several ways to check for Informix extensions to the ANSI standard for SQL syntax in your programs:

• If you use the -ansi flag in the command line that invokes the 4GL
compiler, you receive a compile-time warning, in the form of messages to a diagnostic file, if the program includes Informix extensions to the ANSI standard for SQL syntax.

INFORMIX-4GL issues a run-time warning by setting the character

SQLCA.SQLAWARN [6] to W, if a program executes a statement that includes an Informix extension to ANSI syntax, and the DBANSIWARN environment variable is defined (as described in Appendix C.) See “INFORMIX-4GL Extensions to ANSI Syntax” in Chapter 7 for a list of the Informix extensions to the ANSI standard.

SQL Identifiers
An SQL identifier is the name of an object. It can consist of letters, numbers, and underscores ( _ ). The first character must be a letter. Unless otherwise indicated, an identifier can have from one to 18 characters. Database Table A database name is an identifier that can have from one to 10 characters. A table name is an identifier that must be unique within the database. (In a MODE ANSI database, the owner and table combined must be unique within the database.) A column name is an identifier that must be unique within a table; there can be duplicate column names within a database. When column names within different tables are not unique, use the notation table.column to specify the intended column. If you intend to define an INFORMIX-4GL record like a table, the first 8 characters of each column name in the table must be unique within the table.

Column

If there is an ambiguity because an INFORMIX-4GL identifier and an SQL identifier are the same, INFORMIX-4GL assumes that the identifier refers to a 4GL program variable and not to the SQL object. If you want to override
3-6 Using SQL

Owner Naming

this default assignment, prefix the SQL identifier with an ‘‘at’’ sign ( @ ). For example, if lname is defined as a program variable, but you wish to refer to the database column of the same name, use @lname for the column name:
SELECT @lname INTO lname FROM customer

Owner Naming
In a database created as MODE ANSI, the name of each object (table, view, index, synonym, and constraint) is qualified by the name of the owner of the object. The combined owner.object must be unique within the database. The following rules apply to the naming of an object:

• owner is the login name of the owner of the object. The name must begin
with a letter. It can contain underscores, letters, and numbers, and can be up to 8 characters long. Alternatively, the name can be a quoted string. This allows you to preserve uppercase characters in user names or to include a user name in which the first character is a digit. The quoted string can be up to 8 characters long.

• object is a valid identifier for a table, view, index, synonym, or constraint.
The identifier must begin with a letter. It can contain underscores, letters, and numbers, and can be up to 18 characters long. The format for naming an object in an SQL statement is as follows:
[owner. ] object

An object receives its owner when it is CREATEd. You cannot change the ownership of an object. By default, ownership is assigned to the individual who creates the object. However, a user with database administrator (DBA) privilege can create an object and assign ownership of the object to another user. In a database created as MODE ANSI, you must specify owner when referring to an object created by another user. As with non-MODE ANSI databases, you may specify owner when referring to your own objects. In the following example, the UPDATE statement modifies rows in the stock table owned by the user james:
UPDATE james.stock SET price = price * 1.05

Using SQL

3-7

Database Data Types

Quoted strings allow you to retain case sensitivity when case is important. In the following examples, the SELECT statements retrieve rows from different tables:
SELECT * FROM "Smith".stock SELECT * FROM Smith.stock

Note that "Smith" is in quotes in the first SELECT statement but not in the second. Because of the quotes, the case distinction is preserved in the first SELECT; therefore, the first SELECT retrieves rows from the Smith.stock table while the second SELECT retrieves rows from the smith.stock table. The engine assumes an object is owned by the user if you do not include the owner prefix. As the owner of the system catalog tables is informix, you must include the owner name informix when querying each system catalog. You do not have to supply owner names when working with a non-MODE ANSI database. However, if you specify the owner along with the object name, the engine will check for the accuracy of the owner name. Note: In a MODE ANSI database, you receive an error if you do not use the owner.object naming convention to refer to an object owned by another user. If you start a database as MODE ANSI, you must modify existing queries that reference a table, view, or synonym owned by another user to include the owner prefix.

Database Data Types
You must assign a data type to every column in the database. (See the CREATE TABLE statement in Chapter 7). Except for the SERIAL data type, the SQL data types are identical to the corresponding 4GL data types that were defined in Chapter 2. The valid SQL data types are as follows:
CHAR [(n)] CHARACTER SMALLINT INTEGER INT DECIMAL [(m[,n])]

is a character string of length n (where 1 ≤ n ≤ 32,511). If you do not specify n, CHAR(1) is assumed. is a synonym for CHAR. is a whole number from -32,767 to +32,767. is a whole number from -2,147,483,647 to +2,147,483,647. is a synonym for INTEGER. is a decimal floating point number with m (≤ 32) significant digits (the precision) and n (≤ m) digits right of the decimal point (the scale). When you give values for both m and n, the decimal variable has fixed-point arithmetic. All numbers with an absolute

3-8

Using SQL

Database Data Types

value less than 0.5 × 10-n have the value zero. The largest absolute value of a DECIMAL variable that can be stored without an error is 10m-n - 10-n. The second parameter is optional and, if missing, the variable is treated as a floating decimal. DECIMAL(m) variables have a precision of and a range in absolute value from 10-128 to 10126 If no parameters are designated, DECIMAL is treated as DECIMAL(16), a floating decimal.
DEC NUMERIC SMALLFLOAT

is a synonym for DECIMAL. is another synonym for DECIMAL. is a floating-point number corresponding to the float C data type. The range of values for a SMALLFLOAT data type is the same as the range of values for the C float data type on your machine. is a synonym for SMALLFLOAT. is a floating-point number corresponding to the double C data type. The range of values for a FLOAT data type is the same as the range of values for the C double data type on your machine. You can use n (where n is a whole number between 1 and 14) to specify the precision of a FLOAT data type. INFORMIX-4GL does not use the precision, however. (The optional precision parameter is provided for compatibility with ANSI standards.)

REAL FLOAT [(n)]

DOUBLE PRECISION MONEY [(m [,n] )]

is a synonym for FLOAT. can take two parameters like the DECIMAL data type. The limitation on values for columns of type MONEY (m, n) is the same for columns of type DECIMAL (m, n). The type MONEY (m) is defined as DECIMAL (m, 2) and, if no parameter is given, MONEY defaults to DECIMAL (16, 2). Regardless of the number of parameters, the data type MONEY is always treated as a fixed decimal number. is a sequential integer assigned automatically by
INFORMIX-4GL. You can assign an initial value n.

SERIAL [ (n) ]

The default starting integer is 1.
DATE

is a date entered as a character string in one of the formats described in Chapter 2, and stored as an integer number of days since December 31, 1899.
Using SQL 3-9

SQL Statement Summary

DATETIME first TO last

stores a moment in time with the precision first to last. A DATETIME column is entered as a character string in one of the formats described in Chapter 2, recording the value of a calendar date and time of day. It is stored internally as a DECIMAL number, whose digits represent a contiguous sequence of the following fields: YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, and FRACTION(n) of a second. DATETIME is described in greater detail in Appendix J. stores a span of time with the precision first to last. An INTERVAL column is entered as a character string in one of the formats described in Chapter 2, recording the value of the difference between two DATETIME values. It is stored internally as a DECIMAL number, whose digits represent values of the fields from first to last. An INTERVAL column consists of a contiguous sequence of one of the following two lists of fields: either YEAR and MONTH; or else DAY, HOUR, MINUTE, SECOND, and FRACTION(n) of a second. INTERVAL is described in greater detail in Appendix J.

INTERVAL first TO last

Note: INFORMIX-OnLine supports additional data types. Refer to the INFORMIX-OnLine Programmer’s Manual for more information.

SQL Statement Summary
Six different types of SQL statements are used with INFORMIX-4GL:

• • • • • •

Data definition Data manipulation Cursor management Dynamic management Data access Data integrity

3-10

Using SQL

Data Definition

Data Definition
Data definition statements include those that create and drop a database and its tables, views, and indexes, modify tables, indexes, and columns, or rename tables and columns. Of this list, only the DATABASE statement is required before manipulating the data of an existing database or defining program variables LIKE columns in the database. creates a database directory, sets up the system catalogs, and CREATE makes the new database the current database. There can be no DATABASE more than one current database at any time.
DATABASE CLOSE DATABASE

selects a database and makes it the current database. There can be no more than one current database at any time. closes the current database files and leaves no database current. The only SQL statements permitted when there is no current database are: • CREATE DATABASE • DATABASE • DROP DATABASE • START DATABASE deletes all tables, indexes, and system catalogs. If no other files are present in the database subdirectory, the subdirectory is also deleted. creates a table and defines the columns and their data types. adds or drops columns and constraints from a table, and modifies data types of existing columns. changes the name of a table, replacing the old name with the new name in the system catalogs. deletes all data and indexes for a table and erases its entry in the system catalogs. defines a table selected from rows and columns of existing tables and views. As the underlying tables change, so does the view built on them. See the section “Views” later in this chapter for more information about views. deletes the definition of the view from the system catalogs, along with any views defined in terms of the one that is dropped. The underlying tables are unaffected. defines an alternative name for a table or a view. For INFORMIX-4GL programs, the creator of the synonym is the user who runs the program that creates the synonym.
Using SQL 3-11

DROP DATABASE CREATE TABLE ALTER TABLE RENAME TABLE DROP TABLE CREATE VIEW

DROP VIEW CREATE SYNONYM

Data Manipulation

DROP SYNONYM RENAME COLUMN CREATE INDEX ALTER INDEX DROP INDEX UPDATE STATISTICS

deletes a synonym from the system catalogs. changes the name of a column, replacing the old name with the new name in the system catalogs. creates an index on one or more columns of a table. See the section “Indexing Strategy” later in this chapter for more information on indexes. clusters a table in the order of an existing index or releases an index from the cluster attribute. deletes an existing index, removing it from the system catalogs. updates the system catalogs by determining and inserting the number of rows in the indicated tables. INFORMIX-4GL uses this information in optimizing queries but does not automatically update the system catalogs after each INSERT or DELETE.

Data Manipulation
The data manipulation statements are the most frequently used SQL statements:
DELETE INSERT LOAD SELECT UNLOAD UPDATE

deletes one or more rows from a table. adds one or more rows to a table. inserts rows from an operating system file. retrieves data from one or more tables. copies rows to an operating system file. modifies the data in one or more rows of a table.

SELECT is the most important and the most complex SQL statement.

Although its syntax is defined in detail in Chapter 7, the following examples illustrate its use:
SELECT lname, company INTO p_lname, p_company FROM customer WHERE customer_num = 101

3-12

Using SQL

Cursor Management

This statement queries the customer table and returns the single row for which the customer number is 101. From that row, it selects and places the values in the columns corresponding to the last name and company name of the contact in the program variables p_lname and p_company.
SELECT @quantity, @total_price INTO quantity, total_price FROM items WHERE order_num = 1001

This example shows another SELECT statement that returns a single row. In this example, the program variables quantity and total_price have the same identifier as the corresponding columns in the items table. There is no conflict here, since the prefix @ distinguishes the column name from the program variable. A SELECT statement that returns a single row is called a singleton SELECT statement and can stand alone. The section ‘‘Cursor Management’’ that follows describes how to handle SELECT statements that return more than one row.

Cursor Management
INFORMIX-4GL provides two functional types of cursors:

• A SELECT cursor, which you must use to handle a SELECT statement that
returns more than one row.

• An INSERT cursor, which you can use to insert rows into the database as
a block. The section ‘‘SELECT Cursors’’ describes how to associate a cursor with a SELECT statement and gives examples of the uses of the SELECT cursor. The section ‘‘INSERT Cursors’’ explains how to associate a cursor with an INSERT statement and describes the advantages of using an INSERT cursor.

SELECT Cursors
When a SELECT statement returns exactly one row, the values returned to the program variables are unambiguous. However, when more than one row can be returned, it is necessary to have a device to distinguish one row from another. This device is called a cursor.

Using SQL

3-13

SELECT Cursors

The set of rows returned by a SELECT statement is called the active set for the statement. Within an INFORMIX-4GL program, you can work with only one row of the active set at a time. This row is called the current row, and it is referenced by a cursor. A cursor can be in one of two states: open or closed. When a SELECT cursor is in an open state, it is associated with an active set and can point to the current row, between two rows, before the first row, or after the last row. When it is in a closed state, the cursor is no longer associated with an active set, although it remains associated with the SELECT statement. The following sections describe how to use the cursor management statements to process rows returned by a SELECT statement. (For complete information on the syntax of each statement, see Chapter 7.)

Associating a Cursor with a SELECT Statement
You use the DECLARE statement to name a cursor and to associate it with a SELECT statement. In the DECLARE statement, you specify the type of cursor that you want to use:

• A regular (or ‘‘non-scrolling’’) cursor allows rows to be retrieved from the
active set in consecutive order. You also DECLARE a regular cursor when you plan to delete or update the current row in the active set.

• The SCROLL cursor allows rows to be retrieved from the active set in random order.

• A regular or SCROLL cursor can be specified as WITH HOLD. Unlike regular or SCROLL cursors that are not WITH HOLD, a cursor DECLAREd as WITH HOLD is not closed at the end of a transaction. For example, the following DECLARE statement associates a SCROLL cursor named q_curs with a SELECT statement that retrieves all the rows from the customer table:
DECLARE q_curs SCROLL CURSOR FOR SELECT * FROM customer

The following DECLARE statement associates a non-scrolling cursor with a SELECT statement that retrieves customer rows based on a value that the user supplies for column last name:
PROMPT "Enter a last name: " FOR last_name

DECLARE cust_curs CURSOR FOR SELECT * FROM customer WHERE lname MATCHES last_name

3-14

Using SQL

SELECT Cursors

A cursor name has meaning only from the point at which it is DECLAREd to the end of the source-code file. The DECLARE statement for a cursor must physically appear before any statement that refers to it. For example, the following program will not compile because the DECLARE statement for q_curs appears after the FOREACH statement that refers to it. (See the following section, ‘‘Retrieving and Processing Rows’’ for more information about FOREACH.
DATABASE stores MAIN DEFINE p_customer RECORD LIKE customer.* OPEN FORM custform FROM "customer" DISPLAY FORM custform CALL get_curs() -- INCORRECT FOREACH q_curs INTO p_customer.* DISPLAY BY NAME p_customer.* . . . END FOREACH END MAIN FUNCTION get_curs() DECLARE q_curs CURSOR FOR SELECT * FROM customer END FUNCTION

Retrieving and Processing Rows
Once you have DECLAREd a cursor for a SELECT statement, you can use either the FOREACH statement or the OPEN, FETCH, and CLOSE statements to retrieve and process the rows specified by the SELECT statement.

Using SQL

3-15

SELECT Cursors

The FOREACH Statement
Using the FOREACH statement, you can select rows and execute a series of statements for each row returned by a query. The following example uses a FOREACH statement to retrieve and display rows in the customer table:
PROMPT "Enter a last name: " FOR last_name DECLARE q_curs CURSOR FOR SELECT * FROM customer WHERE lname MATCHES last_name FOREACH q_curs INTO p_customer.* DISPLAY BY NAME p_customer.* . . . END FOREACH

When INFORMIX-4GL encounters the FOREACH statement in this example, it runs the query and repeatedly performs the following operations until the active set is exhausted:

• Retrieves the next row from the active set and stores it in the p_customer
record

• Displays the values in the p_customer record on a screen form • Executes all additional statements within the FOREACH loop
You can use the FOREACH statement when you want to retrieve the rows specified by a SELECT statement and then process them in consecutive order. You can use the FOREACH statement with a regular cursor, a SCROLL cursor, or a cursor WITH HOLD.

The OPEN, FETCH, and CLOSE Statements
You can use the OPEN, FETCH, and CLOSE statements when you need to explicitly control the behavior of a cursor:
OPEN

puts the cursor in an open state with regard to the SELECT statement. The OPEN statement causes the SELECT statement to run with the current program variables and leaves the cursor pointing just before the first row of the resulting active set. While the cursor is in an open state, subsequent changes to any program variables that appear in the SELECT statement associated with the cursor do not affect the active set. advances the cursor to the specified row (either FIRST, LAST, NEXT, PRIOR or PREVIOUS, ABSOLUTE n, or RELATIVE m) and retrieves

FETCH

3-16

Using SQL

SELECT Cursors

the values from that row. If a FETCH statement moves the cursor before the first row or after the last row, the error variable status has the value NOTFOUND (= 100), as does the SQLCODE component of the SQLCA record. (See the section “SQLCA Record” later in this chapter for more information.) NOTFOUND indicates that either end of the active list has been reached.
CLOSE

puts the cursor in a closed state and releases the active set. No statements referring to the cursor, other than OPEN, are operative.

For example, consider the following DECLARE statement:
DECLARE x CURSOR FOR SELECT order_num, order_date FROM orders WHERE paid_date IS NULL AND ship_date > p_date FOR UPDATE OF paid_date

This statement names a cursor x and associates it with the SELECT statement that follows the FOR keyword. The SELECT statement returns the order number and order date for those unpaid orders whose shipping date was later than the date in the program variable p_date. The statement also enables a future UPDATE statement to modify the paid_date column. The DECLARE statement does not perform the query; it simply assigns the cursor to the SELECT statement.
OPEN x

When you execute the OPEN statement later in your program, the Boolean expression in the WHERE clause of the SELECT statement uses the value of the variable p_date at the time of the OPEN statement.
FETCH x INTO order_num, order_date

The FETCH statement retrieves the rows of the active set, moves x to point to the first row, and assigns to the program variables order_num and order_date the values of the columns order_num and order_date in the first row:
UPDATE orders SET paid_date = TODAY WHERE CURRENT OF x

The UPDATE statement substitutes the current date (returned by the TODAY function) for the existing NULL value of paid_date in the current row (that is, the first row) of the active set. The cursor remains pointing to the first row:
CLOSE x

Using SQL

3-17

SELECT Cursors

The cursor x is now put into a closed state, and the active set is effectively dissolved. An immediate FETCH statement would be an error because a cursor in a closed state cannot point to anything. If, at a later time, you should execute the statement
OPEN x

the cursor x would be put back into an open state with a new active set that depends on the value of the program variable p_date when the OPEN statement was executed.

Deleting or Updating the Current Row
You can use special forms of the DECLARE, DELETE, and UPDATE statements to delete or update the current row in an active set. You cannot use a SCROLL cursor to process the rows returned by a SELECT statement, and the SELECT statement cannot include an ORDER BY clause. To delete a row in an active set, you must include a FOR UPDATE clause in the DECLARE statement for a non-SCROLLing cursor, and also specify a WHERE CURRENT OF clause in a subsequent DELETE statement. The following program fragment is an example.
-- Prompt user, then read name from terminal. PROMPT "Enter a last name: " FOR last_name DECLARE q_curs CURSOR FOR SELECT * FROM customer WHERE lname MATCHES last_name FOR UPDATE FOREACH q_curs INTO IF status <> 0 EXIT FOREACH cust_rec

-- Display customer values here. . . . PROMPT "Do you want to delete this customer (y/n) ? " FOR answer IF answer = "y" DELETE FROM customer WHERE CURRENT OF q_curs END IF END FOREACH . . .

3-18

Using SQL

SELECT Cursors

The cursor remains between rows after a DELETE WHERE CURRENT OF statement is executed. This means that you cannot refer to the cursor in another DELETE or UPDATE statement until you use a FETCH statement to advance the cursor to the next row. You can update the current row if you include a FOR UPDATE clause in the DECLARE statement for a non-SCROLLing cursor, and a WHERE CURRENT OF clause in a subsequent UPDATE statement. The following example allows the user to update the address information in the current row:
DECLARE q_curs CURSOR FOR SELECT * FROM customer FOR UPDATE

FOREACH q_curs INTO cust_rec IF status <> 0 EXIT FOREACH -- Display customer values here. . . . PROMPT "Do you want to change the customer’s address (y/n) ?" FOR answer IF answer = "y"

-- Input the new values here. . . . UPDATE customer SET address1 = cust_rec.address1, address2 = cust_rec.address2, city = cust_rec.city, state = cust_rec.state, zipcode = cust_rec.zipcode WHERE CURRENT OF q_curs . . . END IF END FOREACH

If you specify one or more columns in the FOR UPDATE clause of the DECLARE statement, you can only update those columns in a subsequent UPDATE WHERE CURRENT OF statement. If you do not list columns in a FOR UPDATE OF column-list clause, you can update any column retrieved in the query.

Using SQL

3-19

SELECT Cursors

The following example allows the user to update the fname and lname columns of the current row:
BEGIN WORK DECLARE q_curs CURSOR FOR SELECT * FROM customer FOR UPDATE OF fname, lname FOREACH q_curs INTO cust_rec IF status <> 0) EXIT FOREACH -- Display customer values here. . . . PROMPT "Do you want to change the name (y/n) ? " FOR answer IF answer= "y" -- Input the new customer values here. . . . UPDATE customer SET fname = cust_rec.fname, lname = cust_rec.lname WHERE CURRENT OF q_curs END IF END FOREACH

The position of the cursor does not change after an UPDATE WHERE
CURRENT OF statement is executed.

If your database has a transaction log but is not MODE ANSI, you must issue a BEGIN WORK statement before you OPEN a cursor DECLAREd FOR UPDATE that is not WITH HOLD. This requirement does not apply to cursors DECLAREd WITH HOLD, or to cursors that are not FOR UPDATE. In a MODE ANSI database, this distinction disappears because INFORMIX-4GL automatically includes all statements within transactions. You must not use the BEGIN WORK statement in the previous example with a MODE ANSI database. (The section “Data Integrity” later in this chapter describes transactions.)

The SCROLL Cursor
When you need to process the rows returned by a SELECT statement in random order, you must DECLARE a SCROLL cursor and use the OPEN, FETCH, and CLOSE statements.
3-20 Using SQL

SELECT Cursors

When you initially FETCH a row with a SCROLL cursor, all the rows in the active set up to and including the FETCHed row are placed in a temporary file and remain there until you close the cursor. If you then FETCH the same row or any row prior to it, INFORMIX-4GL retrieves the row from the temporary file instead of from the database. The temporary file allows you to retrieve rows in a random order. It also means, however, that subsequent changes to the database may not be reflected in the active set used by a SCROLL cursor. Thus, you cannot DECLARE a SCROLL cursor FOR UPDATE. Instead, you must DECLARE FOR UPDATE a regular cursor or a cursor WITH HOLD when you plan to perform a subsequent UPDATE WHERE CURRENT OF or DELETE WHERE CURRENT OF action. The following example shows how to use a SCROLL cursor and various cursor management statements to retrieve and display rows in the customer table.
MAIN . . . DECLARE q_curs SCROLL CURSOR FOR SELECT * FROM customer WHERE lname MATCHES last_name OPEN q_curs FETCH FIRST q_curs INTO p_customer.* IF status = NOTFOUND THEN CALL mess("No customers found.") ELSE DISPLAY BY NAME p_customer.* CALL viewcust() END IF CLOSE q_curs . . . END MAIN

The MAIN program block includes the following statements:

• The DECLARE statement associates a SCROLL cursor called q_curs
with the SELECT statement that retrieves rows from the customer table. (The program uses a SCROLL cursor so that rows specified by the SELECT statement can be retrieved in random order.)

• The OPEN statement runs the SELECT statement with the current value of
last_name and leaves the cursor pointing just before the first row of the active set.

• The FETCH FIRST statement attempts to retrieve the first row of the
active set.
Using SQL 3-21

SELECT Cursors

• The IF statement displays a message indicating that the active set is
empty if the value of the status variable is NOTFOUND. Otherwise, the program displays the first row on a screen form and calls a function that allows the user to browse through the rows in the active set.

• The CLOSE statement releases the active set after all rows have been
processed. The viewcust function displays a menu that lets the user view the rows in the active set:
FUNCTION viewcust() MENU "BROWSE:" COMMAND "Next" "View the next customer in the list" FETCH NEXT q_curs INTO p_customer.* IF status = NOTFOUND THEN CALL mess("No more customers in this direction.") FETCH LAST q_curs INTO p_customer.* END IF DISPLAY BY NAME p_customer.* COMMAND "Previous" "View the previous customer in the list" FETCH PREVIOUS q_curs INTO p_customer.* IF status = NOTFOUND THEN CALL mess("No more customers in this direction.") FETCH FIRST q_curs INTO p_customer.* END IF DISPLAY BY NAME p_customer.* COMMAND "First" "View the first customer in the list" FETCH FIRST q_curs INTO p_customer.* DISPLAY BY NAME p_customer.* COMMAND "Last" "View the last customer in the list" FETCH LAST q_curs INTO p_customer.* DISPLAY BY NAME p_customer.* COMMAND "Exit" "Leave the menu" EXIT MENU END MENU END FUNCTION

This function consists of a MENU statement that contains the following COMMAND clauses: Next includes a FETCH NEXT statement that attempts to retrieve the next row of the active set. The IF statement returns the cursor to the last row and displays a message if the value of the status variable indicates that the cursor has moved beyond the last row of the active set. The DISPLAY BY NAME statement displays on the screen the row retrieved by the appropriate FETCH statement.

Previous includes a FETCH PREVIOUS statement that attempts to retrieve the previous row of the active set. The IF statement returns the cur3-22 Using SQL

SELECT Cursors

sor to the first row, and displays a message if the value of the status variable indicates that the cursor has moved beyond the first row of the active set. The DISPLAY BY NAME statement displays on the screen the row retrieved by the appropriate FETCH statement. First Last Exit includes a FETCH FIRST statement that retrieves the first row in the active set and displays it on the screen. includes a FETCH LAST statement that retrieves the last row in the active set and displays it on the screen. includes an EXIT MENU statement that terminates the MENU statement.

All FETCH statements except the default FETCH NEXT statement require that you first DECLARE a SCROLL cursor. The default FETCH statement works with all cursors. Note: When you open a cursor that identifies a SELECT statement containing a program variable, INFORMIX-4GL runs the SELECT statement with the current value of the program variable. In the following example, the active set produced by the first OPEN statement differs from the active set produced by the second OPEN statement because the value of last_name changes from Baxter to Grant:
LET last_name = "Baxter" DECLARE q_curs SCROLL CURSOR FOR SELECT * FROM customer WHERE lname MATCHES last_name OPEN q_curs . . . CLOSE q_curs LET last_name = "Grant" OPEN q_curs

The Cursor WITH HOLD
In a database with transactions, the COMMIT WORK and ROLLBACK WORK operations end a transaction and release all row and table locks. In addition, these statements close all cursors except those DECLAREd WITH HOLD. Unlike other cursors, you can OPEN a cursor WITH HOLD outside a transaction, and you must explicitly CLOSE the cursor.

Using SQL

3-23

SELECT Cursors

The following example outlines a typical program structure that uses a cursor WITH HOLD.
LET sel1 = "SELECT order_date FROM orders WHERE customer_num = ? FOR UPDATE" PREPARE st1 from sel1 DECLARE c_master CURSOR WITH HOLD FOR SELECT customer_num FROM customer WHERE city = "Redwood City" DECLARE c_detail CURSOR FOR st1 OPEN c_master WHILE TRUE FETCH c_master INTO p_custnum IF status = NOTFOUND THEN EXIT WHILE END IF BEGIN WORK OPEN c_detail USING p_custnum WHILE true FETCH c_detail INTO p_orddate IF status = NOTFOUND THEN EXIT WHILE END IF UPDATE orders SET order_date = "02/02/90" WHERE CURRENT OF c_detail END WHILE COMMIT WORK END WHILE CLOSE c_master

In this program, the cursor WITH HOLD provides the following advantages:

• You can open the c_master cursor outside a transaction. The BEGIN WORK
statement appears after you OPEN the c_master cursor and perform a FETCH.

• The COMMIT WORK at the end of each iteration of the first WHILE loop
does not close the c_master cursor. The cursor remains open to FETCH the next master row after the COMMIT WORK has closed the c_detail cursor and released all locks. The updated rows are now available to other users on the system. If you do not use a cursor WITH HOLD, you must place the BEGIN WORK and COMMIT WORK statements completely outside the first WHILE loop. You would open both the c_master and c_detail cursors, FETCH all master rows, and FETCH and UPDATE all detail rows within the single transaction. This approach has the following drawback: it holds all locks for the duration of the entire loop. If your program updates a large number of rows, you can

3-24

Using SQL

INSERT Cursors

approach the limits that your operating system places on the number of rows that can be locked at one time. In addition, the locked rows are unavailable to other users on the system.

Cursors WITH HOLD and Locks
In a non-MODE ANSI database with transactions, you must open any cursor DECLAREd FOR UPDATE (but not WITH HOLD) inside a transaction. (In a MODE ANSI database, all statements are automatically within a transaction.) Thus, any UPDATE or DELETE actions that are based on a cursor that is not DECLAREd as WITH HOLD occur within a transaction. You can always roll back the actions if necessary. In a database that is not MODE ANSI, you cannot roll back an UPDATE or DELETE operation performed with a cursor WITH HOLD outside of a transaction, because an SQL operation that takes place outside a transaction is treated as a singleton transaction. Any locks acquired during a singleton transaction are released as soon as the operation ends. Outside a transaction, no locks are retained from statement to statement. In short, the cursor WITH HOLD is designed to provide a natural way of doing a read-only, forward scan over a table, independent of transaction boundaries. Note the risks of using a cursor WITH HOLD outside of a transaction, namely that rows accessed by the cursor are no longer locked. Note: See the INFORMIX-OnLine Programmer’s Manual for a discussion of cursors WITH HOLD and locks on the INFORMIX-OnLine database engine.

Cursors WITH HOLD in a MODE ANSI Database
The cursor WITH HOLD is an Informix extension to ANSI standard syntax. You can use a cursor WITH HOLD with a database created as MODE ANSI. However, the use of the WITH HOLD keywords cause a warning message when the DBANSIWARN environment variable is set, or when the program is compiled with the -ansi flag.

INSERT Cursors
You can associate a cursor with an INSERT statement as well as a SELECT statement. The INSERT cursor permits data to be more efficiently inserted into a database by buffering the data in memory and writing to the disk only

Using SQL

3-25

INSERT Cursors

when the buffer is full. The following statements allow you to declare and manipulate an INSERT cursor. (For complete information about the syntax of each statement, see Chapter 7 of the INFORMIX-4GL Reference Manual).
DECLARE

associates a cursor with an INSERT statement. (The INSERT statement cannot contain an embedded SELECT statement.) You cannot DECLARE a SCROLL INSERT cursor. sets up an insert buffer for an INSERT cursor. stores a row in the INSERT buffer for later insertion into the database. When you fill the buffer (by executing a series of PUT statements), INFORMIX-4GL automatically inserts the rows into the appropriate table as a block. forces INFORMIX-4GL to insert the buffered rows into the database without closing the INSERT cursor. You can force the insertion using the FLUSH statement, but you cannot delay insertion by not using the FLUSH statement. flushes the insert buffer and closes the INSERT cursor.

OPEN PUT

FLUSH

CLOSE

For databases with transactions, you must issue the OPEN, PUT, FLUSH, and CLOSE statements within a transaction. For example, you can use these cursor management statements to insert customers into the customer table, block by block. See the following example:
DECLARE ins_curs CURSOR FOR INSERT INTO customer VALUES (p_customer.*) OPEN ins_curs LET answer = "y" WHILE answer = "y" INPUT BY NAME p_customer.fname THRU p_customer.phone LET p_customer.customer_num = 0 PUT ins_curs PROMPT "Do you want to enter ", "another customer (y/n) ? " FOR answer END WHILE CLOSE ins_curs 3-26 Using SQL

INSERT Cursors

This example includes the following statements:

• The DECLARE statement associates a cursor called ins_curs with an
INSERT statement that inserts a row into the customer table.

• The OPEN statement sets up the insert buffer for the INSERT cursor. • The WHILE loop includes statements that insert information entered
on a screen form into the customer table, block by block. Specifically, the INPUT statement allows the user to enter customer information on a screen form and stores the information in the p_customer record. The PUT statement stores the current values in the p_customer record in the insert buffer. If the insert buffer becomes full as the result of a PUT statement, the rows are automatically inserted into the customer table as a block.

• The CLOSE statement inserts any rows that remain in the insert buffer into
the customer table and closes the INSERT cursor. When you use an INSERT cursor, you should CLOSE the cursor to insert any buffered rows into the database before allowing your program to end. The user can lose data if the cursor is not closed properly. For example, if the user presses the Interrupt key during input in the following program, INFORMIX-4GL closes the INSERT cursor before leaving the program. (Any remaining rows in the insert buffer are inserted into the database before the program stops.)
DEFER INTERRUPT . . . DECLARE ins_curs CURSOR FOR INSERT INTO customer VALUES (p_customer.*) OPEN ins_curs LET answer = "y" WHILE answer = "y" INPUT BY NAME p_customer.fname THRU p_customer.phone ON KEY (INTERRUPT) CLOSE ins_curs EXIT PROGRAM END INPUT LET p_customer.customer_num = 0 PUT ins_curs PROMPT "Do you want to enter another customer (y/n) ? FOR answer END WHILE CLOSE ins_curs . . .

"

You can determine whether INFORMIX-4GL successfully executes a PUT, FLUSH, or CLOSE statement by examining the values of the status and SQLCA.SQLERRD[3] variables. (See the section “SQLCA Record,” later in this

Using SQL

3-27

Dynamic Management

chapter, for more information on these variables.) If INFORMIX-4GL simply puts a row in the insert buffer, it assigns the following values to these global variables:
status = 0 SQLCA. SQLERRD [3] = 0

If INFORMIX-4GL successfully inserts a block of rows into the database as a result of a PUT, FLUSH, or CLOSE statement, it assigns the following values:
status = 0 SQLCA. SQLERRD [3] = the number of rows inserted

If, as a result of a PUT, FLUSH, or CLOSE statement, INFORMIX-4GL is unsuccessful in its attempt to insert an entire block of rows into the database, it assigns the following values:
status = a negative number corresponding to the error message SQLCA. SQLERRD [3] = the number of rows successfully inserted

Dynamic Management
The preceding discussion assumes that you know what the SQL statements are when you write your 4GL programs. That is the case for most applications where you are performing predetermined activities on your database. In some advanced applications, however, you will not know the statement at compile time:

• Interactive programs, where the user supplies input at run time from the
keyboard

• Programs intended to work with different databases whose structure can
vary In situations like these, you must work with dynamically defined statements. There are four dynamic management statements:
PREPARE

takes a character string, interprets it as an SQL statement, and assigns it to a statement identifier. Subsequent dynamic management statements refer to the SQL statement through the statement identifier. runs the previously PREPAREd statement associated with the statement identifier. Use EXECUTE for all PREPAREd statements except the following statements: • SELECT statements

EXECUTE

3-28

Using SQL

Preparing Statements

• INSERT statements that use an insert cursor
DECLARE FREE

has options that DECLARE a cursor for a PREPAREd SELECT or INSERT statement. releases the database engine resources that are required by a PREPAREd statement.

Preparing Statements
You can use the PREPARE statement with either a character string or a character variable that evaluates to an SQL statement. The form of the PREPARE statement that you choose depends on the type of input (if any) required by the statement. You can use either form of the PREPARE statement if the statement requires no input or input for values. If the statement requires input for SQL identifiers such as column names, you must use the PREPARE statement with a character variable. In general, you can improve the performance of your programs by PREPARing statements that you plan to execute many times. Specifically, you might want to PREPARE a statement that requires different input each time it is executed. Note: You can PREPARE any SQL statements except these:
CLOSE DECLARE EXECUTE FETCH LOAD OPEN PREPARE SELECT (with INTO variable clause) UNLOAD

See the section “SQL Statement Summary” earlier in this chapter for more information about SQL statements. Chapter 2 describes the INFORMIX-4GL statements which you cannot PREPARE. Note: When you issue a DECLARE statement that includes the INSERT or SELECT keywords, you declare a cursor that can perform an associated PUT or FETCH statement, even though you do not explicitly PREPARE the statement. For example,
DECLARE m_curs CURSOR FOR INSERT INTO state VALUES (code, sname)

is a cursor declaration that specifies an INSERT statement. When you OPEN this cursor, INFORMIX-4GL automatically PREPAREs the INSERT statement. Implicitly PREPAREd statements become an issue only if you exceed the engine resources allocated for such statements. If this happens, you can use the FREE statement to release the resources. The FREE statement is described later in this chapter.

Using SQL

3-29

Preparing Statements

Statements That Require No Input
If a statement requires no input, you can PREPARE it from either a character string or character variable. For example, the following statement
PREPARE s1 FROM "SELECT * FROM customer"

produces the same result as
DEFINE sel_stmt CHAR(25) LET sel_stmt = "SELECT * FROM customer" PREPARE s1 FROM sel_stmt

Statements That Require Input for Values
Similarly, you can use either form of PREPARE when a PREPAREd statement requires input for one or more values.

Preparing a Character String
If you use PREPARE with a character string, you must use a question mark (?) instead of a program variable in the character string as a placeholder for a value. Specifically, the question mark can represent a value or expression in a character string, but not an SQL identifier (such as a column name or table name). Usually, you use a question mark to represent a value in the following clauses:

• The WHERE clause of a SELECT, UPDATE, or DELETE statement:
PREPARE sel1 FROM "SELECT * FROM customer WHERE lname MATCHES ?"

• The VALUES clause of an INSERT statement:
PREPARE ins1 FROM "INSERT INTO manufact VALUES (?, ?)"

• The SET clause of an UPDATE statement:
PREPARE upd1 FROM "UPDATE customer SET zipcode = ? WHERE CURRENT OF q_curs"

When you PREPARE a statement from a character string, you do not need to supply values for the question marks until you execute the PREPAREd statement. (See the section “Executing PREPAREd Statements” later in this chapter for more information.)

3-30

Using SQL

Preparing Statements

Preparing a Character Variable
Alternatively, you can PREPARE a statement that requires input for values from a character variable.

• First, you use a LET statement to concatenate the variable(s) containing
the input to one or more strings that represent the rest of the statement.

• Second, you PREPARE the character variable that contains the resulting
SQL statement.

The following example shows how to use this approach to PREPARE a statement that selects rows from the customer table based on a customer number that the user supplies:
DEFINE cust_num INTEGER, sel_stmt CHAR(100) PROMPT "Enter a customer number: " FOR cust_num LET sel_stmt = "SELECT * FROM customer WHERE customer_num = ", cust_num USING "###" PREPARE sel1 FROM sel_stmt

When INFORMIX-4GL encounters the LET statement in this example, it concatenates a character string containing part of the SELECT statement to the variable cust_num, which contains a customer number that the user supplies. INFORMIX-4GL then assigns the resulting string to the large character variable sel_stmt and PREPAREs it. When you use this approach, you must supply input values when you assign the SQL statement to the character variable that you will later PREPARE. Note: If you use the LET statement to concatenate strings to variables that contain CHAR or DATE values, or DATETIME or INTERVAL constants, make sure that quotes appear around those values in the resulting character string. To embed a quote in a character string, you must enter a backslash (\) followed by a double quote ("). For example, the LET statement
LET sel_stmt = "SELECT * FROM customer WHERE lname MATCHES \"", last_name CLIPPED, "\"" PREPARE s1 FROM sel_stmt

produces the following character string if the current value of last_name is Baxter:
SELECT * FROM customer WHERE lname MATCHES "Baxter"

Using SQL

3-31

Preparing Statements

In contrast, the statements like the following do not require quotation marks around placeholders for values:
DECLARE q_curs CURSOR FOR SELECT * FROM customer WHERE lname MATCHES last_name PREPARE s1 FROM "SELECT * FROM customer WHERE lname MATCHES ?"

Statements That Require Input for SQL Identifiers
You must use PREPARE with a character variable to PREPARE a statement that requires data for an SQL identifier (such as a column name, table name, username, view name, or synonym). The approach that you use is identical to that described in the previous section.

• First, you concatenate the variable(s) representing the SQL identifier(s) to
one or more character strings that contain the rest of the statement.

• Second, you assign the resulting string to a large character variable and
PREPARE it.

The following example shows how to use this approach to PREPARE a statement that grants the CONNECT privilege to a specified user:
DEFINE p_user CHAR(12), grant_stmt CHAR(50) PROMPT "Enter the name of user ", "to receive CONNECT privilege: " FOR p_user LET grant_stmt = "GRANT CONNECT TO ", p_user CLIPPED PREPARE s1 FROM grant_stmt

When INFORMIX-4GL encounters the LET statement in this example, it concatenates a character string containing part of the GRANT statement to the character variable p_user, which contains a username. INFORMIX-4GL then assigns the resulting string to grant_stmt and PREPAREs it.

3-32

Using SQL

Executing PREPAREd Statements

Executing PREPAREd Statements
The method for executing a PREPAREd statement depends on the kind of statement that you want to run. The EXECUTE statement runs any PREPAREd statements except those that follow:

• •

SELECT statements INSERT statements that require a cursor

The DECLARE statement has a special form designed to work with PREPAREd SELECT and INSERT statements.

The EXECUTE Statement
If you have PREPAREd a non-SELECT statement from a character variable or from a character string that does not contain question marks, you can run it with a simple EXECUTE statement, as shown in the following examples:
PREPARE s1 FROM "DELETE FROM customer WHERE customer_num = 115" EXECUTE s1 LET del_stmt = "DELETE FROM customer WHERE customer_num = 115" PREPARE s1 FROM del_stmt EXECUTE s1

If you PREPAREd a non-SELECT statement from a character string that does contain question marks, you must use the EXECUTE statement with a USING clause. This clause consists of the USING keyword followed by one or more program variables representing the values that replace the question marks in the PREPAREd character string.

Using SQL

3-33

Executing PREPAREd Statements

The EXECUTE statement in the following example executes a DELETE statement using a customer number that the user supplies:
PREPARE s1 FROM "DELETE FROM customer WHERE customer_num = ?" PROMPT "Do you want to delete a customer (y/n) : FOR answer WHILE answer = "y" PROMPT "Enter a customer number : " FOR cust_num EXECUTE s1 USING cust_num IF status = 0 THEN DISPLAY "Row deleted." END IF IF status = 100 THEN DISPLAY "No row found for that customer number" ELSE CALL mess("Unable to delete the customer row.") END IF PROMPT "Do you want to delete another customer (y/n): " FOR answer END WHILE "

When INFORMIX-4GL executes the PREPAREd DELETE statement in this example, it substitutes the current value of cust_num for the question mark in the character string.

3-34

Using SQL

Executing PREPAREd Statements

Running PREPAREd SELECT Statements
If you PREPAREd a SELECT statement from a character variable or from a character string that does not contain question marks, you can use a DECLARE statement with either FOREACH or OPEN, FETCH, and CLOSE. Two examples follow:
LET sel_stmt = "SELECT * FROM customer WHERE lname MATCHES \"", last_name CLIPPED, "\"" PREPARE sel1 FROM sel_stmt DECLARE q_curs CURSOR FOR sel1 FOREACH q_curs INTO p_customer.* DISPLAY BY NAME p_customer.* . . . END FOREACH PREPARE sel1 FROM "SELECT * FROM customer" DECLARE q_curs CURSOR FOR sel1 FOREACH q_curs INTO p_customer.* DISPLAY BY NAME p_customer.* . . . END FOREACH

If you PREPAREd a SELECT statement from a character string that does contain one or more question marks, you must use the DECLARE statement with an OPEN statement that includes a USING clause. As described

Using SQL

3-35

Executing PREPAREd Statements

previously, this clause consists of the USING keyword followed by one or more program variables representing the values that replace the question marks in the character string. An example follows:
PREPARE sel1 FROM "SELECT * FROM customer WHERE zipcode MATCHES ?" DECLARE q_curs CURSOR FOR sel1 PROMPT "Enter a zipcode: " FOR zip OPEN q_curs USING zip WHILE TRUE FETCH q_curs INTO p_customer.* IF status = NOTFOUND THEN EXIT WHILE END IF DISPLAY BY NAME p_customer.* . . . END WHILE CLOSE q_curs

When INFORMIX-4GL opens the cursor for the PREPAREd SELECT statement in this example, it substitutes the current value of zip for the question mark in the character string. A Note on Preparing and Executing SELECT Statements for Update: A previous section entitled ‘‘Deleting or Updating the Current Row’’ describes how to use the DECLARE FOR UPDATE statement and a subsequent DELETE or UPDATE statement to delete or update the current row. If you want to use DECLARE FOR UPDATE with a PREPAREd SELECT statement,

3-36

Using SQL

Executing PREPAREd Statements

make sure that the FOR UPDATE clause appears as part of the PREPAREd character string or character variable and not as part of the DECLARE statement. An example follows:
PREPARE s1 FROM "SELECT * FROM customer FOR UPDATE" DECLARE q_curs CURSOR FOR s1 FOREACH q_curs INTO p_customer.* . . . DELETE FROM customer WHERE CURRENT OF q_curs END FOREACH

Running PREPAREd INSERT Statements
If you have PREPAREd an INSERT statement, you can run it by using the EXECUTE statement or the PUT statement. A previous section, ‘‘The EXECUTE Statement,’’ describes how to use the EXECUTE statement if you want INFORMIX-4GL to insert one row into the database at a time. This section explains how to DECLARE a cursor and use the PUT statement to insert rows into the database through an insert buffer. If you PREPARE an INSERT statement from a character variable or from a character string that does not contain question marks, you can use the DECLARE, OPEN, FLUSH and/or CLOSE statements with a simple PUT statement, as follows:
PREPARE s1 FROM "INSERT INTO manufact VALUES ("WLS", "Willis") DECLARE icurs CURSOR FOR s1 OPEN icurs PUT icurs . . . CLOSE icurs

If you PREPARE an INSERT statement from a character string that does contain one or more question marks, you must use the DECLARE, OPEN, FLUSH, and/or CLOSE statements with a PUT statement that includes a FROM

Using SQL

3-37

Preparing Multiple SQL Statements

clause. This clause consists of the FROM keyword, followed by one or more program variables representing the values that replace the question marks in the character string. An example follows:
PREPARE s1 FROM
"INSERT INTO customer (customer_num, company) VALUES (0, ?)"

DECLARE ins_curs CURSOR FOR s1 OPEN ins_curs LET answer = "y" WHILE answer = "y" Prompt "Enter a customer: " FOR p_customer.company PUT ins_curs FROM p_customer.company PROMPT "Do you want to enter another customer (y/n) ? FOR answer END WHILE CLOSE ins_curs "

When INFORMIX-4GL executes the PUT statement in this example, it substitutes the current value of p_customer.company for the question mark in the PREPAREd INSERT statement and stores the row in the insert buffer for later insertion into the database.

Preparing Multiple SQL Statements
INFORMIX-4GL supports PREPAREd objects that combine more than one data manipulation statement. To use this dynamic management feature involves the same procedures as for simple PREPAREd statements, but with character strings that concatenate several SQL statements that you can successively execute to perform some task. (A multiple-statement PREPARE cannot, however, reference an object like a table or synonym that is created by another SQL statement that you specify in the same PREPARE statement.)

3-38

Using SQL

The FREE Statement

The following example updates the stores database by replacing the existing manufacturer codes with new codes. Since the manu_code columns are potential join columns that link three of the tables, the task of replacing the old codes with the new must be performed in three tables.
DATABASE stores MAIN DEFINE code_change RECORD new_code LIKE manufact.manu_code, old_code LIKE manufact.manu_code END RECORD, sqlmulti CHAR(250) PROMPT "Enter new manufacturer code: " FOR code_change.new_code PROMPT "Enter old manufacturer code: " FOR code_change.old_code LET sqlmulti =
"UPDATE manufact SET manu_code = ? WHERE manu_code = ?;", "UPDATE stock SET manu_code = ? WHERE manu_code = ?;", "UPDATE items SET manu_code = ? WHERE manu_code = ?"

PREPARE exmulti FROM sqlmulti EXECUTE exmulti USING code_change.*, code_change.*, code_change.* END MAIN

This program prompts the user for both the new and the old three-letter code. It then updates all corresponding rows in three tables (manufact, stock, and items) as a single action.

The FREE Statement
You can create a PREPAREd statement explicitly in a PREPARE statement, which assigns an INFORMIX-4GL identifier to the statement that you specify in the FROM clause. You can also create a PREPAREd statement implicitly, by associating a cursor with a DECLARE statement that includes the SELECT or INSERT keywords. When you specify that cursor in an OPEN statement, INFORMIX-4GL automatically PREPAREs the associated INSERT or SELECT statement. Both explicitly and implicitly PREPAREd statements require database engine resources. You can ignore this cost in typical programs, but there is a limit to the number of PREPAREd objects that the 4GL application can create.

Using SQL

3-39

Data Access

The FREE statement is useful in this situation where you are at the engine’s limit on the number of PREPAREd objects. In effect, it ‘‘unPREPAREs’’ a statement, releasing the resources that had been allocated to that statement, so that you can use them to PREPARE something else. The FREE statement supports two formats:
FREE statement-name FREE cursor-name

Always use the first form if you explicitly PREPAREd the statement. The second form is for implicitly PREPAREd statements to which you assigned no statement-name. If you assigned a statement-name with PREPARE, freeing an associated cursor does not release the PREPAREd statement. After a successful FREE statement, you cannot use statement-name with a cursor or with EXECUTE unless you PREPARE it again. If you FREE a cursor, you cannot use it again until you OPEN it.

Data Access
A user has access to the database, a table, and to specific columns within a table only when the DBA or the owner of the table specifically grants these privileges. You can temporarily limit access to a table by executing the LOCK TABLE statement. (Under transactions, the affected rows are locked until the transaction is complete. Explicit table/record locking is generally not required.) The following SQL statements affect data access:
GRANT REVOKE LOCK TABLE

grants database access privileges to specific users or to the public. removes database access privileges from specific users or from the public. limits access to the table to the current user only, or allows other users only to read the table. Use the LOCK TABLE statement only when making major changes to a table in a multiuser environment and when simultaneous interaction with the table by another user would interfere. LOCK TABLE decreases the accessibility of the database, since it prevents other users from accessing the table. If the database has transactions and is not MODE ANSI, you must issue a BEGIN WORK statement before you can issue the LOCK TABLE statement. restores access to a previously LOCKed table.

UNLOCK TABLE 3-40 Using SQL

User Status and Privileges

See the next section, ‘‘User Status and Privileges,’’ for further information. Use of the LOCK TABLE and UNLOCK TABLE statements is described in the section “Locking” later in this chapter. Chapter 7 identifies the various keywords that can specify user privileges in the GRANT and REVOKE statements.

User Status and Privileges
When you create a database, you are automatically the DBA of that database and are the only one who has access to the database. Another user does not have access to a database until you grant the CONNECT privilege to that person. Another user cannot create or drop tables and indexes unless granted the RESOURCE privilege. Only the DBA (you, initially) can grant these privileges. You can also grant the DBA privilege to another user. The DBA privilege extends all the powers of the Database Administrator to the grantee, including the ability to alter the system tables; to drop, start, and roll forward the database; and to grant CONNECT, RESOURCE, and DBA privileges to others. If you have the RESOURCE privilege, you have the CONNECT privilege by default. With the DBA privilege, you have both the RESOURCE and CONNECT privileges. You can only revoke the privilege of a DBA grantee; you cannot revoke your own DBA privilege. If you, as the creator of a database, grant DBA privileges to another user, that user can revoke the DBA privilege from you, the database creator. This last property permits the transfer of authority from the maker of the database application to the person who has responsibility for maintaining the database.
INFORMIX-4GL allows the CONNECT and RESOURCE privileges to be granted TO PUBLIC, in addition to specifically named users.

In addition to these database-level privileges, the owner of the table can grant a collection of table-level privileges . These privileges permit the grantee access to specific columns to execute SELECT or UPDATE statements, or give the grantee authority to insert new rows, delete old rows, create indexes, and alter the structure of the table. In a non-MODE ANSI database, the default is to grant all table-level privileges (except ALTER) to all users (PUBLIC). In a MODE ANSI database, no default table-level privileges are granted. You must explicitly grant these privileges. However, if you use START DATABASE to convert your database to MODE ANSI, the existing privileges remain in effect unless you specifically revoke them.

Using SQL

3-41

Data Integrity

Several of the SQL statements (ALTER TABLE, ALTER INDEX, DROP INDEX, DROP TABLE, DROP VIEW, GRANT, RENAME COLUMN, RENAME TABLE, REVOKE) can be executed only by the DBA or by the owner of the specified table or index. (You can give others the privilege of executing the ALTER TABLE, GRANT, and REVOKE statements, with certain restrictions.) The owner of a table is the username of the person who executed the CREATE TABLE statement. The owner of an index is the one who executed the CREATE INDEX statement. Execution occurs when the compiled INFORMIX-4GL program containing the CREATE statements is run, not when the INFORMIX-4GL program is compiled.

Data Integrity
INFORMIX-4GL has features to protect the integrity of your data. These

features include recovery procedures through transaction logs and audit trails, and concurrency control through record locking and table locking.

Transactions
INFORMIX-4GL supports data integrity by implementing the idea of transactions. A transaction is a series of database operations (SQL statements) that

you want to be completed entirely or not at all. Examples of transactions are abundant in bookkeeping, where several operations on several different accounts must be made as a unit or the books will be out of balance. You can use the following statements to control transactions in INFORMIX-4GL programs: marks the start of a transaction (if the database is not BEGIN MODE ANSI). WORK marks the end of a transaction by authorizing all database COMMIT changes since the transaction began. WORK marks the end of a transaction by revoking all database ROLLBACK changes since the transaction began. WORK initiates a new transaction log file and (optionally) START converts a database to MODE ANSI. DATABASE ROLLFORWARD uses a transaction log file to restore a database from backup. DATABASE The BEGIN WORK, COMMIT WORK, ROLLBACK WORK, and ROLLFORWARD DATABASE statements are only available when the database has a transaction log. You can use the WITH LOG IN clause of the CREATE DATABASE or START DATABASE statements to create a transaction log file that records all modifi3-42 Using SQL

Transactions

cations to the database. If you also specify the MODE ANSI option, transactions are implicit, and you are always within a transaction. You terminate the transaction when you issue a COMMIT WORK or ROLLBACK WORK statement. In terms of transactions, there are three kinds of 4GL databases:

• A database that has no transaction log is described as a database ‘‘without
transactions.’’

• A database created or started with a transaction log and as MODE ANSI
is described as a database ‘‘with implicit transactions.’’ (A synonymous term is ‘‘a MODE ANSI database.’’)

• A database created or started with a transaction log, but not as MODE
ANSI, is a database ‘‘with explicit transactions.’’ (You use the BEGIN WORK statement to begin a transaction.)

Databases Without Transactions
A database without transactions may require considerable recovery effort if it becomes corrupted through failure of a data manipulation statement, particularly if the error occurs within a series of closely related database operations that form a single unit of work. For example, under transactions, you can UPDATE several rows as a single unit of work. If the UPDATE fails after changing some of the rows but not all, you can ROLLBACK the transaction to the original state where no rows are modified. Without transactions, you must take explicit action to restore the updated rows. (The “Audit Trails” section later in this chapter describes a recovery procedure for databases without transactions.)

Databases with Implicit Transactions
If you want a database to have implicit transactions, you must create or start the database as MODE ANSI and specify a transaction log file. All SQL statements are automatically part of a transaction. Note: You do not need to use the BEGIN WORK statement with a MODE ANSI database, since the statement is implied.

Using SQL

3-43

Transactions

Databases with Explicit Transactions
If your database supports explicit transactions, you must issue the BEGIN WORK statement before you perform a series of operations that you want to consider a unit. This statement causes all subsequently altered rows of the database tables to be locked against modification by others (although others can view them). If you do not execute the BEGIN WORK statement, INFORMIX-4GL treats each data manipulation statement that changes the database as a singleton transaction. Each statement, if it executes successfully, is committed, and the database is permanently altered. If the statement fails, there is an automatic rollback to the status before the statement. You must execute cursor manipulation statements inside a transaction if your database supports explicit transactions. That is, first execute the BEGIN WORK statement before opening a cursor. All open cursors that are not WITH HOLD are closed by the COMMIT WORK and ROLLBACK WORK statements.

Using Transactions
The number of rows that can be locked at one time by all users is limited. The actual limit depends on your operating system. Try to restrict the definition of a transaction to a few statements that involve only a few rows. If you expect that the number of rows to be entered during the transaction will be large, LOCK the tables involved until the transaction is completed. Regardless of whether a transaction is explicit or implicit, you can terminate the transaction with a COMMIT WORK statement when you are satisfied that the series of operations has produced the desired results. If you are not satisfied with the results, you can terminate the transaction with a ROLLBACK WORK statement. With the exceptions stated in the next paragraph, this statement restores the database to the state that existed immediately before the transaction began. Both the COMMIT WORK and the ROLLBACK WORK statements release all row and table locks, making the data accessible for modification by others. On INFORMIX-SE, you cannot roll back GRANT or REVOKE statements, nor any of the data definition statements. These statements alter the number or names of tables, or change the number, names, data types, or indexes of columns. If they were executed successfully, they are committed, and the ROLLBACK WORK statement cannot undo them. If your database supports explicit transactions, you should not use these statements within a transaction.

3-44

Using SQL

Transaction Log File Maintenance

Transaction Log File Maintenance
The transaction log file can become quite large and, periodically, the DBA will want to archive it on tape and initiate another log file. At the same time, the DBA should also create a backup of your database. In general, every log file must have a corresponding archive copy of the database. After backing up the log file and the database, the DBA must specify an empty log file. To reuse the same log file, the DBA should create an empty log file with the same name as the old one. The DBA can do this with the following command:
cat /dev/null > logfile

To change the name of the log file, the DBA must execute the START DATABASE statement just before making a backup of the database. The START DATABASE statement locks the database in EXCLUSIVE MODE while it is operating so that no further changes can be made. If START DATABASE fails, no database is open. If the database is without transactions and you want to use transactions, the DBA must execute the START DATABASE command just before making a copy of the database. If there is a backup copy of the database and a transaction log file that begins with the operations executed immediately after the backup was made, the DBA can bring the backup database up to date with the ROLLFORWARD DATABASE statement. This statement recovers the database through the last terminated transaction. The DBA must load the backup database files and execute the ROLLFORWARD DATABASE statement. After rolling the database forward, the DBA is the only one who has access to the database, since it is left in an exclusive mode. This state allows the DBA to check the database for errors before making it generally available. Logging does not occur during this checking phase. The DBA must close the database when it has been restored correctly.

Audit Trails
An audit trail is a file that contains a history of all additions, deletions, updates, and manipulations to a database table. An audit trail serves a purpose similar to that of a transaction log: each is used to maintain a record of modifications to a database, and each can be used to update backup copies of a database. Three audit trail statements are available to protect the integrity of a table:
CREATE AUDIT DROP AUDIT

creates an audit trail for a table. removes the audit trail on a table.
Using SQL 3-45

Audit Trails

RECOVER TABLE restores a table using the audit trail.

Creating an Audit Trail
Use the CREATE AUDIT statement to create an audit trail file and to begin writing the audit trail. The format is
CREATE AUDIT FOR table-name IN "pathname"

Here table-name is the name of the table for which you want to create an audit trail file and pathname is the full pathname of the audit trail file. The audit trail file should be on a physical device other than the one that holds the data so that a system failure affecting the device that holds the data does not also damage the audit trail. If your computer system has more than one hard disk, the audit trails should be written to a disk not containing the data. To use the audit trail, make a backup copy of the table after you have executed a CREATE AUDIT statement, but before you have made any changes to the table. Once you have started the audit trail and have made a backup, you are ready to work with the table. You can drop and create an audit trail file whenever you want. Drop and create the audit trail files just before you make a complete backup of the device containing the data file. If a system failure should occur, you can use the audit trail to back up the table from the time of the last backup to the time when the failure occurred.

Recovering a Table
In the event of a system failure, you can use the RECOVER TABLE statement to restore a database table by using a backup copy of the table and an audit trail file. You must first restore a backup copy of the table. The backup copy must be in the original state that it was in when the audit trail was started. If it is not in the original state, the recovery fails. The format of the recovery statement is
RECOVER TABLE table-name

where table-name is the name of the table you want to recover. Once you recover the table, use the DROP AUDIT statement to remove the contents of the audit trail file. Then run the CREATE AUDIT statement to start a new audit trail file. Finally, make a new backup copy of the table.

3-46

Using SQL

Comparison of Transactions and Audit Trails

Comparison of Transactions and Audit Trails
Transactions provide data integrity in two ways. First, they guarantee that SQL statements are either successfully completed or completely canceled. If, for example, you update several rows of one or more tables within a transaction, the entire update is guaranteed either to succeed by updating all rows, or to fail without changing any rows. Second, you can use the transaction log to recover an entire database. Audit trails are associated with individual tables. They do not guarantee that modifications to several rows of a table either succeed entirely or fail without any effect. You can use an audit trail file only to recover the table for which it is created. You should consider using audit trails in place of a transaction log only when you have one or a few critical tables and you do not need the additional facilities provided by transactions. If you need to maintain the integrity of the database as a whole, or need the guarantee that SQL statements are executed as a unit either entirely or not at all, you must use transactions.

Locking
INFORMIX-4GL uses locking to prevent different users from executing conflicting operations on the same data. Without locking, for example, two users could be allowed to update the same row at the same time. In this situation, the computer memory contains two different versions of the rows (the one updated by user A and the one updated by user B). Without some method of concurrency control, the user whose row is the last one actually written to the file ‘‘wins’’ and overwrites changes by the other user.

The following SQL statements control locking: limits access to the table to the current user only or allows other LOCK users only to read the table. Use the LOCK TABLE statement TABLE only when making major changes to a table in a multi-user environment, and when simultaneous interaction with the table by another user would interfere. LOCK TABLE decreases the accessibility of the database since it prevents other users from accessing the table. If the database has transactions but is not MODE ANSI, you must issue a BEGIN WORK statement before you can issue the LOCK TABLE statement. restores access to a previously locked table. UNLOCK
TABLE

Using SQL

3-47

Row-Level Locking

SET LOCK MODE

alters the locking strategy, either to fail when a row is already locked, or to wait for the lock to be released before proceeding. (This statement is supported only on systems with UNIX System V locking, or with shared memory.)

In addition, in the rare instance in which you need to limit access to the entire database to a single user, you can open the database in EXCLUSIVE mode. INFORMIX-4GL provides two levels of locking:

• Row-level or record-level locking • Table-level or file-level locking
INFORMIX-4GL performs row-level locking implicitly. The locking strategy

can differ slightly, depending on whether or not the database uses transaction management. Data definition statements, such as ALTER TABLE, CREATE INDEX, and so on, use implied table-level locking. You can explicitly specify table-level locking. The following sections describe each level of locking and the methods for its use. Note: INFORMIX-OnLine supports additional functionality. Refer to the INFORMIX-OnLine Programmer’s Manual for more information.

Row-Level Locking
Ordinarily, INFORMIX-4GL locks a row when you execute an UPDATE statement, or when you execute a FETCH statement and the cursor is DECLAREd with a FOR UPDATE clause. If the UPDATE statement affects only one row, INFORMIX-4GL releases the lock immediately after performing the update. Locking the row prevents two programs from attempting to update the same row at the same time. One program receives the lock and can proceed with the update. The other program either fails in its attempt or waits for that program to release the lock. (See the section “Wait for Locked Row” later in this chapter.) If the UPDATE statement affects more than one row, INFORMIX-4GL uses the same row-locking strategy. As soon as a row is UPDATEd, the lock is released and the next row is locked and UPDATEd. When the UPDATE finishes, all rows are unlocked. If you want more control over the update of multiple rows, you can DECLARE a cursor FOR UPDATE. The WHERE clause of the SELECT statement specifies the rows you want to update. After you OPEN the cursor and FETCH a row, that row remains locked until you either CLOSE the cursor or FETCH the next row.

3-48

Using SQL

Table-Level Locking

Row-Level Locking in Transactions
If your database uses transaction management, rows that you INSERT, UPDATE or DELETE within a transaction remain locked until the end of the transaction. The end of a transaction is either a COMMIT WORK, where all modifications are made to the database, or a ROLLBACK WORK, where none of the modifications are made.
INFORMIX-4GL locks a row when it is selected for update. For example, if you DECLARE a cursor FOR UPDATE, the FETCH statement locks the row. If the row is updated, it remains locked until the end of the transaction. If the row is not updated, the lock is released upon the next FETCH.

Table-Level Locking
Use table-level locking to lock an entire table and prevent others from altering or seeing rows in that table. You may want to use this form of locking, for example, during batch operations that affect every row in a table. If the operations must be completed as a single transaction, it may be more efficient to lock the entire table before beginning the transaction. Normally, under transactions, INFORMIX-4GL locks each row manipulated by an UPDATE, DELETE, or INSERT statement. If you lock the entire table, however, INFORMIX-4GL does not use row-level locking, because it is not necessary. As a result, you are not likely to reach the limit that your operating system can place on the number of rows that can be locked at any one time. INFORMIX-4GL performs table-level locking automatically as part of the following statements: ALTER TABLE, DROP TABLE, CREATE INDEX, ALTER INDEX, and DROP INDEX. The LOCK TABLE statement has two extensions:

• If you lock the table IN SHARE MODE, other users are able to SELECT data
from the table, but they are not able to INSERT, DELETE, or UPDATE rows in the table.

• If you lock the table IN EXCLUSIVE MODE, other users are not able to
access the table at all until you execute an UNLOCK TABLE statement. Because locking an entire table prevents others from adding or altering data in the table, use this feature sparingly. Lock the entire table only when rowlevel locking (as described in the previous section) is not sufficient.

Using SQL

3-49

Wait for Locked Row

Wait for Locked Row
If another user locks a row in a table at the row level and you attempt to alter or delete that row (or examine it with SELECT statement FOR UPDATE), INFORMIX-4GL returns an error, stating that the row is locked. If you prefer that INFORMIX-4GL wait on any locked row until the competing process unlocks it, you can execute the SET LOCK MODE TO WAIT statement. From then on, your request waits until INFORMIX-4GL unlocks the requested row, and you do not receive an error code. If another user locks a table IN EXCLUSIVE MODE and you attempt to alter, delete, or even read a row in the table, INFORMIX-4GL returns an error code. The wait-for-lock feature applies only on systems that support kernel locking. Note: INFORMIX-OnLine supports additional functionality. Refer to the INFORMIX-OnLine Programmer’s Manual for more information.

Indexing Strategy
There are two major purposes for creating an index on columns of a database table: to speed sorting of rows and to optimize the performance of queries. When your application writes reports involving complex queries through a large database, significant time savings can result from judicious indexing. The drawback to having an index is that indexes slow down the process of inserting new data into the database. When you update a table, its indexes can also be modified. This is not a problem when you are adding information interactively, a row at a time, but can become serious when it is necessary to insert a large number of rows from one table into another. The solution to this potential conflict between needs is to take a dynamic approach to indexing. One of the advantages of an Informix relational database is that you do not have to decide issues like which columns to index at the time that you create your tables. You should write your applications to create indexes when you need them and to drop them when they get in the way. It takes time to create an index on a table already containing data, and you should create only those indexes that optimize the queries you make. For example, by judicious scheduling, you can create your indexes in anticipation of batch report writing during the night and drop them the next morning before there are huge data-entry needs.

3-50

Using SQL

Indexing Strategy

The following are hints for strategic indexing. Although the last two items refer to a single query, they apply when you anticipate making a number of queries with the same qualities.

• Do not create indexes for small tables with fewer than 200 rows. Speed
that you gain from using an index does not overcome the time required to open and search the index file on small tables.

• Do not create indexes on a column that has only a few possible values.
Such columns are those that contain data like sex, marital status, yes/no responses, or zip codes in a small city. Because data like this produces skewed indexes, indexing can cause the optimizing strategy of INFORMIX-4GL to fail and queries to take longer than if the columns were not indexed. If you have a frequent need to have data sorted on columns with a small range of possible values, create a temporary table of the sorted data. Another approach is to redesign the database with separate tables for each alternative value.

• If the WHERE clause of a SELECT statement imposes a condition on a single column, put an index on that column. If conditions are placed on several columns, make a composite index on all the affected columns. For the SELECT statement
SELECT * FROM items WHERE order_num > 1015

put an index on order_num. For the statement
SELECT * FROM items WHERE order_num = 1015 AND total_price = 1000.00

create a composite index on both order_num and total_price.

• If the WHERE clause of a SELECT statement has a join condition between
a single column in one table and a single column in another table, create an index on the column in the table with the larger number of rows. If several columns of one table have join conditions with several columns in another table, create a composite index on the affected columns of the table with the larger number of rows. For the SELECT statement
SELECT * FROM items, stock WHERE items.stock_num = stock.stock_num

place an index on stock_num in the items table, since it has many more rows than the stock table. You should execute the UPDATE STATISTICS

Using SQL

3-51

Query Optimizer

statement before the SELECT statement so that INFORMIX-4GL knows the current size of the tables. For the statement
SELECT * FROM items, stock WHERE items.stock_num = stock.stock_num AND items.manu_code = stock.manu_code

put a composite index on stock_num and manu_code in the items table.

Query Optimizer
It is not always easy to know how indexes are used during a query, but you can determine this by issuing the SET EXPLAIN statement. When you set this statement to ON, a file called sqexplain.out is created in the current directory. A description of the decisions made by the query optimizer, a feature of the database engine to improve performance, is written into this file for each subsequent query. The recorded information includes the order of table access, how filters are applied, and what (if any) indexes are used in processing the query. For example, if your queries seem to be taking longer than necessary, you may choose to change your indexing strategy. However, in a complex query, it may be difficult to predict the actual order of actions taken by the optimizer, thus making it difficult to determine what (if any) indexes should be added or dropped. The SET EXPLAIN statement provides you with information to determine exactly how the database is being accessed and to help you assess whether changing indexes may improve the decisions of the optimizer.

Auto-Indexing
If you execute a SELECT statement that includes a join between two tables and there are no indexes on the joined columns, INFORMIX-4GL creates a temporary index on the table with the larger number of rows before performing the join. The index disappears when the query finishes. This enhancement is transparent to the user, except for a dramatic improvement in the speed of unindexed joins.

Clustered Indexes
Since UNIX systems extract information from the disk in blocks, rows physically on the same block and already in the order of an index are retrieved more quickly. Ordinarily, no relationship need exist between the physical

3-52

Using SQL

NULL Values

order of the data in the .dat file and the order in an index. You can, at least temporarily, make the physical order in the table the same as the order in an index through clustering.
INFORMIX-4GL orders, or clusters, the physical data in a table when you create a new index by executing a variant of the CREATE INDEX statement or when you execute the new ALTER INDEX statement for an existing index. Since users who have access to the table can add additional rows or update the information in existing rows, a table that you cluster according to an index does not stay that way. Over time, you can expect the benefit of an earlier clustering to disappear and you may want to cluster the table again using an ALTER INDEX TO CLUSTER statement.

Since a table can have only one physical order, you can have only one clustered index on a table at any given time. You can change the physical order to reflect a different index by executing two ALTER INDEX statements: 1. Execute an ALTER INDEX TO NOT CLUSTER statement to release the cluster attribute from the first index. 2. Execute an ALTER INDEX TO CLUSTER statement to attach the cluster attribute to the second index. You cannot execute the ALTER INDEX or CREATE INDEX statements on a view.

NULL Values
The basic purpose of introducing NULL values in a database is to indicate when no value has been assigned to a particular column in a particular row of a table. Your reasons for not having assigned a value could include not knowing the correct value, or that no value yet exists. The NULL can also indicate that no value is appropriate for a given column because of the values that were entered into other columns. As an example, consider entering data for a bank customer who is requesting a loan. If the customer, Mr. Farthing, is not employed, the employer column in the client table will have no entry for this customer. This CHAR column will have the value NULL. The hire_date column is meaningless if Mr. Farthing is not employed. There is no appropriate date to enter; the value is NULL.

Using SQL

3-53

Default Values

Default Values
In INFORMIX-4GL, the default value for a column is NULL. INFORMIX-4GL makes a distinction for number values between zero and NULL, and for character values between blanks and NULL. You do not need to know how INFORMIX-4GL implements the value NULL to make use of it. By definition, type SERIAL columns can never contain the NULL value. Columns of type SERIAL always contain integers greater than or equal to one. You can insist that a column of any type not have NULL values by using the NOT NULL clause in the CREATE TABLE statement. INFORMIX-4GL will prevent a NULL from being entered into any column that is declared NOT NULL. You cannot, however, use a NOT NULL clause in an ALTER TABLE statement when you add a new column. The reason is that INFORMIX-4GL enters a NULL value into that column for all rows that already exist. A column for which you create a unique index can have, at most, one NULL value. Note for Users with an SQL Version 1 Database: When no value is provided for a column entry in a row of a table in an SQL Version 1 database, INFORMIX-4GL enters a blank for type CHAR columns, zeros for number columns, and a very large negative value for type DATE columns. Since zero could well be an acceptable value for a number column (for example, the value for a type MONEY column), there is no way to distinguish an unknown value from zero. To incorporate an existing SQL Version 1 database into INFORMIX-4GL programs, you must execute the dbupdate utility described in Appendix E. (The discussion of the dbupdate utility describes how you can avoid using NULL values.)

The NULL in Expressions
If any value that participates in an arithmetic expression is NULL, the value of the entire expression is NULL. For example, consider the following query:
SELECT order_num, ship_charge/ship_weight FROM orders WHERE order_num = 1023

If ship_weight is NULL because the order with number 1023 is new and the shipping charge has not yet been determined, the value returned for ship_charge/ship_weight will also be NULL.

3-54

Using SQL

The NULL in Boolean Expressions

The situation is different when you use one of the aggregate functions. (See Chapter 7 for a description of the aggregate functions.) COUNT(*) counts all rows, even if the value of every column in the row is NULL. COUNT (DISTINCT column-name), AVG, SUM, MAX, and MIN ignore rows with NULL values for the column in their argument and return the appropriate value based on the rest of the rows. If, however, a column contains only NULL values, then COUNT (DISTINCT column-name) returns zero, and the other four aggregate functions return NULL for that column.

The NULL in Boolean Expressions
To incorporate NULL values into Boolean expressions, it is necessary to enlarge the number of truth values from simply TRUE and FALSE to include UNKNOWN. If one of the expressions of a Boolean expression is NULL, the truth value of the Boolean expression is UNKNOWN. For example, the Boolean expression,
ship_charge/ship_weight < 5.0

has the truth value UNKNOWN for the order in the previous example. If you combine Boolean expressions using the operators AND, OR, and NOT, the following tables give the resulting truth value (where T corresponds to TRUE, F to FALSE, and ? to UNKNOWN). AND T F ?
Figure 3-1

T T F ?

F F F F

? ? F ?

OR T F ?

T T T T

F T F ?

? T ? ?

NOT T F ? F T ?

Combining Boolean Expressions

The NULL in WHERE Clauses
If the Boolean expression in a WHERE clause evaluates to UNKNOWN for a particular row, INFORMIX-4GL treats the search condition as not satisfied and does not select or modify that row. Consider this clause
WHERE ship_charge/ship_weight < 5 AND order_num = 1023

Using SQL

3-55

The NULL in ORDER BY Clauses

The row where order_num = 1023 is the row where ship_weight is NULL. Since ship_weight is NULL, ship_charge/ship_weight is also NULL, and the truth value of ship_charge/ship_weight < 5 is UNKNOWN. Since order_num = 1023 is TRUE, the preceding AND truth table states that the truth value of the entire search condition is UNKNOWN. Consequently, that row will not be chosen. If the search condition had used an OR in place of the AND, the search condition would be TRUE. You can select (or reject) rows containing NULL values with a new type of search condition:
column IS [ NOT ] NULL

You must use the keyword IS. It is not permitted to write the condition as follows:
column = NULL column != NULL (Incorrect) (Incorrect)

If you perform a join between two tables using the WHERE clause,
WHERE column1 = column2 INFORMIX-4GL will not select the rows where either column1 or column2 is NULL. In particular, no row will be returned if both column1 and column2 are NULL. This is merely a special case of the more general rule that Boolean expressions containing NULL values have an UNKNOWN truth value.

Similarly, if a subquery returns a single NULL value, the search condition evaluates to UNKNOWN.

The NULL in ORDER BY Clauses
For the purpose of sorting rows using the ORDER BY clause, the NULL value is treated as being less than a non-NULL value. When the ordering is ascending ( ASC ), the NULL values come first; when the ordering is descending ( DESC ), the NULL values come last.

The NULL in GROUP BY Clauses
When you refer to a column in a GROUP BY clause, INFORMIX-4GL treats all rows containing a NULL value in the column as a single group. NULL values are considered identical when evaluated within a GROUP BY clause.

3-56

Using SQL

The NULL Keyword in INSERT and UPDATE Statements

The NULL Keyword in INSERT and UPDATE Statements
When you execute the INSERT statement, INFORMIX-4GL will insert the NULL value into all columns for which you do not provide a value, or for all columns not listed explicitly. Since the value-list of the INSERT statement must be the same length as the column-list, you can use the keyword NULL to indicate that a column in column-list should be assigned a NULL value.
INSERT INTO orders (order_num, order_date, customer_num) VALUES (0, NULL, 123)

All other columns in the orders table will be filled with NULL values. Similarly, you can use the NULL keyword to modify a column value when using the UPDATE statement. For a customer whose previous address required two address lines, but now requires only one, you would use the following entry:
UPDATE customer SET address1 = "123 New Street", address2 = NULL, city = "Palo Alto", zipcode = "94303" WHERE customer_num = 134

Views
Views are constructs on a database that allow you to do the following tasks:

• Provide different users with different windows (called ‘‘views’’) on the
data in the database. A single view can involve columns from different tables, or can show values that are functions of the values from the columns. A view has a name and looks to a user as if it were a table. The user can query a view, for example, using the same syntax as though the view were a table in the database.

• Limit access to sensitive data by allowing users to see only aggregate
information. With the GRANT and REVOKE statements, you can prevent a user from seeing any salary data in a personnel table. With a view, you can allow the user to see average salaries in various groups, but still protect the individual salary data.

• Permit users to update, insert, and to delete data in the database as
though the data were organized as it appears in a view. You can also examine through a view the changes made in a real table of the database.

Using SQL

3-57

Creating and Deleting Views

Views are therefore dynamic windows into the database and are not static snapshots. They differ in this respect from a temporary table created by the INTO TEMP clause of a SELECT statement or the CREATE TEMP TABLE statement. Such temporary tables show you only the state of the database when the temporary table was created. Although views appear to be tables in the database, they differ in several important ways. You cannot create an index on a view. Under certain conditions, you cannot update or modify the data perceived through a view. An obvious case occurs when the ‘‘column’’ seen in a view is really an expression generated from actual database tables. Generally speaking, there is no way to determine the appropriate change in the underlying columns involved in such an expression if you want to change the value of the ‘‘column.’’ The next sections describe how to create and delete views, how to query the database through views, how to modify the database through a view, and how to set up privileges for a view.

Creating and Deleting Views
You must use the CREATE VIEW statement to create a view. (See Chapter 7 for complete information about the CREATE VIEW statement.) A view is determined by a SELECT statement that returns the ‘‘table’’ that defines the view. You cannot use the UNION operator in the definition of a view. (See Chapter 7 for the definition of the UNION operator.) The SELECT statement is stored in the sysviews system catalog. When you subsequently refer to a view in another statement, INFORMIX-4GL performs the defining SELECT statement in executing the new statement. You can use the same column names as in the underlying table for the view or you can assign new names. When a column in a view is the evaluation of an expression or is not unique (because, for example, you have included all the columns of a join, including the columns that define the join), you must supply new names. These column names are stored in syscolumns with the column names of regular tables. You can delete a view by executing the DROP VIEW statement. When you drop a view, you also drop all views that were defined in terms of that view.

Querying Through Views
You can make queries involving views exactly as though they were tables in the database. If possible, 4GL first combines the view-defining SELECT statement with the query to create a new SELECT statement and then executes the
3-58 Using SQL

Modifying Through Views

new statement. Otherwise, it creates the view as a temporary table and applies the query to the table. 4GL can detect errors during either of these phases.

Modifying Through Views
In addition to querying through views, you can use the INSERT, UPDATE, and DELETE statements with views. INFORMIX-4GL combines the view-defining SELECT statement with the view-referring statement and then executes it. The following restrictions apply when modifying tables through a view:

• You cannot modify the database through a view if the view definition
involves joins, the GROUP BY clause, the DISTINCT keyword, or an aggregate function. If any of these features appears in the view definition, the creator of the view cannot execute INSERT, DELETE, or UPDATE statements on the view. You can define a view, however, using a subquery that refers to another table. This approach can often circumvent the restriction on joins. (See the section “Data Constraints Using Views,” later in this chapter.)

• A view column can be UPDATEd only if it is derived directly from a database table and not as a result of an expression. Expression-derived columns are called ‘‘virtual’’ columns. You cannot INSERT rows through a view that contains virtual columns, although you can DELETE a row that contains a virtual column.

• You cannot execute the ALTER TABLE, CREATE INDEX, ALTER INDEX, or
UPDATE STATISTICS statements on a view. You do, however, receive the benefit of existing indexes on the underlying tables.

You can use an INSERT statement on a view that shows only a portion of an underlying table. When you do so, the unmentioned columns of the underlying table will receive NULL values. If one of the unmentioned columns does not permit NULL values, INFORMIX-4GL will not permit you to INSERT to the view. If you drop a column from a table underlying a view and you have defined the view in terms of that column, INFORMIX-4GL issues an error if you subsequently refer to the view (other than with the DROP VIEW statement). Unless you create the view with a WITH CHECK OPTION clause, it is possible to INSERT or UPDATE data through a view that does not satisfy the limitations on the view. A row inserted or updated in this manner is no longer accessible through the view. For example, a view could be created that allows the user access only to customers from Palo Alto. If, when using the view, the user creates a new row with a customer from Menlo Park, the user cannot
Using SQL 3-59

Privileges with Views

select the row through the view. If the city column on an existing row is updated to Menlo Park, the row disappears from the view. The WITH CHECK OPTION clause in the CREATE VIEW statement causes INFORMIX-4GL to reject an UPDATE or INSERT that violates the restrictions of the view. You must be careful when you UPDATE a table through a view that can contain duplicate rows. Duplicate rows can occur in a view even if the underlying table has unique rows. If a view is defined on the items table and contains only the columns order_num and total_price, the view contains duplicate rows if two items from the same order have the same total price. If you put the cursor on one of the rows where total_price = $1234.56 and update the total_price to $1250.00 through the view, you have no way of knowing which item you have increased.

Privileges with Views
When you create a view, you receive the same privileges that you had on the underlying tables. If you have these privileges with the GRANT OPTION, you can grant privileges on your view to other users. (See Chapter 7.) If the view is built on more than one table, you can have only the SELECT privilege, since multi-table views do not permit you to INSERT, DELETE, or UPDATE. You must have the SELECT privilege on all of the columns from which a multi-table view is derived to have the SELECT privilege on the entire view. If, as a result of these restrictions, you have no privileges on a view, the CREATE VIEW statement returns an error code.

Data Constraints Using Views
The purpose of data constraints is to ensure that all data entered into the database satisfies pre-assigned limitations. Through a form in INFORMIX-4GL, data entry can be controlled with the INCLUDE attribute that lists values and ranges of values permitted for a column. The values entered into the syscolval table in the include column serve a similar purpose. (See Chapter 4.) In both of these cases, however, the list of allowed values is static and is dependent only on the designated column. It is often desirable to define allowed value ranges dynamically, based on the values in other columns or even in other tables. The existence of views and, specifically, the WITH CHECK OPTION clause permits the DBA to control the entry of data into the database. This is most easily demonstrated with an example taken from the stores database.

3-60

Using SQL

Outer Joins

Suppose you want to ensure that no item

• Has a value of more than $20,000 • Is for stock that does not exist
The first step is to create the following view:
CREATE VIEW safe_items AS SELECT * FROM items WHERE total_price < 20000 AND EXISTS (SELECT stock_num, manu_code FROM stock WHERE stock.stock_num = items.stock_num AND stock.manu_code = items.manu_code) WITH CHECK OPTION

If you do all data entry and data modification through the safe_items view, 4GL will reject all data that does not meet the requirements of the WHERE clause. Because of the dynamic nature of views, the view will only contain rows corresponding to current stock items if you change the stock table by adding rows corresponding to new stock items or deleting old ones. By extending the WHERE clause, this example can be expanded to cover very general data-constraint needs.

Outer Joins
An outer join between two tables treats the two tables unsymmetrically. One of the tables is dominant (often referred to as ‘‘preserved’’), and the other table is subservient. If the subservient table has no rows satisfying the join condition, the outer join attaches a row of NULL values to the row of the dominant table before projecting the desired columns. To illustrate, let a be a column from tab1 and b a column in tab2. Further, let the values in the two tables be as shown in the following display:
tab1.a 2 3 5 tab2.b 4 2 6 5

Using SQL

3-61

Table Access by ROWID

INFORMIX-4GL syntax requires that the subservient table in an outer join be preceded by the keyword OUTER in the FROM clause. The following SELECT

statement contains an outer join between tab1 (the dominant table) and tab2 (the subservient table):
SELECT a, b FROM tab1, OUTER tab2 WHERE a = b

The resulting table has the following three rows:
a 2 3 5 b 2 5

Every value for a is present, and only those values for b that correspond to a value in a are present. When there is no value in column b that satisfies the join condition, a NULL value (shown here as -) is substituted. A WHERE clause is required in the case of outer joins and must set a condition between the two tables. See Appendix G for more information about outer joins.

Table Access by ROWID
You can use the keyword ROWID in INFORMIX-4GL statements to refer to the internal record number associated with a row in a database table. The ROWID can be thought of as a hidden column in every table. When you refer to table.*, the implied list of columns does not include ROWID. On the other hand, you can use the syntax
SELECT ROWID , * FROM table

to get the ROWID value for each row. You can also determine the ROWID of the last row that INFORMIX-4GL dealt with by examining the SQLCA record. See the next section for how to do this. You can also use ROWID in WHERE clauses to select rows based on their internal record number. This feature is useful when there is no other unique column in a table. If a row is deleted from the table, its ROWID can be assigned to a new row. You should not attribute chronological or other significance to the sequential values of ROWID.

3-62

Using SQL

SQLCA Record

SQLCA Record
Proper database management requires that all logical sequences of statements that modify the database continue successfully to completion. If, for example, you UPDATE a customer account to show a reduction of $100 in the payable balance and the next step, to UPDATE the cash balance, fails for some reason, your books will be out of balance. It is prudent to check that every SQL statement executes as you anticipated.
INFORMIX-4GL provides two ways to do this: the global variable status that indicates errors both from form-related statements and SQL statements; and a global record SQLCA that allows you to test the success of SQL statements. The status variable provides the primary information, and SQLCA provides additional information. INFORMIX-4GL returns a result code into the SQLCA record after executing every SQL statement except DECLARE. This record is shown here: DEFINE SQLCA SQLCODE SQLERRM SQLERRP SQLERRD SQLAWARN END RECORD SQLCODE RECORD INTEGER, CHAR(71), CHAR(8), ARRAY [6] CHAR (8)

OF

INTEGER ,

indicates the result of executing an SQL statement. It is set to zero for a successful execution of most statements and to NOTFOUND ( = 100 ) for a successfully executed query that returns zero rows or for a FETCH that seeks beyond the end of an active set. is negative for an unsuccessful execution.
INFORMIX-4GL sets the global variable status equal to SQLCODE after each SQL statement. See “Error Messages” after the

SQLCODE

appendixes for the error codes.
SQLERRM SQLERRP SQLERRD

is not used at this time. is not used at this time. an array of six variables of type INTEGER
SQLERRD[1] SQLERRD[2] SQLERRD[3] SQLERRD[4]

is not used at this time. is the SERIAL value returned or ISAM error code. is the number of rows processed. is the estimated CPU cost for query.
Using SQL 3-63

SQLCA Record

SQLERRD[5] SQLERRD[6]

is the offset of error into the SQL statement. is the ROWID of last row.

SQLAWARN is a character string of length eight whose individual characters

signal various warning conditions (as opposed to errors) following the execution of an SQL statement. The characters are blank if no problems were detected.
SQLAWARN[1] is set to W if one or more of the other warning characters has been set to W. If SQLAWARN[1]

is blank, you do not have to check the remaining warning characters.
SQLAWARN[2] is set to W if one or more data items was truncated to fit into a CHAR program variable, or if a DATABASE statement selected a database

with transactions.
SQLAWARN[3] is set to W if an aggregate function ( SUM, AVG, MAX, or MIN ) encountered a NULL value in its evaluation, or if a DATABASE statement selected a MODE ANSI database. SQLAWARN[4] is set to W if a DATABASE statement selected an INFORMIX-OnLine database, or when the number of items in the select-list of a SELECT

clause is not the same as the number of program variables in the INTO clause. The number of values returned by INFORMIX-4GL is the smaller of these two numbers.
SQLAWARN[5] is set to W if float-to-decimal conversion is

used.
SQLAWARN[6] is set to W when your program executes an INFORMIX-4GL extension to ANSI standard syntax, and the DBANSIWARN environment

variable is set.
SQLAWARN[7] is not used at present. SQLAWARN[8] is not used at present.

3-64

Using SQL

TODAY, CURRENT, and USER Functions

TODAY, CURRENT, and USER Functions
INFORMIX-4GL provides functions to allow you to include the date, the date and time of day, and the login name of the current user in an SQL statement. TODAY returns the system date. CURRENT returns the system date and time. USER returns a string containing the login account name of the current user.

You can use these functions in SQL statements wherever you can use a constant of a similar data type. TODAY returns a DATE, CURRENT a DATETIME, and USER a CHAR value. You can also use CURRENT and TODAY (but not USER) in 4GL statements. For example, if you wish to retrieve the rows that you have inserted into a table, you must define a CHAR column to contain the USER name. When you insert new rows into the table, use the USER function as follows:
INSERT INTO table VALUES ( . . . , USER , . . . )

With a SELECT statement, you can retrieve the rows that you entered:
SELECT * FROM table WHERE user_col = USER

(See the section“Cursor Management,” earlier in this chapter, for a discussion on using the SELECT statement to return multiple rows.) Use the TODAY function in the same way. You can insert the system date into a table with the following statement:
INSERT INTO table VALUES ( . . . , TODAY , . . . )

The next statement retrieves all rows with the current date from table:
SELECT * FROM table WHERE date_col = TODAY

You can use CURRENT to insert the system date and time:
INSERT INTO table VALUES ( . . . , CURRENT , . . . )

The next query selects rows whose DATETIME value is within a range from the beginning of 1989 to the current instant.
SELECT * FROM table WHERE dt_col BETWEEN "1989-1-1 00:00:00" AND CURRENT

See the section “Built-in Functions” in Chapter 2 for more information about the TODAY and CURRENT functions.

Using SQL

3-65

TODAY, CURRENT, and USER Functions

3-66

Using SQL

Chapter

Form Building and Compiling
Chapter Overview 3 Structure of a Form Specification File 4 DATABASE Section 7 SCREEN Section 9 Textual Information 11 Display Fields 11 Graphics Characters in Forms 13 TABLES Section 15 ATTRIBUTES Section 17 Fields Linked to Database Columns Form-Only Fields 19 Multiple-Line Fields 21 Multiple-Column Fields 22 Attributes Syntax 23 AUTONEXT 24 COLOR 26 COMMENTS 28 DEFAULT 30 DISPLAY LIKE 32 DOWNSHIFT 33 FORMAT 34 INCLUDE 36 NOENTRY 38 PICTURE 39 REQUIRED 41 REVERSE 43 UPSHIFT 44 VALIDATE LIKE 46 VERIFY 47

4
18

WORDWRAP 48 INSTRUCTIONS Section 52 Field Delimiters 53 Screen Records 55 Screen Arrays 56 Default Screen Attributes 57 The upscol Tables in a MODE ANSI Database

60

Creating and Compiling a Form 61 Through the Programmer’s Environment 62 Through the Operating System 63 Using PERFORM Forms in INFORMIX-4GL 64

4-2

Form Building and Compiling

Chapter Overview
A screen form is a terminal screen display that can support input or output tasks within a 4GL application program. You can use screen forms in conjunction with screen interaction and data manipulation statements of INFORMIX-4GL to enter, retrieve, modify, or delete data. Before you can use a customized screen form in your INFORMIX-4GL program, you must create a form specification file and use FORM4GL to compile this file. The form specification file is an ASCII file that contains the screen format and the instructions to INFORMIX-4GL about how to display the data. The first and longest section of this chapter, “Structure of a Form Specification File,” describes the function and syntax of each of the required and optional components of a 4GL form specification file. Another part of this chapter, “Default Screen Attributes,” describes the syscolval and syscolatt tables into which you can insert default attributes, formats, and values for screen fields of 4GL applications. The section “Creating and Compiling a Form” describes how to use FORM4GL to compile form files for use in INFORMIX-4GL programs. The last section, “Using PERFORM Forms in INFORMIX-4GL” describes what happens when an INFORMIX-4GL program uses screen forms designed for PERFORM, the screen transaction program of INFORMIX-SQL. Note: The FORM4GL syntax for forms that you design to work with INFORMIX-4GL is different in several significant ways from the syntax of PERFORM. You can use PERFORM forms with INFORMIX-4GL, but you must recompile them using FORM4GL. In addition, not all of the PERFORM features are operative.

Form Building and Compiling

4-3

Structure of a Form Specification File

Structure of a Form Specification File
An INFORMIX-4GL form specification file consists of three required sections (DATABASE, SCREEN, and ATTRIBUTES) and can also include two optional sections (TABLES and INSTRUCTIONS). If present, these sections must appear in the following order:

• •

DATABASE Section: Each form specification file must begin with a DATABASE section identifying the database (if any) on which you want to

base the form.
SCREEN Section: The SCREEN section appears next, showing the exact layout of the form as you want it to appear on the screen. You must specify the position of the screen fields for data entry and display, and any additional text or graphic characters. TABLES Section: A TABLES section must follow the SCREEN section if you define any field with the name of a column in a database table. The TABLES section identifies all the tables whose columns are associated with screen fields in the ATTRIBUTES or INSTRUCTIONS sections, and defines aliases for any table names or synonyms that require an owner qualifier. ATTRIBUTES Section: The ATTRIBUTES section describes each field on

the form and assigns names to fields. The field specifications can include, for example, appearance, acceptable input values, on-screen comments, and default values.

INSTRUCTIONS Section: The INSTRUCTIONS section is optional. It can

specify non-default field delimiters and can define screen records and screen arrays. Each section must begin with the keyword for which it is named. After you create a form specification file, you use the FORM4GL utility to compile it. Your INFORMIX-4GL application can then use program variables to transfer information between a database and the fields of the screen form, as is illustrated by the examples that appear in Chapters 7, 11, 12, and 13 of the INFORMIX-4GL User Guide.

4-4

Form Building and Compiling

Structure of a Form Specification File

A FORM4GL form specification file has this structure:
DATABASE { database-name | FORMONLY } [ WITHOUT NULL INPUT ] SCREEN [ SIZE lines [ BY cols ] ] { [text] [ [field-tag] ] [graphics-char] ... } [ END ] [ TABLES [ tab-alias = [ owner. ] table ] ... [ END ] ] ATTRIBUTES

field-tag = { table.column

| FORMONLY. field-name [ TYPE [ data-type [ NOT NULL ] | LIKE table.column ] ] } [ , attribute-list ] [ = . . . ] [ ; ] [ = . . . ] ;

... [ END ] [ INSTRUCTIONS [ DELIMITERS "ab" ] [ SCREEN RECORD record-name [ [ n ] ] ( { table.* | table.column1 THRU table.column2 | table.column } [ , . . . ] ) ...] [ END ] ]

This summary includes three exceptions to the usual syntax notation of this manual. The following are literal characters to be entered in your file, rather than conventional symbols to mark optional terms:

• the set of braces ( { } ) in the SCREEN section • the inner brackets ( [ ] ) around field-tag in the SCREEN section • the inner brackets ( [ ] ) around n in the INSTRUCTIONS section
The next five sections of this chapter identify the keywords and terms listed previously, and describe their syntax in detail.

Form Building and Compiling

4-5

Structure of a Form Specification File

Example
Figure 4-1 illustrates the overall structure of form specification files:
DATABASE stores SCREEN { -------------------------------------------------------------------------CUSTOMER INFORMATION: Customer Number: [c1 ] Telephone: [c10 ] ... SHIPPING INFORMATION: Customer P.O.: [o20 Ship Date: [o21 } TABLES customer orders items manufact ATTRIBUTES c1 = customer.customer_num = orders.customer_num; ... c10 = customer.phone, PICTURE = "###-###-####x#####"; ... o20 = orders.po_num; o21 = orders.ship_date; o22 = orders.paid_date; INSTRUCTIONS SCREEN RECORD sc_order[5] (orders.order_date THRU orders.paid_date)

] ] Date Paid: [o22 ]

Figure 4-1

Sections of a Form Specification File

In this example, the screen form will display columns from several tables in the stores database. The file is for a default physical screen size (24 lines of 80 characters) and includes all five of the required and optional sections that are described in the pages that follow. This example is incomplete, since it omits portions of the SCREEN and ATTRIBUTES sections that describe some of the screen fields. The ellipsis notation ( . . . ) in those sections is a typographic device to simplify this illustration.

4-6

Form Building and Compiling

DATABASE Section

DATABASE Section
Overview
The DATABASE section of a form specification file identifies the database (if any) with which the form is designed to work. You must include this section, even if your screen form does not refer to the tables of any database. The DATABASE section has this structure.

Syntax
DATABASE { database-name | FORMONLY } [WITHOUT NULL INPUT]

Explanation
DATABASE

is a required keyword to mark the beginning of the DATABASE section of a form specification file. is the name of a database that contains columns used to define display fields of the form. are keywords to indicate that database-name does not support NULL values. is a keyword to indicate that the screen form is not associated with any database.

database-name
WITHOUT NULL INPUT FORMONLY

Notes
1. You should use the WITHOUT NULL INPUT option only if you have elected to create and work with a database that does not have NULL values. (See the description of dbupdate in Appendix E for the other required steps.) For fields that have no other defaults, this option causes INFORMIX-4GL to display zeros as default values for number and INTERVAL fields, and blanks for character fields. The default DATE value is 12/31/1899, and the default for DATETIME is 1899-12-31 23:59:59.99999. 2. It is possible to create a form that is not related to a database. To do so, specify FORMONLY after the DATABASE keyword, and omit the TABLES section of the form specification file. Use the table name formonly in the ATTRIBUTES section in naming fields that are not linked to specific columns of a database.
Form Building and Compiling 4-7

DATABASE Section

Examples
The following DATABASE section specifies that any columns referenced in the TABLES section are in the stores demonstration database:
database stores

The next example of a DATABASE section specifies that the screen form is not associated with any database:
database formonly

4-8

Form Building and Compiling

SCREEN Section

SCREEN Section
Overview
The SCREEN section of the form specification file specifies the vertical and horizontal dimensions of the physical screen, and the position of display fields and other information that will appear on the screen form. This section is required. It has the following syntax:

Syntax
SCREEN [ SIZE lines [ BY cols ] ] { screen-layout } [ END ]

Explanation
SCREEN SIZE

is a required keyword to mark the beginning of the SCREEN section. is an optional keyword to specify the vertical and horizontal dimensions of the terminal screen. is an integer that specifies the total number of lines of characters (measured vertically) that the terminal screen can display. The default is 24 lines. is an optional keyword to specify how many characters (measured horizontally) a line can display. is an integer that specifies the width of the screen. The default is the maximum number of characters in any line of the screen-layout. is the group of display fields and optional text and graphics characters that define a screen form. The braces ( { } ) are required symbols to indicate the beginning and end of the screen-layout, and do not represent a choice among required options. is an optional keyword to mark the end of the SCREEN section.

lines

BY

cols

{ screen-layout }

END

Form Building and Compiling

4-9

SCREEN Section

Notes
1. If you omit the SIZE keyword, lines defaults to 24, and cols defaults to the maximum number of characters in any line of your screen-layout. If you specify a default form at the Programmer’s Environment, as described near the end of this chapter, these SIZE defaults appear explicitly in the file. 2. Your form4gl command line can override either or both of the lines or cols dimensions of the SCREEN section by specifying: form4gl -l lines -c cols form-name Here lines and cols are defined as above, and form-name is the filename (without the .per extension) of a form specification file. 3. Specify lines as the total screen height. Four lines are reserved for the system, so no more than ( lines - 4 ) can display data. 4. If ( lines - 4 ) is less than the number of lines in the screen-layout, FORM4GL splits your form into a new page after every (lines - 4) lines. INFORMIX-4GL does not support multiple-page forms, so any lines beyond the first page will overlay the last line of the first page if your screen-layout is too large for your screen. (Create several form specification files if you need to display more data than can fit on one form.) 5. If the SIZE clause or command line specify dimensions too small for the screen-layout, FORM4GL issues a compile-time warning, but still produces the compiled form that your file specified. 6. The screen-layout must be enclosed in braces ( { } ). It consists of display fields and (optionally) textual information and graphics characters. Display fields must be indicated by brackets ( [ ] ) that define the field length and the position within a line of the form, and by field tag labels within the field. 7. Do not use braces as comment indicators in the screen-layout. 8. As in the other sections of a form specification file, the keyword END is not required, but it is recognized by FORM4GL to provide compatibility with earlier Informix products.

4-10

Form Building and Compiling

SCREEN Section

Example
This figure schematically illustrates the structure of a SCREEN section. Here the SCREEN SIZE dimensions specify a physical screen that can display up to 35 lines of data, with up to 80 characters in each line. (Four of the 39 lines specified here are reserved for the system.)
SCREEN SIZE 39 BY 80 { . . .

Text, display fields, and graphic characters
. . . } [ END ]

Screen layout

Textual Information
A screen layout can specify strings of ASCII characters that appear on the screen form. These characters can label the form and its fields, or otherwise improve the display. Except for the displacements described later in ‘‘Graphics Characters in Forms,’’ position in the screen layout determines where text appears on the screen. Text cannot overlap display fields, but the PICTURE attribute (described in “Attributes Syntax” later in this chapter) can specify literal characters within CHAR fields.

Display Fields
You can indicate where data will be displayed on the screen by using brackets ( [ ] ) to delimit fields in the screen layout. You must label each field with an associated field tag to identify the field.

Syntax
[fieldtag ]

Explanation
[ ] are delimiters for a field. The width of the field is the number of characters that can be placed between the brackets. (The brackets are required in this context, and do not signify an optional syntax.) is the field tag that labels the display field.
Form Building and Compiling 4-11

fieldtag

SCREEN Section

Notes
1. Each field must have a field tag, enclosed within brackets. 2. The field tag is from 1 to 50 characters long. It must fit within the brackets. The first character must be a letter. The rest of the field tag can include letters, numbers, and underscores ( _ ). 3. Field tags are labels; they are not the same as field names. The ATTRIBUTES section links each field tag to a field name. 4. The same field tag can be used at more than one position in the SCREEN section of the form specification, if you want the same information to appear in more than one screen field, or if you define a multiple-line field, or a screen array. (Multiple-line fields and screen arrays are described later in this chapter.) 5. The case of a field tag is ignored (so a1 and A1 are the same). 6. You can give single-character fields the tags a through z (so a form can include no more than 26 single-character fields.) 7. In a default form specification file, the widths of all fields are determined by the data type of the corresponding columns in the database tables. (See “Creating and Compiling a Form” for more information about default form specification files.) 8. If you create your own form, you normally should set the width of each display field in the SCREEN section to be equal to the width of the program variable or column to which it corresponds. 9. Fields corresponding to number columns should be large enough to contain the largest number that you might display. If the field is too small to display an assigned number, INFORMIX-4GL fills the field with asterisks ( * ) to indicate the overflow. 10. Fields intended to display character data can be shorter than the defined column length. INFORMIX-4GL fills a field from the left, and truncates from the right any character string that is longer than the field to which it is assigned. Through subscripting, you can assign portions of a character column to one or more fields. (See the “ATTRIBUTES Section” later in this chapter.) 11. If you edit and modify the default form specification file or create a new file, you can verify that the field widths match the width requirements of the corresponding CHAR columns by using the -v option of FORM4GL. At the system prompt, enter: form4gl -v form-name
FORM4GL reports any discrepancies in the file form-name.err. 4-12 Form Building and Compiling

SCREEN Section

12. The “INSTRUCTIONS Section” later in this chapter describes an optional delimiter that can be used to separate consecutive display fields in a screen layout.

Example
The SCREEN section listed below appears in the orderform.per form specification file in the INFORMIX-4GL demonstration application. This uses default screen dimensions (24 by 80). Notice the use of textual information for field labels, a screen title, and ornamental lines. (The “INSTRUCTIONS Section” later in this chapter describes how repeated field tags are used in forms that define screen arrays.)
SCREEN { ------------------------------------------------------------------------------ORDER FORM ------------------------------------------------------------------------------Customer Number:[f000 ] Contact Name:[f001 ][f002 ] Company Name:[f003 ] Address:[f004 ][f005 ] City:[f006 ] State:[a0] Zip Code:[f007 ] Telephone:[f008 ] ------------------------------------------------------------------------------Order No:[f009 ] Order Date:[f010 ] Purchase Order No:[f011 ] Shipping Instructions:[f012 ] ------------------------------------------------------------------------------Item No. Stock No. Code Description Quantity Price Total [f013 ] [f014 ] [a1 ] [f015 ] [f016 ] [f017 ] [f018 ] [f013 ] [f014 ] [a1 ] [f015 ] [f016 ] [f017 ] [f018 ] [f013 ] [f014 ] [a1 ] [f015 ] [f016 ] [f017 ] [f018 ] [f013 ] [f014 ] [a1 ] [f015 ] [f016 ] [f017 ] [f018 ] Running Total including Tax and Shipping Charges:[f019 ] =============================================================================== } END

Graphics Characters in Forms
You can include graphics characters in the SCREEN section to place boxes and other rectangular shapes in a screen form. Use the following characters to indicate the borders of one or more boxes on the form:
Symbol

p q b d |

Purpose Use p to mark the upper-left corner. Use q to mark the upper-right corner. Use b to mark the lower-left corner. Use d to mark the lower-right corner. Use hyphens ( - ) to indicate horizontal line segments. Use vertical ( | ) bars to indicate vertical line segments. Form Building and Compiling 4-13

SCREEN Section

The meanings of these six special characters are derived from the gb or acsc specifications in the termcap or terminfo files, respectively. INFORMIX-4GL substitutes the corresponding graphics characters when you display the compiled form. Once the form has the desired configuration, use the \g string to indicate when to begin graphics mode and when to end graphics mode. Insert a \g string before the first p, q, d, b, hyphen, or vertical bar that represents a graphics character. To leave graphics mode, insert the string \g after the p, q, d, b, hyphen, or vertical bar. Do not insert a \g string into original white space of a screen layout. The backslash should displace the first graphics character in the line, and push the remaining characters to the right. The process of indicating graphics distorts the appearance of a screen layout in the SCREEN section, compared to the corresponding display of the screen form. You can include other graphics characters in a form specification file. The meaning, however, of a character other than the p, q, d, b, hyphen, and vertical bar is terminal-dependent. To use graphics characters, the system termcap or terminfo files must include entries for the following variables: termcap: gs ge gb terminfo: smacs rmacs acsc the escape sequence for entering graphics mode. the escape sequence for leaving graphics mode. the concatenated, ordered list of ASCII equivalents for the six graphics characters used to draw the border. the escape sequence for entering graphics mode. the escape sequence for leaving graphics mode. the concatenated, ordered list of ASCII equivalents for the six graphics characters used to draw the border.

See Appendix I, “Modifying termcap and terminfo,” and the manual that comes with your terminal for information about making changes to your termcap or terminfo files to support these graphics characters.

4-14

Form Building and Compiling

TABLES Section

TABLES Section
Overview
The third section of the form specification file lists all the tables that you reference elsewhere in the screen form. You do not need to display in the screen form every column of every table listed, but any table or view whose columns are referenced in the form must be included. In a MODE ANSI database, a form must qualify any table name with the owner prefix if the form will be run by users other than owner. If a prefix is needed, you must specify a simple alias for owner.table-name in the TABLES section to reference the table in other sections of the form specification file. The structure of the TABLES section is shown below:

Syntax
TABLES [tab-alias = [ owner.] ] table . . . [ END ]

Explanation
TABLES

is a keyword to begin the TABLES section. is the table alias in the form specification file. is the username of whoever created tabname. is the identifier or synonym of table in its database. is an optional keyword to end the TABLES section.

tab-alias owner table
END

Notes
1. If the DATABASE section specifies FORMONLY, no TABLES section is needed unless you give a field the VALIDATE LIKE or DISPLAY LIKE attribute in the ATTRIBUTES section, or type a field LIKE a database column. 2. Every table listed in the TABLES section must be part of the database that you specify in the DATABASE section. 3. Every database column referenced in the ATTRIBUTES section must be part of some table specified in the TABLES section.

Form Building and Compiling

4-15

TABLES Section

4. The table identifier is the name listed in the tabname column of the systables catalog, or else a synonym. You do not need to specify tab-alias, unless the form will be used in a MODE ANSI database by a user who did not create table. 5. Except to assign a tab-alias in the TABLES section, a form file cannot qualify table with an owner prefix. You must define a tab-alias to reference the owner of a table or synonym. (This alias can be the same identifier as table, for example stock can be the alias for tom.stock) 6. Statements in INFORMIX-4GL programs or in other sections of the form specification file can reference screen fields as column or as table. column, but they cannot specify owner. table. column. You cannot specify table. column as a field name if you define a different tab-alias for table. 7. INFORMIX-4GL allows you to specify up to 20 tables, but the actual limit on the number of tables and views in a form is machine-dependent. 8. The END keyword is not required.

Examples
The file orderform.per in Appendix A lists four tables:
TABLES customer orders items stock

The following TABLES section specifies aliases for two tables:
TABLES tab1 tab2 = = refdpt.booktab athdpt.balltab

Note: INFORMIX-OnLine supports additional functionality. Refer to the INFORMIX-OnLine Programmer’s Manual for more information.

4-16

Form Building and Compiling

ATTRIBUTES Section

ATTRIBUTES Section
Overview
The ATTRIBUTES section associates an identifier and a data type with every field in the SCREEN section. You can also describe the behavior and appearance of each field by using attributes to describe how INFORMIX-4GL should display the field, specify a default value, limit the values that can be entered, or set other parameters. Attributes are described later in this chapter, in the section“Attributes Syntax.”

Syntax
ATTRIBUTES field-tag = field-description ; ... [ END ]

Explanation
ATTRIBUTES

is a required keyword to mark the beginning of the ATTRIBUTES section. is a field tag specified in the SCREEN section. is an optional keyword to mark the end of the ATTRIBUTES section.

field-tag
END

field-description specifies a field name and optional attributes.

Notes
1. The ATTRIBUTES section must describe every field-tag from the SCREEN section. (Tags with more than one field-description are described later in ‘‘Multiple-Column Fields.’’) 2. The order in which you list the field tags determines the order of fields in the default screen records. (See the “INSTRUCTIONS Section” for more information about screen records.) 3. The equal ( = ) sign and the semicolon ( ; ) are required symbols. 4. A field not associated with any column is called a form-only field.

Form Building and Compiling

4-17

ATTRIBUTES Section

Fields Linked to Database Columns
You can specify two kinds of field descriptions: those that associate a field tag with the data type and default display attributes of a database column, and those that link field tags to form-only fields. Unless a screen field is form-only, its field-description must specify the identifier of some column in the database as the name of the field. Screen fields are associated with database columns only during the compilation of the form specification file. During the compilation process, FORM4GL examines two optional tables, syscolval and syscolatt, for default values of the attributes that you have associated with any columns of the database. (See the section “Default Screen Attributes” later in this chapter for a discussion of these tables.) After FORM4GL extracts these default attributes and identifies the data types from the system catalogs, the association between the fields and database columns is broken. INFORMIX-4GL programs must mediate between screen fields and database columns with program variables.

Syntax
field-tag = [ table.] column [ , attr-list ] ;

Explanation
field-tag table column is a field tag that identifies a field in the SCREEN section. is a table name or alias from the TABLES section. is the name of a column in table or, if you omit table, in some table listed in the TABLES section. This name can also appear in 4GL statements that reference the field. is one or more FORM4GL field attribute specifications, separated by commas.

attr-list

Notes
1. Although you must include an ATTRIBUTES section that names every field-tag, you are not required to specify any attributes. 2. You need to specify table only if column occurs in more than one table of the TABLES section. FORM4GL issues an error during compilation if there is ambiguity. Because you can refer to field names collectively through a screen record built upon all the fields related to a single table, your forms may be easier to work with if you specify table for each field.

4-18

Form Building and Compiling

ATTRIBUTES Section

(The ‘‘INSTRUCTIONS Section’’ provides more information about screen records.) 3. A screen field can display a portion of a character string by using subscripts in the column specification. Subscripts are comma-separated integers in square ( [ ] ) brackets to indicate starting and ending character positions within a string value.

Examples
The ATTRIBUTES section in the following file lists fields linked to columns in the customer table. The UPSHIFT and PICTURE attributes listed here are described later in this chapter.
DATABASE stores SCREEN { Customer Name:[f000 Address:[f002 City:[f004 Telephone:[f006 } TABLES customer

][f001 ] ][f003 ] ] State:[a0] Zip Code:[f005 ] ]

ATTRIBUTES f000 = customer.fname; f001 = customer.lname; f002 = customer.address1; f003 = customer.address2; f004 = customer.city; a0 = customer.state, UPSHIFT; f005 = customer.zipcode f006 = customer.phone, PICTURE = "###-###-#### XXXXX";

Form-Only Fields
Form-only fields are not associated with columns of any database. They can be used to enter or display the values of program variables. If the DATABASE section specifies FORMONLY, this is the only kind of field description that you can specify in the ATTRIBUTES section.

Syntax
fieldtag = FORMONLY. field-name [ TYPE [ data-type [ NOT NULL ] | LIKE [ table. ] column ] ] [ , attr-list ] ;

Form Building and Compiling

4-19

ATTRIBUTES Section

Explanation
field-tag
FORMONLY

is the field tag used in the SCREEN section. is a keyword indicating that the field does not correspond to a column of a table in the database. is an SQL identifier for the name of the field. is a keyword to specify an INFORMIX-4GL data type. is any one of the INFORMIX-4GL data types except SERIAL. (See the section “Database Data Types” in Chapter 3 for definitions of the data types.) is a keyword to associate the screen field with the data type specification of a database column. is a table alias, name, or synonym. is the name of a column in the database. are keywords to specify that, if you reference this field in an INFORMIX-4GL INPUT or INPUT ARRAY statement, the user must enter a value in the field. is a list of one or more FORM4GL display field attribute specifications, separated by commas. (See the section “Attributes Syntax” for a list of FORM4GL attributes.)

field-name
TYPE

data-type

LIKE

table column
NOT NULL

attr-list

Notes
1. You must specify a data-type only if you use the INCLUDE or DEFAULT attribute for this field. Otherwise, FORM4GL assumes the field is a CHAR type whose length is the width of the field. INFORMIX-4GL performs the necessary data conversion for the corresponding program variable during input or display. 2. When describing data-type, do not give a length to type CHAR, DECIMAL, or MONEY fields, since the length is determined by the display width in the SCREEN section. 3. If you specify one or more FORMONLY fields, INFORMIX-4GL behaves as if they formed a database table named formonly, with the field names as column names. 4. When the DATABASE section has the WITHOUT NULL INPUT clause, the NOT NULL keyword instructs INFORMIX-4GL to use zero (number types) or blanks (character types) as a default value for this field in INPUT or INPUT ARRAY statements. If you do not specify any type, INFORMIX-4GL treats the field as type CHAR.

4-20

Form Building and Compiling

ATTRIBUTES Section

Examples
The following form-only fields could be used in an order entry form to display information about items:
f020 = f021 = f022 = f023 = f024 = TYPE formonly.manu_name; formonly.description; formonly.unit_price; formonly.unit_descr; formonly.order_placed DATETIME YEAR TO HOUR NOT NULL, DEFAULT = CURRENT;

The demonstration application uses the following form-only field to store the running total price for the order as items are entered:
f019 = formonly.t_price;

Multiple-Line Fields
If you need to enter or display long character strings from program variables, you can specify multiple-line fields that occupy several lines. To create a multiple-line field, repeat the same field tag in different fields of the layout in the SCREEN section, typically on successive lines. You must also specify the WORDWRAP attribute for that field tag in the ATTRIBUTES section. During input and display, INFORMIX-4GL treats these fields as segments of a single field. The following example shows only the SCREEN and ATTRIBUTES sections of a form specification file that specifies a multiple-line field:
SCREEN SIZE 24 BY 80 { title: [title author: [author ] synopsis: [synopsis [synopsis [synopsis [synopsis [synopsis } . . . ATTRIBUTES title = booktab.title; author = booktab.author; synopsis = booktab.synopsis, WORDWRAP COMPRESS;

] ] ] ] ] ]

Since the screen field whose tag is synopsis appears in five physical segments in the screen layout and has the WORDWRAP attribute, it is a multiple-line field. Its value is composed of the physical segments taken in top-to-bottom, left-to-right order. The field should ordinarily be as long or longer than the column, so it can display all of the text. Users of your 4GL application pro-

Form Building and Compiling

4-21

ATTRIBUTES Section

gram may expect all segments to be the same size and laid out in vertical alignment, as in the example, but that is not required. Segments can be of different sizes, and distributed over the screen in any arrangement. In the description of the field in the last line of the ATTRIBUTES section, the keyword WORDWRAP enables a multiple-line editor. If you omit it, words cannot flow from segment to segment of the field, and users must move the cursor from field to field with Arrow keys or the RETURN key to edit values in the form. (See the description of the WORDWRAP attribute later in this chapter for more information about the multiline editor and about the COMPRESS keyword.)

Multiple-Column Fields
A screen form that contains information from several database tables can include screen fields that display data via program variables from two or more database columns. The database columns that you assign to the same field must have the same field size. Usually they also have the same data type. If they are character columns, they must have the same length. The following specification in the ATTRIBUTES section assigns two column names to a field tag, so that the names table1. column and table2. column both reference the same field: field-tag = table1.column = table2.column; You can also include one or more attribute lists in field descriptions when you assign several columns to the same field. The placement of attributes determines when they take effect. When INFORMIX-4GL executes an INPUT, INPUT ARRAY, DISPLAY, or DISPLAY ARRAY statement, the screen fields listed (explicitly or implicitly) in the 4GL statement are called active fields. If you want an attribute to apply regardless of which field name is active, place the attribute in an attr-list after the last field name: field-tag = table1.column = table2.column, attr-list; If you want different attributes to apply for each of the field names, place a semicolon ( ; ) after the attribute list for each field name: field-tag = table1.column, attr-list1; = table2.column, attr-list2; Here attr-list1 is effective when table1.column is active, and attr-list2 is effective only when table2.column is active. (The FORMAT and REVERSE attributes, described later in this chapter, always take effect if you include them in the description of a multiple-column field, regardless of their placement.)

4-22

Form Building and Compiling

ATTRIBUTES Section

Attributes Syntax
FORM4GL recognizes the following display field attributes: AUTONEXT COLOR COMMENTS DEFAULT DISPLAY LIKE DOWNSHIFT FORMAT INCLUDE NOENTRY PICTURE REQUIRED REVERSE UPSHIFT VALIDATE LIKE VERIFY WORDWRAP [ COMPRESS ]

Syntax for assigning each of these attributes is described in the sections that follow. For simplicity and clarity, these descriptions of the attributes that you can assign to a screen field use the following syntax format:
field-tag = [ table. ] column, attr ;

Here field-tag is a field tag that was specified in the SCREEN section, column or table.column is the name of a screen field (either linked to a database column or FORMONLY ), and attr specifies an attribute. This format is simplified by ignoring multiple-column fields, and by omitting terms that specify the data-type and NOT NULL keywords of a form-only field. Here is the complete syntax of a field description that assigns one or more attributes.

Syntax
field-tag = { [ table. ] column | FORMONLY. field-name [ TYPE [ data-type [ NOT NULL ] | LIKE [ table. ] column ] ] } , attr [ , attr ] [ = . . . ] [ ; ] [ = . . . ] ;

Refer to this complete syntax if you need to specify a form-only field or a multiple-column field. Note: INFORMIX-OnLine supports an additional attribute, PROGRAM. Refer to the INFORMIX-OnLine Programmer’s Manual for more information.

Form Building and Compiling

4-23

AUTONEXT

AUTONEXT
Overview
Use the AUTONEXT attribute to cause the cursor to advance automatically during input to the next field when the current field is full.

Syntax
field-tag = [ table. ] column, AUTONEXT;

Explanation
field-tag table.column
AUTONEXT

is the field tag used in the SCREEN section. is the name of a field (either related to a column or FORMONLY). is a keyword that tells INFORMIX-4GL to advance the cursor to the next field when the current field is full.

Notes
1. You specify the order of fields in each INPUT or INPUT ARRAY statement. 2. AUTONEXT is particularly useful with character fields in which the input data are of a standard length, such as numeric postal codes, or the abbreviations in the state table. It is also useful if a character field has a length of one, since only one keystroke is required to enter the data and to move to the next field. 3. If data entered in the field does not meet requirements of other attributes like INCLUDE or PICTURE, the cursor does not automatically move to the next field, but remains in the current field. 4. If the most recent OPTIONS statement specifies INPUT WRAP, the ‘‘next’’ field after the last field is the first field.

4-24

Form Building and Compiling

AUTONEXT

Example
The demonstration application uses the customer form to enter all the names and addresses of the customers. The following excerpt from the ATTRIBUTES section of the customer form uses the AUTONEXT attribute:
... a0 = customer.state, DEFAULT = "CA", AUTONEXT; f007 = customer.zipcode, AUTONEXT; f008 = customer.phone; ...

When two characters are entered into the customer.state field (thus filling the field), the cursor moves automatically to the beginning of the next field (the customer.zipcode field). When five characters are entered into the customer.zipcode field (filling this field), the cursor moves automatically to the beginning of the next field (the customer.phone field).

Form Building and Compiling

4-25

COLOR

COLOR
Overview
You can use the COLOR attribute to display field text in color on color monitors, or to specify other video attributes for field text.

Syntax
field-tag = [ table. ] column, COLOR = dispmode [ . . . ] [ WHERE condition ] ;

Explanation
field-tag table.column
COLOR =

is the field tag used in the SCREEN section. is the name of a field (either related to a database column or FORMONLY). is a keyword, followed by an equal ( = ) sign. is the name of a screen color or intensity. is a keyword to specify a Boolean expression. is a Boolean expression. If it is TRUE, text in the field is displayed with the dispmode attribute.

dispmode
WHERE

condition

Notes
1. The condition can be a Boolean expression of the following forms: expr [ NOT ] IN (expr [ , expr . . . ] ) expr [ NOT ] BETWEEN expr AND expr expr [ NOT ] LIKE expr [ ESCAPE "char"] expr [ NOT ] MATCHES expr [ ESCAPE "char"] bool-expr [ AND | OR ] bool-expr for relop a relational operator ( = <> != > >= <= < ); bool-expr a Boolean expression; and expr the current field-tag, a constant, or TODAY or CURRENT, arithmetic symbols, or the unary minus symbol: expr { + | - | * | / } expr - expr 2. In a condition, a field tag evaluates to the current value in the field. 3. If you do not specify a condition, the intensity and/or color in your dispmode list applies to the field.
( expr )

expr relop expr expr IS [ NOT ] NULL ( bool-expr ) NOT bool-expr

4-26

Form Building and Compiling

COLOR

4. If condition is FALSE, the field is displayed with default characteristics, rather than with the attribute specified by dispmode. (See “Default Screen Attributes” later in this chapter.) 5. The dispmode list can specify zero or one color name, and zero or more intensity names from these lists:
Color WHITE YELLOW MAGENTA RED CYAN GREEN BLUE BLACK Text Display White Yellow Magenta Red Cyan Green Blue Black Intensity BLINK * UNDERLINE * REVERSE LEFT Text Display Blinking Underlined Reverse (inverse) video Left-justified

* The only attributes available on systems where INFORMIXTERM = terminfo

Examples
This example specifies that field text appears in red:
f000 = customer.customer_num, color = red;

The next lines specify various field displays if conditions are TRUE:
f002 f003 f004 f005 = = = = manufact.manu_code, color = red WHERE f002 = "HRO"; customer.lname, color = red WHERE f003 LIKE "Quinn"; mytab.col6, color = green WHERE f004 < 10000; mytab.col9, color = blue reverse WHERE f005 IS NULL, color = yellow WHERE f005 BETWEEN 5000 and 10000, color = red blink WHERE f005 > 10000;

Related Attribute
REVERSE

Form Building and Compiling

4-27

COMMENTS

COMMENTS
Overview
You can use the COMMENTS attribute to cause INFORMIX-4GL to display a message on the Comment line at the bottom of the screen. The message is displayed when the cursor moves to the associated field and is erased when the cursor moves to another field.

Syntax
field-tag = [ table. ] column, COMMENTS = "message" ;

Explanation
field-tag table.column
COMMENTS =

is the field tag used in the SCREEN section. is the name of a field (either related to a column or FORMONLY). is a keyword, followed by an equal ( = ) sign. is a character string enclosed in quotation marks.

message

Notes
1. The message must appear between quotation ( " ) marks on a single line of the form specification file. 2. The default position of the Comment line on the screen is line 23. You can reset this position with the OPTIONS statement. 3. The default position of the Comment line in a window is LAST. You can reset this position in the OPTIONS statement (if you want the new position in all windows) or in the ATTRIBUTE clause of the appropriate OPEN WINDOW statement (if you want the new position in a specific window). See Chapter 7 for a description of the OPTIONS and OPEN WINDOW statements of INFORMIX-4GL. 4. The most common application of the COMMENTS attribute is to give information or instructions to the user. This is particularly appropriate when the field accepts only a limited set of values. (See the description of the INCLUDE attribute later in this section for details of how to specify a range or a list of acceptable values for data entry.)

4-28

Form Building and Compiling

COMMENTS

5. 4GL programs can use the same screen form to support distinct task (for example, data input and query by example). Do not specify the COMMENTS attribute in a field description unless the message is appropriate to all of the tasks in which the message can appear. If the same field requires a different message for various tasks, you should specify each message using the INFORMIX-4GL MESSAGE or DISPLAY statements, rather than in the form specification file.

Example
This field description specifies a message for the Comment line. The message will appear when the screen cursor enters the field that displays the first name of a customer:
c2 = customer.fname, comments = "Please enter initial if available.";

Related Attribute
INCLUDE

Form Building and Compiling

4-29

DEFAULT

DEFAULT
Overview
Use the DEFAULT attribute to assign a default value to a display field.

Syntax
field-tag = [ table. ] column, DEFAULT = value;

Explanation
field-tag table.column
DEFAULT =

is the field tag used in the SCREEN section. is the name of a field (either related to a column or FORMONLY). is a keyword, followed by an equal ( = ) sign. is the default value.

value

Notes
1. Default values have no effect when you execute the INPUT statement using the WITHOUT DEFAULTS option. In this case, INFORMIX-4GL displays the values in the program variables list on the screen. The situation is the same for the INPUT ARRAY statement, except that INFORMIX-4GL displays the default values when you insert a new row. 2. If you use the WITHOUT NULL INPUT option in the DATABASE section and you do not use the DEFAULT attribute, then character fields default to blanks, number and INTERVAL fields to 0, and MONEY fields to $0.00. The default DATE value is 12/31/1899, and the DATETIME default value is 1899-12-31 23:59:59.99999. 3. If you do not use the WITHOUT NULL INPUT option in the DATABASE section, all fields default to NULL values unless you use the DEFAULT attribute. 4. If table is FORMONLY, you must specify a data type when you assign the DEFAULT attribute to a field. (See the syntax in the section “Form-Only Fields” earlier in this chapter.) 5. For CHAR or DATE fields, enclose value in quotes ( " ).

4-30

Form Building and Compiling

DEFAULT

6. If the field type is DATETIME or INTERVAL, you can enclose value in quotation ( " ) marks, or enter it as an unquoted literal:
DATETIME (values) qualifier [ + | - ]INTERVAL (values) qualifier

Here values and qualifier are terms described in Appendix J. Besides these quoted and literal formats, a value of data type INTERVAL can also be specified in the format: expression UNITS field Here expression can be a literal number, or the name of a number column or variable, or an expression in parentheses that evaluates to a number. UNITS is a keyword, and field is a DATETIME element name, such as MONTH, DAY, HOUR, and so forth. (Here field is neither a field name nor field tag.) 7. If both the DEFAULT attribute and the REQUIRED attribute are assigned to the same field, the REQUIRED attribute is ignored. 8. Use the TODAY keyword as the value to assign the current date as the default value of a DATE field. 9. Use the CURRENT keyword as the value to assign the current date and time as the default for a DATETIME field.

Example
The following field descriptions specify DEFAULT values:
c8 = state, UPSHIFT, AUTONEXT, DEFAULT = "CA"; o12 = order_date, DEFAULT = TODAY; f019 = formonly.timestamp TYPE DATETIME YEAR TO DAY COLOR = red, DEFAULT = CURRENT;

Form Building and Compiling

4-31

DISPLAY LIKE

DISPLAY LIKE
Overview
Use the DISPLAY LIKE attribute to display the field by using the attributes assigned to a database column in the syscolatt table.

Syntax
field-tag = [ table. ] column, DISPLAY LIKE tbl.col;

Explanation
field-tag table.column
DISPLAY LIKE

is the field tag used in the SCREEN section. is the name of a field (either related to a column or FORMONLY). are required keywords. is the name of a database column.

tbl.col

Notes
1. This attribute is equivalent to listing all the attributes that you have assigned to tbl.col in the syscolatt table. See the section “Default Screen Attributes” for details of the syscolatt table. 2. You do not need the DISPLAY LIKE attribute if table.column is the same as tbl.col. 3. Do not use a column of type DATETIME or INTERVAL for tbl.col.

Example
s12 = formonly.total, DISPLAY LIKE items.total_price;

Related Attribute
VALIDATE LIKE

4-32

Form Building and Compiling

DOWNSHIFT

DOWNSHIFT
Overview
Assign the DOWNSHIFT attribute to a character field when you want INFORMIX-4GL to convert uppercase letters entered by the user to lowercase letters, both on the screen and in the corresponding program variable.

Syntax
field-tag = [ table. ] column, DOWNSHIFT;

Explanation
field-tag table.column
DOWNSHIFT

is the field tag used in the SCREEN section. is the name of a field (either related to a column or
FORMONLY).

is the keyword that instructs INFORMIX-4GL to convert character input data to lowercase letters in the program variable.

Note
Because uppercase and lowercase letters have different ASCII values, storing character strings in one or the other format can simplify sorting and querying a database.

Related Attribute
UPSHIFT

Form Building and Compiling

4-33

FORMAT

FORMAT
Overview
Use the FORMAT attribute with a DECIMAL, SMALLFLOAT, FLOAT, or DATE field to control the format of output displays.

Syntax
field-tag = [ table. ] column, FORMAT = " format-string" ;

Explanation
field-tag table.column
FORMAT =

is the field tag used in the SCREEN section. is the name of a field (either related to a column or FORMONLY). is a keyword, followed by an equal ( = ) sign. is a string of characters to specify a data format. You must enclose format-string in quotation marks.

format-string

Notes
1. For DECIMAL, SMALLFLOAT, or FLOAT data types, the format-string consists of pound signs (#) that represent digits, and a decimal point. For example, "###.##" produces at least three places to the left of the decimal point and exactly two to the right. 2. If the actual number displayed is shorter than the format-string, INFORMIX-4GL right justifies it and pads the left with blanks. 3. If the format-string is smaller than the display width, FORM4GL gives a warning, but the form is usable. INFORMIX-4GL displays the data right justified in the field. 4. If necessary to satisfy the format, INFORMIX-4GL rounds numbers before displaying them. 5. For DATE data types, INFORMIX-4GL recognizes the following symbols as special in the format-string: mm mmm produces the two-digit representation of the month. produces a three-letter abbreviation of the month; for example, Jan, Feb, and so on.

4-34

Form Building and Compiling

FORMAT

dd ddd yy yyyy

produces the two-digit representation of the day. produces a three-letter abbreviation of the day of the week; for example, Mon, Tue, and so on. produces the two-digit representation of the year. produces a four-digit year.

For dates, FORM4GL interprets any other characters as literals and displays them wherever you place them within format-string. 6. If FORMAT is an attribute of any field name of a multiple-column field, the field uses the specified format-string regardless of which column is active.

Examples
For DATE fields:
Input no FORMAT attribute FORMAT = "mm/dd/yy" FORMAT = "mmm dd, yyyy" FORMAT = "yymmdd" FORMAT = "dd-mm-yy" FORMAT = "(ddd.) mmm. dd, yyyy" Result 09/15/1989 09/15/89 Sep 15, 1989 890915 15-09-89 (Sat.) Sep. 15, 1989

Related Attribute
PICTURE

Form Building and Compiling

4-35

INCLUDE

INCLUDE
Overview
Use the INCLUDE attribute to specify acceptable values for a field, and to cause INFORMIX-4GL to check before accepting an input value.

Syntax
field-tag = [ table. ] column, INCLUDE = ( { value | value TO value } [ , . . . ] );

Explanation
field-tag table.column
INCLUDE =

is the field tag used in the SCREEN section. is the name of a field (either related to a column or FORMONLY). is a keyword, followed by an equal ( = ) sign. is an element in a list (in parentheses) of individual values (value1, value2, . . . ), or a range of values (value1 TO value2), or any combination of individual values and ranges, separated by commas. is a keyword that separates the lower and upper limits of a range of values.

value

TO

Notes
1. If table is FORMONLY, you must specify a data type when you assign the INCLUDE attribute to a field. (See the syntax in the section “Form-Only Fields” earlier in this chapter.) 2. When you specify a range of values, the lower value must appear first. (Here ‘‘lower’’ means the number closer to zero or with the larger negative value; or the earlier DATE or DATETIME value; or the string that starts with a character closer to the beginning of the ASCII collating sequence.) 3. For ranges of character values, INFORMIX-4GL uses dictionary order within the printable ASCII character set. (See Appendix H for the ASCII collating sequence.) In a number field, the range 5 TO 10 is acceptable. In a character field, it is incorrect. The character string ‘‘10’’ is less than the string ‘‘5,’’ since 1 comes before 5 in the ASCII character set.

4-36

Form Building and Compiling

INCLUDE

4. If you include a character string that contains a blank space, a comma, or any special characters, or does not begin with a letter, you must enclose the entire string in quotation marks. It is advisable to enclose character strings in quotation marks at all times. 5. The user must enter an acceptable value in any display field with the INCLUDE attribute before INFORMIX-4GL accepts a new row. 6. If the list of acceptable values in the value-list does not include the default value, the INCLUDE attribute behaves like the REQUIRED attribute, and an acceptable entry is required. 7. Including a COMMENTS attribute to indicate acceptable values makes data entry easier.

Example
i18 = items.quantity, include = (1 to 50), comments = "Acceptable values are 1 through 50";

Related Attributes
COMMENTS, REQUIRED

Form Building and Compiling

4-37

NOENTRY

NOENTRY
Overview
Use the NOENTRY attribute to prevent data entry during an INPUT or INPUT ARRAY statement.

Syntax
field-tag = [ table. ] column, NOENTRY;

Explanation
field-tag table.column
NOENTRY

is the field tag used in the SCREEN section. is the name of a field (either related to a column or FORMONLY). is a keyword indicating that no data can be entered in the field by an INPUT or INPUT ARRAY statement.

Note
The NOENTRY attribute does not prevent data entry into a field during a CONSTRUCT statement (for a query by example).

Example
i13 = items.stock_num; = stock.stock_num, NOENTRY;

When you are entering data into the stock table, the stock_num column is not available, since this SERIAL column gets its value from INFORMIX-4GL during the INSERT statement. You can, however, use the same field to enter the stock number intended for the items table.

4-38

Form Building and Compiling

PICTURE

PICTURE
Overview
Use the PICTURE attribute to specify the character pattern for data entry to a character field.

Syntax
field-tag = [ table. ] column, PICTURE = "format-string";

Explanation
field-tag table.column
PICTURE =

is the field tag used in the SCREEN section. is the name of a field (either related to a column or
FORMONLY).

is a keyword, followed by an equal ( = ) sign. is a string of characters (enclosed in quotes) to specify the desired character pattern.

format-string

Notes
1. A format-string can include three special symbols:
Symbol A # X Meaning Any letter Any digit Any character

INFORMIX-4GL treats any other character in the format-string as a literal. The cursor skips over any literals during data entry.

2. INFORMIX-4GL displays the literal characters in the display field and leaves blanks elsewhere. 3. The format-string must fill the entire width of the display field. 4. If the user attempts to enter a character not in conformity with the format-string, the terminal beeps, and INFORMIX-4GL does not echo the character on the screen. 5. The PICTURE attribute does not require the entry of the entire field. It only requires that whatever the user enters conforms to format-string.

Form Building and Compiling

4-39

PICTURE

6. When PICTURE formats DATETIME or INTERVAL fields, FORM4GL does not check the syntax of format-string, but your form will work if the syntax is correct. Any error in format-string, however, such as an incorrect field separator, produces a run-time error.

Examples
The field specification
c10 = customer.phone, picture = "###-###-####x#####";

produces the following display field before data entry:
[ x ]

As another example, if you specify a field for part numbers like this
f1 = part_no, picture = "AA#####-AA(X)"; INFORMIX-4GL accepts any of the following inputs: LF49367-BB(*) TG38524-AS(3) YG67489-ZZ(D)

The user does not enter the ‘‘-’’ or the parentheses, but INFORMIX-4GL includes them in the string that it passes to the program variable.

Related Attribute
FORMAT

4-40

Form Building and Compiling

REQUIRED

REQUIRED
Overview
Use the REQUIRED attribute to force data entry in a particular field during an INPUT or INPUT ARRAY statement.

Syntax
field-tag = [ table. ] column, REQUIRED;

Explanation
field-tag table.column
REQUIRED

is the field tag used in the SCREEN section. is the name of a field (either related to a column or
FORMONLY).

is the keyword that instructs INFORMIX-4GL to insist upon data entry to the field-tag field.

Notes
1. The REQUIRED keyword is effective only when table.column occurs in the list of screen fields of an INPUT or INPUT ARRAY statement. 2. There is no default value for a REQUIRED field. If you assign both the REQUIRED attribute and the DEFAULT attribute to the same field, INFORMIX-4GL assumes that the DEFAULT value satisfies the REQUIRED attribute. 3. The REQUIRED attribute requires only that the user enter a printable character in the field. If the user subsequently erases the entry during the same input, INFORMIX-4GL considers the REQUIRED attribute satisfied. If you want to insist on a non-NULL entry, make the field form-only and NOT NULL.

Example
If your ATTRIBUTES section includes the field description
o20 = orders.po_num, REQUIRED; INFORMIX-4GL requires the entry of a purchase order value when you collect information for a new order. Form Building and Compiling 4-41

REQUIRED

Related Attribute
NOENTRY

4-42

Form Building and Compiling

REVERSE

REVERSE
Overview
Assign the REVERSE attribute to fields that you want INFORMIX-4GL to display in reverse video (dark characters in a bright field).

Syntax
field-tag = [ table. ] column, REVERSE;

Explanation
field-tag table.column
REVERSE

is the field tag used in the SCREEN section. is the name of a field (either related to a column or
FORMONLY).

is the keyword that instructs INFORMIX-4GL to display the field-tag field in reverse video.

Notes
1. On terminals that do not support reverse video, fields having the REVERSE attribute are enclosed in angle brackets ( < > ) . 2. If REVERSE is an attribute of any field name of a multiple-column field, the field is displayed in reverse video, regardless of which column is active.

Example
f000 = customer.customer_num, reverse;

Related Attribute
COLOR

Form Building and Compiling

4-43

UPSHIFT

UPSHIFT
Overview
Assign the UPSHIFT attribute to a character field when you want INFORMIX-4GL to convert lowercase letters in data entry to uppercase letters, both on the screen and in the program variable corresponding to that field.

Syntax
field-tag = [ table. ] column, UPSHIFT;

Explanation
field-tag table.column
UPSHIFT

is the field tag used in the SCREEN section. is the name of a field (either related to a column or FORMONLY). is the keyword that instructs INFORMIX-4GL to convert character input data to uppercase.

Note
Because uppercase and lowercase letters have different ASCII values, storing all character strings in one or the other format can simplify sorting and querying a database.

Example
c8 = state, UPSHIFT, AUTONEXT, INCLUDE = ("CA", "OR", "NV", "WA"), DEFAULT = "CA" ;

Because of the UPSHIFT attribute, INFORMIX-4GL enters uppercase characters in the state field regardless of the case used to enter them. The AUTONEXT attribute tells INFORMIX-4GL to move automatically to the next field once you type the total number of characters allowed for the field (in this instance, two characters). The INCLUDE attribute restricts entry in this field to the characters CA, OR, NV, or WA only. The DEFAULT value for the field is CA.

4-44

Form Building and Compiling

UPSHIFT

Related Attribute
DOWNSHIFT

Form Building and Compiling

4-45

VALIDATE LIKE

VALIDATE LIKE
Overview
Use the VALIDATE LIKE attribute to cause INFORMIX-4GL to validate the data entered into the field, using the default attributes assigned to a database column in the syscolval table.

Syntax
field-tag = [ table. ] column, VALIDATE LIKE tbl.col;

Explanation
field-tag table.column
VALIDATE LIKE

is the field tag used in the SCREEN section. is the name of a field (either related to a column or FORMONLY). are required keywords. is the name of a database column

tbl.col

Notes
1. This attribute is equivalent to listing all the attributes that you have assigned to tbl.col in the syscolval table. A later section, ‘‘Default Screen Attributes,’’ describes the syscolval table. 2. You do not need the VALIDATE LIKE attribute if table.column is the same as tbl.col. 3. Do not use columns of type DATETIME or INTERVAL for tbl.col.

Example
s13 = formonly.state, VALIDATE LIKE customer.state;

Related Attribute
DISPLAY LIKE

4-46

Form Building and Compiling

VERIFY

VERIFY
Overview
Use the VERIFY attribute when you want INFORMIX-4GL to require users to enter data twice for a particular field, in order to reduce the probability of erroneous data entry.

Syntax
field-tag = [ table. ] column, VERIFY;

Explanation
field-tag table.column
VERIFY

is the field tag used in the SCREEN section. is the name of a field (either related to a column or
FORMONLY).

is the keyword that instructs INFORMIX-4GL to require duplicate data entry to the field-tag field.

Note
Since some data are critical, this attribute supplies an additional step in data entry to ensure the integrity of your data. After the user enters a value into a VERIFY field and presses RETURN, INFORMIX-4GL erases the field and requests reentry of the value. The user must enter exactly the same data each time, character for character: 15000 is not exactly the same as 15000.00.

Example
If you specify a field for salary information like this:
s10 = quantity, VERIFY; INFORMIX-4GL requires the entry of exactly the same data twice.

Form Building and Compiling

4-47

WORDWRAP

WORDWRAP
Overview
Use the WORDWRAP attribute in a multiple-line field to enable the multiline editor. This attribute wraps a long character string to the next line of a multiple-line field for data entry and display.

Syntax
field-tag = [ table. ] column, WORDWRAP [ COMPRESS ] ;

Explanation
field-tag table.column
WORDWRAP COMPRESS

is the field tag used in the SCREEN section. is the name of a multiple-line field (either related to a column or FORMONLY). is a keyword to wrap long character strings to the next segment of a multiple-line field. is a keyword to discard any blank spaces that the user did not enter and that are not part of the data.

Notes
1. When a 4GL program uses a multiple-line field to display output, the data is poured out into the segments of the multiple-line field, in left-to-right and top-to-bottom order. 2. When text is entered into a multiple-line field whose attributes include WORDWRAP, the multiline editor breaks character strings into segments at blanks (if it can), padding field segments with blanks at the right. Where possible, contiguous non-blank substrings (here called ‘‘words’’) within a string are not broken at display line boundaries. 3. When keyboard input reaches the end of a line, the multiline editor brings the current word down to the next line, moving text down to subsequent lines as necessary. When the user deletes text, the editor pulls words up from lower lines whenever it can. 4. Text in WORDWRAP fields can have printable ASCII characters, the TAB, and NEWLINE. These are retained in the program variable. The TAB character aligns the display at the next tab stop, while NEWLINE moves
4-48 Form Building and Compiling

WORDWRAP

5.

6.

7.

8.

9.

10. 11.

the display to the start of the next line. Tab stops are in every eighth column, beginning at the left-hand edge of the field. Ordinarily, the length of the variable should not be greater than the total length of the field. When the data is longer than the field (or if too much padding is required for WORDWRAP), the multiline editor fills the field and discards the excess data. This allows a long variable to be shown in summary form. If a truncated variable is used to update the database, however, data will be lost. The editor distinguishes between intentional blanks (from the database or typed by the user) and editor blanks (inserted at the ends of lines for wordwrap or to align after a NEWLINE). Intentional blanks are retained as part of the data. Editor blanks are inserted and deleted automatically as required for word-wrapping. When designing a multiple-line field, you should allow room for editor blanks, over and above the variable length. The expected number of editor blanks is half the length of an average word per line. Text that requires more space than you expect might be truncated after the final line of the field. The COMPRESS keyword prevents blanks produced by the editor from being included in the program variable. If you specify COMPRESS, truncation occurs only if the sum of intentional characters exceeds the column size. But the stored data does not correspond to its multiline display, so a report cannot display it in identical form. If you omit COMPRESS, all blanks are retained in the variable, even editor blanks, and the contents of a variable reflect its multiline display. For example, a report could duplicate its appearance by printing successive substrings the width of a display segment. If the sum of the field segment lengths exceeds the length of the variable, some trailing characters might be truncated. An earlier section, ‘‘Multiple-Line Fields,’’ describes the SCREEN section specifications for multiple-line fields. When data is entered or updated in a WORDWRAP field, the user can use keys that are described in this note to move the screen cursor over the data, and to insert, delete, and type over the data. The cursor never pauses on editor blanks. The editor has two modes, insert (to add data at the cursor) and typeover (to replace existing data with entered data). You cannot overwrite a NEWLINE. If the cursor in typeover mode encounters a NEWLINE character, the cursor mode automatically changes to insert, ‘‘pushing’’ the NEWLINE character to the right. Some keystrokes behave differently in the two modes.
Form Building and Compiling 4-49

WORDWRAP

When the cursor first enters a multiline field, it is positioned on the first character of the first segment, and the mode is set to typeover. The cursor movement keys are as follows:
RETURN BACKSPACE

leaves the entire multiline field, and goes to the first character of the next field. moves left one character, unless at the left edge of a segment. From the left edge of the first segment, these either move to the first character of the preceding field, or only beep, depending on input wrap mode. (Input wrap mode is controlled by the OPTIONS statement.) From the left edge of a lower segment, these move to the rightmost intentional character of the next higher segment. moves right one character, unless at the rightmost intentional character in a segment. From the rightmost intentional character of the last segment, this either moves to the first character of the next field, or only beeps, depending on input wrap mode. From the rightmost intentional character of a higher segment, this moves to the first intentional character in a lower segment. moves from the topmost segment to the first character of the preceding field. From a lower segment, this moves to the character in the same column of the next higher segment, jogging left, if required, to avoid editor blanks, or if it encounters a TAB. moves from the lowest segment to the first character of the next field. From a higher segment, moves to the character in the same column in the next lower segment, jogging left if required to avoid editor blanks, or if it encounters a TAB. inserts a TAB character, in insert mode, and moves the cursor to the next TAB stop. This can cause following text to jump right to align at a TAB stop. In typeover mode, this moves the cursor to the next TAB stop that falls on an intentional character, going to the next field segment if required.

or
LEFT ARROW

RIGHT ARROW

UP ARROW

DOWN ARROW

TAB

The character keys enter data. Any following data shifts right, and words can move down to subsequent segments. This can result in characters

4-50

Form Building and Compiling

WORDWRAP

being discarded from the final segment of the field. The other keystrokes that alter data are:
CONTROL-A CONTROL-X CONTROL-D

switches between typeover and insert mode. deletes the character under the cursor, possibly causing words to be pulled up from subsequent segments. deletes all text from the cursor to the end of the multiple-line field (not merely to the end of the current field segment). inserts a NEWLINE character, causing subsequent text to align at the first column of the next segment of the field, and possibly moving words down to subsequent segments. This can result in characters being discarded from the final segment of the field.

CONTROL-N

12. The appearance on the screen of a character value can vary, depending on whether or not it is displayed in a multiple-line WORDWRAP field. For instance, if a value prepared using WORDWRAP is displayed without it, words will be broken, not wrapped, and tabs and newlines will display as question marks. This does not represent any loss of data, only a different mode of display. If a value prepared under the multiline editor is again edited without WORDWRAP, however, some formatting may be lost. For example, a user might type over a TAB or NEWLINE, not realizing what it was. A user might remove a blank from the first column of a line, and thus join a word to the last word on the previous line. These mistakes will be visible when the value is next displayed in a WORDWRAP field or in a 4GL report that uses the WORDWRAP function. 13. If you also have INFORMIX-SQL installed on your system, you can use the SQL Interactive Editor to display character data that you prepared using WORDWRAP. Since the default screen display of the Interactive Editor does not wrap words, words will appear broken, not wrapped, and TAB and NEWLINE characters will appear as question marks ( ? ). This does not represent any loss of data, only a different mode of display.

Form Building and Compiling

4-51

INSTRUCTIONS Section

Example
In the following form specifications, a CHAR value in the column charcolm is displayed in the multiple-line field whose tag is mlf.
SCREEN SIZE 24 by 80 { Enter text: [mlf ] [mlf ] . . . [mlf ] [mlf ] } TABLES tablet . . .

ATTRIBUTES mlf = tablet.charcolm, WORDWRAP COMPRESS;

If the data string is too long to fit in the first line, successive segments will be displayed in successive lines, until all of the lines are filled, or until the last text character is displayed (whichever happens first). If the form is used to insert data into tablet.charcolm, the keyword COMPRESS specifies that INFORMIX-4GL will not store editor blanks. Do not use a comma between the keywords WORDWRAP and COMPRESS. Note: INFORMIX-OnLine supports additional data types. Refer to the INFORMIX-OnLine Programmer’s Manual for more information.

INSTRUCTIONS Section
The INSTRUCTIONS section is the optional final section of a form specification file. You can use this section to specify non-default field delimiters, and to define screen records and screen arrays. It appears after the last field description (or after the optional END keyword) of the ATTRIBUTES section. It has this structure:

Syntax
INSTRUCTIONS { delimiters | record | array } ... [ END ] 4-52 Form Building and Compiling

INSTRUCTIONS Section

Explanation
INSTRUCTIONS

is a required keyword to mark the beginning of the INSTRUCTIONS section. specifies two non-default screen field delimiters. specifies a screen record. specifies an array of screen records. is an optional keyword to mark the end of the INSTRUCTIONS section.

delimiters record array
END

Notes
1. Specify no more than one delimiters instruction. 2. The END keyword is optional and can be omitted. The pages that follow describe these three types of instructions.

Field Delimiters
You can change the delimiters that INFORMIX-4GL uses to enclose fields when the form appears on the screen from brackets ( [ ] ) to any other printable character, including blank spaces.

Syntax
DELIMITERS "ab"

Explanation
DELIMITERS

is a keyword to specify field delimiters. is the opening field delimiter. is the closing field delimiter.

a b

Notes
1. The DELIMITERS instruction tells INFORMIX-4GL what symbols to use as field delimiters when it displays the form on the screen. 2. FORM4GL requires brackets ( [ ] ) in the SCREEN section of a form specification file, regardless of any DELIMITERS instruction. 3. You must enclose the pair of ab symbols in quotation ( " ) marks.

Form Building and Compiling

4-53

INSTRUCTIONS Section

4. Each delimiter occupies a space, so two fields on the same line are ordinarily separated by at least two spaces. If you want only one space between consecutive screen fields, follow these two steps: (1) In the SCREEN section, substitute a vertical bar ( | ) for paired back-to-back ( ][ ) brackets that separate adjacent fields. (2) In the INSTRUCTIONS section, define some symbol as both the beginning and ending delimiter. For example, you could specify "| |" or "/ /" or ": :" or " " (blanks).

Examples
The following specifications display < and > as opening and closing delimiters of screen fields:
INSTRUCTIONS DELIMITERS "<>" END

The following specifications substitute | for ][ between adjacent fields in the same line of the screen layout, and display a colon ( : ) as both the opening and closing delimiter:
SCREEN { . . . Full Name-[f011 . . . } . . . INSTRUCTIONS DELIMITERS "::" |f012 ]

Here the fields whose tags are f011 and f012 will be displayed as:
Full Name-: | :

If you substitute blanks for colons as DELIMITERS symbols, field boundaries are not marked (or are only marked if they have attributes that contrast with the surrounding background).

4-54

Form Building and Compiling

INSTRUCTIONS Section

Screen Records
You can collect groups of screen fields into screen records. Define any screen records in the INSTRUCTIONS section of a form specification file, and refer to them in your INFORMIX-4GL program.

Syntax
SCREEN RECORD record-name ( { table.* | table.column1 THRU table.column2 | table.column } [ , . . . ] )

Explanation
SCREEN RECORD

are keywords to define a list of fields as a screen record or as a screen array. is an SQL identifier for the screen record. is a table name, alias, or synonym (or the keyword
FORMONLY).

record-name table column1, column2, column
THRU

are field names that you defined in the ATTRIBUTES section. (These identifiers link the fields to database columns, unless you specify table as FORMONLY.) is an optional keyword to specify consecutive fields. The keyword THROUGH is a synonym.

Notes
1. A screen record or screen array can include fields with different table specifications, including FORMONLY. 2. FORM4GL automatically creates a default screen record for each table that is used to identify a field in the form specification file. The default record, which has the name of the table, contains components corresponding to only those columns in the table that are fields on the form. The order of components in a screen record is the order of the field names in the ATTRIBUTES section. Use table.* to denote the same fields as the default record for table. 3. FORM4GL returns an error if you define a screen record with the same name as a table in the form. 4. The option of giving a range of field names with the THROUGH (or THRU) keyword assumes the order in which the fields are listed in the ATTRIBUTES section. The THRU keyword is shorthand for listing all fields
Form Building and Compiling 4-55

INSTRUCTIONS Section

that appear in the ATTRIBUTES section from column1 to column2, inclusive.

Examples
This example creates a screen record called address from fields linked to some columns of the customer table. This record can simplify 4GL statements to update customer address and telephone data.
SCREEN RECORD address (customer.address1 THRU customer.phone)

All the fields linked to columns from the customer table constitute a default screen record whose record-name is customer.

Screen Arrays
You can collect groups of screen fields into screen arrays. A screen array is usually an array of lines on the form, each containing identical groups of screen fields. Each ‘‘column’’ of a screen array consists of fields with the same tag. Define screen arrays in the INSTRUCTIONS section, and refer to them in your INFORMIX-4GL program.

Syntax
SCREEN RECORD record-name [ n ] ( { table.* | table.column1 THRU table.column2 | table.column } [ , . . . ] )

Explanation
Syntax terms are the same as for screen records on the previous page, with the addition of [ n ] as a required integer parameter, enclosed in brackets. (In this context, the brackets are required, and do not signify an optional syntax.)

Notes
1. The integer n specifies the number of rows in the screen array. 2. You can reference record-name in the DISPLAY, DISPLAY ARRAY, INPUT, and INPUT ARRAY statements of INFORMIX-4GL.

4-56

Form Building and Compiling

Default Screen Attributes

Example
To illustrate a typical screen array, consider the following fragment of a form specification file:
SCREEN { ... Item 1 Item 2 Item 3 Item 4 Item 5 }

[p [p [p [p [p

][q ][q ][q ][q ][q

][u ][u ][u ][u ][u

][t ][t ][t ][t ][t

] ] ] ] ]

TABLES orders items stock ATTRIBUTES ... p = stock.stock_num; q = items.quantity; u = stock.unit_price; t = items.total_price; ... INSTRUCTIONS SCREEN RECORD sc_items[5] (stock.stock_num, items.quantity, stock.unit_price, items.total_price)

The sc_items screen array has five rows and four columns and includes fields linked to columns from two database tables. The rows are numbered from 1 to 5. If there are no other columns of the items table in the form, the default screen record items contains two fields, corresponding to the quantity and total_price columns of the items table.

Default Screen Attributes
As an alternative to entering attributes in the form specification file, you can enter them into two database tables, syscolval and syscolatt, using the upscol utility described in Appendix E. During compilation of a form, FORM4GL searches these tables for data validation and screen attribute information about screen fields whose names correspond to database columns. FORM4GL adds the attributes listed in these tables to attributes listed in the form specification file. In case of conflict, attributes explicitly mentioned in the form specification file take priority.

Form Building and Compiling

4-57

Default Screen Attributes

INFORMIX-4GL enforces the resulting set of field attributes during the execution of the INPUT and INPUT ARRAY statements (by using syscolval), and during DISPLAY and DISPLAY ARRAY statements (by using syscolatt).

The schemas of these tables follow:
syscolval tabname char(18) colname char(18) attrname char(10) attrval char(64) syscolatt tabname char(18) colname char(18) seqno serial color smallint inverse char(1) underline char(1) blink char(1) left char(1) def_format char(64) condition char(64)

Here tabname and colname are the names of the table and column to which the attributes apply. Here colname cannot be a DATETIME or INTERVAL column. Permissible values for the attrname and attrval columns in syscolval are shown in the following table:
attrname INCLUDE PICTURE DEFAULT COMMENTS SHIFT VERIFY AUTONEXT attrval as in this chapter as in this chapter as in this chapter as in this chapter UP, DOWN, NO (the default) YES, NO (the default) YES, NO (the default)

The color column in syscolatt stores an integer that describes color (for color terminals) or intensities (for monochrome terminals). The next table shows the displays specified by each value of color, and the correspondence between default color names and intensities.
Number 0 1 2 3 4 5 6 7 Color Terminal White Yellow Magenta Red Cyan Green Blue Black Monochrome Terminal Normal Bold Bold Bold† Dim Dim Dim† Invisible

4-58

Form Building and Compiling

Default Screen Attributes

The background for colors is BLACK in all cases. The † signifies that, if the keyword BOLD is indicated as the attribute, the field will be RED on a color terminal; or, if the keyword DIM is indicated as the attribute, the field will be BLUE on a color terminal. You can also define non-default names for colors, by associating different names with the color number codes in a file named colornames. Appendix I describes the format of the colornames file. If this exists in $INFORMIXDIR/incl (see Appendix C), INFORMIX-4GL examines colornames at compile time to obtain the correspondence between the numbers 0 through 7 and the color names. Those names can appear in the ATTRIBUTE clause of a 4GL statement. (But you cannot use numbers or nondefault colors from colornames to specify the COLOR attribute in a form specification file.) The values for inverse, underline, and blink are Y (yes) and N (no). The default for each of these columns is N, that is, normal display (bright characters in a dark field), no underline, and steady font. Which of these attributes can be displayed simultaneously with the color combinations or with each other is terminal-dependent. The def_format column takes the same string that you would enter for the FORMAT attribute in a screen form. Do not use quotation marks. The condition column takes string values that are a restricted set of the WHERE clauses of a SELECT statement, except that the WHERE keyword and the column name are omitted. INFORMIX-4GL assumes that the value in the column identified by tabname and colname is the subject of all comparisons. Examples of permitted entries for the condition column follow:
<= 100 BETWEEN 101 AND 1000 >= 1001 MATCHES "[A-M]*" IN ("CA", "OR", "WA") NOT LIKE "%analyst%"

The VALIDATE statement checks a program record or variable list against syscolval. The INITIALIZE statement looks up the default values that are listed in the syscolval table, and assigns them to variables. Some 4GL statements, including CONSTRUCT, DISPLAY, DISPLAY ARRAY, INPUT, INPUT ARRAY, and OPTIONS, support an ATTRIBUTE clause that can specify these attributes:
WHITE = NORMAL YELLOW = BOLD MAGENTA = BOLD RED = BOLD CYAN = DIM GREEN = DIM BLUE = DIM BLACK = INVISIBLE REVERSE BLINK UNDERLINE

Form Building and Compiling

4-59

The upscol Tables in a MODE ANSI Database

On color terminals, NORMAL is interpreted as WHITE; BOLD as RED; DIM as BLUE; and INVISIBLE as BLACK. If you have a colornames file, you can also use the color names or numbers listed there. You can override the default attributes in syscolatt by assigning other attributes in the form specification file, or in the ATTRIBUTE clause of the INFORMIX-4GL CONSTRUCT, DISPLAY, DISPLAY ARRAY, INPUT, or INPUT ARRAY statement. When one of these is the current statement and includes an ATTRIBUTE clause, INFORMIX-4GL displays only the attributes in that clause. There is no carry-over of unmentioned display attributes from the compiled form (except FORMAT). For example, if a column is designated as RED and BLINK in syscolatt, and your 4GL program executes the statement DISPLAY . . . ATTRIBUTE BLUE the field has only the BLUE attribute. You do not get blinking BLUE. As stated earlier, form specification file attributes take precedence over the default syscolatt attributes. A note describing the OPTIONS statement in Chapter 7 lists the order of precedence among different sources of attribute specifications, if these are in conflict. Unconditional color or intensity attributes are available through the ATTRIBUTE clause. These and conditional attributes are also supported by syscolatt and by the COLOR keyword in the ATTRIBUTES section. You can use the upscol utility, described in Appendix E, to specify default attributes in syscolval and syscolatt. The color, intensity, and other screen attributes interact with termcap or terminfo files on UNIX systems. Appendix I describes the changes that should be made in system information files to support these display features for your terminal. Systems that use terminfo files rather than termcap, however, support no INFORMIX-4GL display attributes except REVERSE and UNDERLINE.

The upscol Tables in a MODE ANSI Database
In a database that is not MODE ANSI, the default screen attributes and validation criteria that you specify with the upscol utility are stored in two tables, syscolval and syscolatt. If any user of upscol assigns default values or attributes to a database column, those defaults are available to every user of a form that references the column.

4-60

Form Building and Compiling

Creating and Compiling a Form

In a database that is started or created as MODE ANSI, however, separate owner.syscolval and owner.syscolatt tables are created for each user of the upscol utility. These tables store the default specifications of that individual user. Which set of upscol tables is used by FORM4GL depends on the nature of the request. If the TABLES section specifies a table alias for owner.table, FORM4GL uses the upscol tables of the owner of table. If that user owns no upscol tables, no defaults are assigned to fields associated with that table alias. If the TABLES section of the form does not specify a table alias that includes the owner of a database table, the upscol tables owned by the user running FORM4GL are applied to fields associated with that database table, unless the user owns no upscol tables. In the ATTRIBUTES section, specifications of the form
field-tag = . . . DISPLAY LIKE table.column field-tag = . . . VALIDATE LIKE table.column

use upscol tables (if they exist) owned by the user who runs FORM4GL, unless table is an alias that specifies a different owner. If table is an alias for owner.table, FORM4GL uses the upscol tables of the owner specified by table. If the upscol tables do not exist, the statements take no action. If owner is not the correct owner, the compilation fails and an error message is issued. See also the notes in Chapter 7 on the VALIDATE and INITIALIZE statements of INFORMIX-4GL.

Creating and Compiling a Form
You can create a form specification file and its customized screen form either through the INFORMIX-4GL Programmer’s Environment or directly from the operating system. Either alternative requires that you have already created the database and all the tables to which the form refers. The next two subsections describe these alternative procedures.

Form Building and Compiling

4-61

Through the Programmer’s Environment

Through the Programmer’s Environment
To create a screen form using the Programmer’s Environment (which is described in Chapter 1), you must follow these steps: 1. At the system prompt, enter i4gl if you have the C Compiler Version, or r4gl if you have the Rapid Development System. 2. Select Form and then Generate from the menu. (Alternatively, you can select the New option. INFORMIX-4GL prompts you for a form name, prompts you for an editor if you have not already selected one, and invokes that editor with an empty form specification file. Now you must enter form specifications. The Generate option is usually a more efficient way to create a customized form.) 3. Enter the name of the database and the name that you want to assign to the form (for example, myform). INFORMIX-4GL asks you for the names of the tables whose columns you want in your form. After you select the tables, FORM4GL creates a default form specification file, as well as a compiled default form, and then displays the FORM Design Menu. 4. The default form specification file formats the screen as a list of all the columns in the tables that you entered in Step 3. It does not provide any special instructions to INFORMIX-4GL about how to display the data. Select the Modify option, and INFORMIX-4GL presents the MODIFY FORM Screen. Select the default form specification (given as myform earlier), and INFORMIX-4GL calls a system editor to display the file. Edit the default form specification file to produce your customized screen form and associated instructions. (You can specify an editor using the DBEDIT environment variable. This is fully explained in Appendix C.) When you save your file and quit the editor, you return to the MODIFY FORM Menu. 5. Select Compile. If your form specification file successfully compiles, FORM4GL creates a form file with the extension .frm (for example, myform.frm). Go on to Step 7. If your form specification file does not compile successfully, go on to Step 6. 6. Select the Correct option from the COMPILE FORM Menu. INFORMIX-4GL again calls your editor to display the form specification file, with the compilation errors marked. When correcting your errors, you need not delete the error messages. INFORMIX-4GL does that for you. Save the file and go to Step 5. 7. Save your form specification file with the Save-and-exit option.

4-62

Form Building and Compiling

Through the Operating System

Through the Operating System
The FORM4GL command line has the following syntax:

Syntax
form4gl { [ -l lines ] [ -c cols ] [ -v ] form-name | -d }

Explanation
-l lines are optional symbols and an integer to specify the total number of lines of characters (measured vertically) that the terminal can display. (The default is 24.) are optional symbols and an integer to specify the width of the screen, in characters. (The default is the number of characters in the longest line of the screen layout, as specified in the SCREEN section.) are optional characters to verify that the screen fields are as wide as any corresponding character fields specified in the ATTRIBUTES section. is the name of the form specification file (without the .per extension). are optional symbols to specify a default form specification file.

-c cols

-v

form-name -d

To create a customized screen form directly from the operating system, follow these steps: 1. Create a default form specification file by entering the command
form4gl -d

at the operating system prompt. FORM4GL asks for the name of your form specification file, the name of your database, and the name of a table whose columns you want in your form. It continues to ask for another table name until you enter a RETURN for the name of a table. FORM4GL then creates a default form specification file and appends the extension .per to its name. It also creates a compiled default form with the extension .frm. 2. Use the system editor to modify the default form specification file to meet your specifications. If, as an alternative, you create a new form specification file and skip Step 1, be sure to give the filename the extension .per.

Form Building and Compiling

4-63

Using PERFORM Forms in INFORMIX-4GL

3. Enter a command of the form:
form4gl myform

Here myform is the name of your form specification file (without the .per extension). If the compilation is successful, FORM4GL creates a compiled form file called myform.frm and you are finished creating your customized screen form. If not, FORM4GL instead creates a file named myform.err, and you need to go on to Step 4. 4. Review the file myform.err to discover the compilation errors. Make corrections in the file myform.per. Go to Step 3.

Using PERFORM Forms in INFORMIX-4GL
If you have designed forms to use with the PERFORM screen transaction program of INFORMIX-SQL, you need to know how those forms behave when used with INFORMIX-4GL. The following features differ between PERFORM and INFORMIX-4GL:

• Only the DELIMITER keyword in the INSTRUCTIONS section of a
PERFORM form specification is supported in INFORMIX-4GL. Other

keywords in that section are ignored. For the same effects, you must code them into your INFORMIX-4GL program. (See the BEFORE and AFTER clauses of the INPUT statement.)

• Multiple-page forms will not work with INFORMIX-4GL and will
produce undesirable overlays. (You can use multiple forms in 4GL to produce the effects of forms having several pages.)

• There is no concept of ‘‘current table’’ in INFORMIX-4GL. A single INPUT
or INPUT ARRAY statement allows you to enter data into fields that correspond to columns in different tables.

• Joins defined in the PERFORM form specification are ignored in INFORMIX-4GL. You can associate two field names with the same field tag, using the same notation as in a PERFORM join, but no join is effected. On the

other hand, you can create more complex joins and look-ups in INFORMIX-4GL using the full power of SQL.

• The PERFORM attributes LOOKUP, NOUPDATE, QUERYCLEAR, RIGHT,
and ZEROFILL are inoperative in INFORMIX-4GL, and the conditions of a COLOR attribute cannot reference other field tags nor aggregate functions.

• The default attributes listed in syscolval and syscolatt do not apply
to your PERFORM forms unless you recompile them.
4-64 Form Building and Compiling

Chapter

Report Writing
Chapter Overview 3 Calling a REPORT Routine 4 Structure of a REPORT Routine 5 DEFINE Section 7 OUTPUT Section 9 REPORT TO 10 LEFT MARGIN 12 RIGHT MARGIN 13 TOP MARGIN 15 BOTTOM MARGIN 16 PAGE LENGTH 17 ORDER BY Section 18 FORMAT Section 20 EVERY ROW 21 Control Blocks 23 AFTER GROUP OF 25 BEFORE GROUP OF 27 FIRST PAGE HEADER 29 ON EVERY ROW 31 ON LAST ROW 33 PAGE HEADER 34 PAGE TRAILER 36 Statements 37 Standard 4GL Statements 37 Statements Valid Only in the FORMAT Section NEED 38 PAUSE 39 PRINT 40 PRINT FILE 42 SKIP 43 Expressions and Built-in Functions 44

5
37

Aggregates 46 LINENO 48 PAGENO 49 SPACES 50 WORDWRAP 51

5-2

Report Writing

Chapter Overview
INFORMIX-4GL provides all the tools of a general-purpose relational report writer. Reports in INFORMIX-4GL have the following features:

• You have full control over page layout for your 4GL report. This includes
first-page headers that differ from headers on subsequent pages, page trailers, columnar data presentation, special formatting before and after groups of sorted data, and conditional formatting that depends on the data.

INFORMIX-4GL provides aggregate functions that enable you to compute percentages, sums, averages, maximums, and minimums.

• You can use the WORDWRAP function to display long character strings
that occupy multiple lines of output.

• You can use all the built-in functions of INFORMIX-4GL and the USING
operator. (Chapter 2 describes USING and the built-in 4GL functions and expressions.)

• You can create the report either from the rows returned by a cursor or
from report records assembled from any other source, such as the output of several different SELECT statements.

• You can manipulate data returned by the cursor on a row-by-row basis,
either before or after the row is formatted by the report.

• You can update the database or perform any other sequence of INFORMIX-4GL statements in the middle of writing a report if the intermediate values calculated by the report meet your criteria. For example, you could even write an alert message containing a second report.

This chapter describes the rules for calling and writing 4GL REPORT routines. (See also Chapter 9 of the INFORMIX-4GL User Guide for additional examples of REPORT routines.)

Report Writing

5-3

Calling a REPORT Routine

Calling a REPORT Routine
To call a REPORT routine requires three 4GL statements that occur before, during, and after a program loop that you define. You can call a REPORT routine from the MAIN program block of a 4GL program or from a function, but a routine of type REPORT must be defined outside the MAIN program block
START REPORT report-name [ TO { PRINTER | PIPE program | filename } ] OUTPUT TO REPORT report-name ( variable-list ) FINISH REPORT report-name

The basic loop structure (whether a FOR, FOREACH, or WHILE loop) is illustrated as follows:
START REPORT report1 begin loop -- of whatever kind . . . OUTPUT TO REPORT report1(customer.*) . . . end loop FINISH REPORT report1

• The START REPORT statement initializes the report and optionally
specifies the output file or device.

• The OUTPUT TO REPORT statement tells INFORMIX-4GL to process the
next row of the report.

• The FINISH REPORT statement causes the ON LAST ROW control block
to be executed, if it is present, so that INFORMIX-4GL can produce the end-of-report summaries. You can find the full syntax for these statements in Chapter 7.

5-4

Report Writing

Structure of a REPORT Routine

Structure of a REPORT Routine
Like the MAIN program block or a function of a 4GL program, a report is a sequence of consecutive statements within a 4GL source file. A REPORT routine is composed of sections that consist of control blocks or statements, or both. Each statement can contain clauses made up of keywords and expressions. You must observe the order of the sections that follow when you write an INFORMIX-4GL REPORT routine.

DEFINE Section: This section declares the data types of any program variables or records that are passed as arguments to the report by the calling statement, and of any local variables or records that are used within the report. Reports that do not have such arguments or local variables do not require a DEFINE section. OUTPUT Section: This optional section specifies a non-default page

length and margins for the physical format of the report, and specifies whether INFORMIX-4GL sends the report to the screen, to a file, or to another program.

• •

ORDER BY Section: This optional section specifies the variables on which you want rows to be sorted, and the order in which 4GL will process any group control blocks that you specify in the FORMAT section. FORMAT Section: This required section specifies the appearance of the

report, including page headers, page trailers, and aggregate functions of the data. Control blocks can specify actions to take before or after specific groups of rows are processed, using any INFORMIX-4GL statement, expression, or function. Control blocks can also include certain statements and functions that are only recognized within the FORMAT section of a REPORT routine. Each section begins with the keyword for which it is named. These elements of a REPORT routine are described in the pages that follow. The first statement of a REPORT routine must be the REPORT statement, and the last must be the END REPORT statement:

Syntax
REPORT report-name (argument-list) [ DEFINE section ] [ OUTPUT section ] [ ORDER BY section ] FORMAT section END REPORT

Report Writing

5-5

Structure of a REPORT Routine

Explanation
REPORT

is a required keyword. is an INFORMIX-4GL identifier.

report-name

(argument-list) is a list of variables or record identifiers, enclosed in parentheses and separated by commas.
END REPORT

are required keywords.

Notes
1. Record identifiers cannot have the asterisk ( .* ) extension in argument-list. 2. The DEFINE, OUTPUT, ORDER BY, and FORMAT sections are described in later sections of this chapter. 3. A minimal report consists only of the FORMAT section. You can include other sections as needed.

Examples
Several REPORT routines are included with the demonstration application listed in Appendix A. They illustrate many of the commands available for writing reports with INFORMIX-4GL, and provide some of the examples that appear in this chapter.

5-6

Report Writing

DEFINE Section

DEFINE Section
An INFORMIX-4GL REPORT routine requires a DEFINE section when you pass arguments to the report or use local variables in the report.

Syntax
DEFINE variable-list { type | LIKE table.column | RECORD { LIKE table.* | variable-list type [ , . . . ] END RECORD } } [ , . . . ]

Explanation
DEFINE

is a required keyword. is one or more identifiers of program variable. is one of these data types (as defined in Chapter 2):
SMALLINT INTEGER INT DECIMAL [ (m [ , n ] ) ] DEC [ ( m [ , n ] ) ] NUMERIC [ (m [ , n ] ) ] SMALLFLOAT REAL RECORD [ LIKE table. * ] FLOAT [ ( n ) ] DOUBLE PRECISION [ ( n ) ] MONEY [ (m [ , n ] ) ] CHAR [ ( n ) ] CHARACTER [ (n ) ] DATE DATETIME qualifier INTERVAL qualifier

variable-list type

LIKE

is a keyword to specify the data type indirectly. is the full identifier for a column in the current database. The DATABASE statement must precede DEFINE statements that use indirect typing. is a data type that describes a set of variables of possibly differing database data types. is the name of a database table. are keywords that follow the declaration of the last element of a program record.

table.column

RECORD

table
END RECORD

Report Writing

5-7

DEFINE Section

Notes
1. The DEFINE section obeys the same rules as given in Chapter 7 for the DEFINE statement, except that report parameters cannot be of type ARRAY, nor can they be records with ARRAY members. 2. The variable-list must include any local variables that you use in the report, and any variables or record identifiers that appear in the argument-list of the REPORT statement. You are required to specify an argument-list if any of the following conditions are true:

• When there is an ORDER BY section in your report. In this case, you
must pass all the values for each row of the report.

• When you use the GROUP PERCENT aggregate function anywhere in
your report, or use an aggregate function over all the rows of the report at any place except in the ON LAST ROW control block. (In short, if you print an aggregate dependent on all rows of the report in the middle of the report, you must pass the rows of the report through the argument-list.)

• When you use the FORMAT EVERY ROW control block. In this case,
you must pass all the values for each row of the report.

• When you use the AFTER GROUP OF control block. In this case, you
must pass at least the parameters named in that block.

Example
REPORT r_invoice (c, stock_tot) DEFINE c RECORD LIKE customer.*, stock_tot SMALLINT

Note: INFORMIX-OnLine supports additional functionality. Refer to the INFORMIX-OnLine Programmer’s Manual for more information.

5-8

Report Writing

OUTPUT Section

OUTPUT Section
An INFORMIX-4GL REPORT routine can contain an OUTPUT section. This optional section controls the width of the margins and the length of the page, and allows you to direct the output from the report to a file, to a printer, or to an operating system pipe. The OUTPUT section consists of the OUTPUT keyword, followed by one or more statements. The OUTPUT section has this structure:
OUTPUT [ REPORT TO statement ] [ LEFT MARGIN statement ] [ RIGHT MARGIN statement ] [ TOP MARGIN statement ] [ BOTTOM MARGIN statement ] [ PAGE LENGTH statement ]

• The REPORT TO statement specifies where to send output from the report
routine. If you omit this section, output is to the screen.

• The LEFT MARGIN statement specifies how many blank spaces to include
at the left of each line of output. The default is 5 spaces.

• The RIGHT MARGIN statement specifies the maximum number of characters in each line of output, including the left margin. The default is 132 characters.

• The TOP MARGIN statement specifies how many blank lines appear
before the first line on each page of output. The default is 3 lines.

• The BOTTOM MARGIN statement specifies how many blank lines follow
the last line on each page of output. The default is 3 lines.

• The PAGE LENGTH statement specifies the total number of lines on each
page of output, including lines of data, the top and bottom margins, and any page headers or page trailers that you define in the FORMAT section. The default is 66 lines. The pages that follow describe these OUTPUT statements.

Report Writing

5-9

REPORT TO

REPORT TO
Overview
This optional statement directs the output of the INFORMIX-4GL report to a file, an operating system pipe, or the system printer.

Syntax
REPORT TO { "filename" | PIPE "program" | PRINTER }

Explanation
REPORT TO

are required keywords. is a quoted string containing the name of a file to receive the report. is an optional keyword. is a variable of type CHAR or a quoted string containing the name of a program that is to receive the output from the INFORMIX-4GL report. The program name, and any associated arguments, must be enclosed within quotation ( " ) marks. is an optional keyword.

filename
PIPE

program

PRINTER

Notes
1. You cannot use more than one of the REPORT TO options in a REPORT routine. When you do not use this optional statement, INFORMIX-4GL sends the report to your screen. 2. If the START REPORT statement has a TO clause directing output of the report to a file, pipe, or printer, INFORMIX-4GL ignores the REPORT TO statement of the OUTPUT section. 3. If filename is a variable, you must pass it as an argument to the REPORT routine. 4. The REPORT TO PRINTER statement causes INFORMIX-4GL to send the report to the program named by the DBPRINT environment variable. If you do not set this variable, INFORMIX-4GL sends the report to the lp program, or to whatever program is the default to access the system printer on your implementation of UNIX.
5-10 Report Writing

REPORT TO

5. If you want to send the report to a printer other than the system printer, you can use the REPORT TO filename option to send output to a file, and then send the file to a printer of your choice. You can also use the REPORT TO PIPE option to direct the output to a program that sends the output to the correct printer.

Examples
The following OUTPUT section directs the report output to the label.out system file.
OUTPUT REPORT TO "label.out" LEFT MARGIN 0 TOP MARGIN 0 BOTTOM MARGIN 0 PAGE LENGTH 6

The following OUTPUT section directs the output from the INFORMIX-4GL report to the more utility.
OUTPUT REPORT TO PIPE "more"

Report Writing 5-11

LEFT MARGIN

LEFT MARGIN
Overview
This statement sets a left margin for a report.

Syntax
LEFT MARGIN integer

Explanation
LEFT MARGIN

are required keywords. is an integer that specifies the width of the left margin, in spaces.

integer

Notes
1. The default left margin is five spaces. 2. All columnar displacement indicated by the COLUMN function starts at the margin set by LEFT MARGIN.

Example
The following LEFT MARGIN statement instructs INFORMIX-4GL to print the left side of the report as far to the left as possible.
OUTPUT REPORT TO "label.out" LEFT MARGIN 0 TOP MARGIN 0 BOTTOM MARGIN 0 PAGE LENGTH 6

5-12

Report Writing

RIGHT MARGIN

RIGHT MARGIN
Overview
This statement sets a right margin for a report.

Syntax
RIGHT MARGIN integer

Explanation
RIGHT MARGIN

are required keywords. is an integer that specifies the width of the text on the page, in characters.

integer

Notes
1. The RIGHT MARGIN determines the right margin by specifying the width of the page, in characters. This is not dependent on the LEFT MARGIN, but always starts its count from the left edge of the page, so that the columns of the LEFT MARGIN are included in the value of RIGHT MARGIN. 2. The RIGHT MARGIN is effective only when the FORMAT section contains an EVERY ROW statement. 3. The default RIGHT MARGIN is 132 characters. 4. INFORMIX-4GL attempts to produce an EVERY ROW report by listing the variable names across the top of the page, and presenting the data in columns beneath these headings. If there is not sufficient room between the LEFT MARGIN and the RIGHT MARGIN to do this, INFORMIX-4GL produces a report that lists the variable names and the data of each row in two columns.

Report Writing

5-13

RIGHT MARGIN

Example
The following example demonstrates the use of the RIGHT MARGIN statement. After it processes the OUTPUT section, INFORMIX-4GL sets the right margin for the report at 70 characters.
REPORT simple(customer) DEFINE customer LIKE customer.* OUTPUT RIGHT MARGIN 70 FORMAT EVERY ROW END REPORT

5-14

Report Writing

TOP MARGIN

TOP MARGIN
Overview
This statement sets a top margin for a report.

Syntax
TOP MARGIN integer

Explanation
TOP MARGIN

are required keywords. is an integer that specifies the number of blank lines that INFORMIX-4GL leaves at the top of each page.

integer

Notes
1. The default top margin is three lines. 2. The top margin appears above any page header that you specify in the FORMAT section.

Example
The following TOP MARGIN statement instructs INFORMIX-4GL to begin printing at the top of each page.
OUTPUT REPORT TO "label.out" LEFT MARGIN 0 TOP MARGIN 0 BOTTOM MARGIN 0 PAGE LENGTH 6

Report Writing

5-15

BOTTOM MARGIN

BOTTOM MARGIN
Overview
This statement sets a bottom margin for a report.

Syntax
BOTTOM MARGIN integer

Explanation
BOTTOM MARGIN

are required keywords. is an integer that specifies the number of blank lines that INFORMIX-4GL is to leave at the bottom of each page.

integer

Notes
1. The default bottom margin is three lines. 2. The bottom margin appears below any page trailer.

Example
The following BOTTOM MARGIN statement instructs INFORMIX-4GL to continue printing to the bottom of each page.
OUTPUT REPORT TO "label.out" LEFT MARGIN 0 TOP MARGIN 0 BOTTOM MARGIN 0 PAGE LENGTH 6

5-16

Report Writing

PAGE LENGTH

PAGE LENGTH
Overview
This statement sets the number of lines on each page of a report.

Syntax
PAGE LENGTH integer

Explanation
PAGE LENGTH are required keywords.

integer

is an integer that specifies the length of the page, in lines.

Notes
1. The default page length is 66 lines. 2. The PAGE LENGTH includes both the TOP MARGIN and BOTTOM MARGIN.

Example
The following example includes a PAGE LENGTH statement:
OUTPUT PAGE LENGTH 22 TOP MARGIN 0 BOTTOM MARGIN 0

This example specifies that INFORMIX-4GL print each page with 22 lines. On a standard 24-line video screen, 22 lines is the maximum that you can use with the PAUSE statement without causing undesirable scrolling.

Report Writing

5-17

ORDER BY Section

ORDER BY Section
The optional ORDER BY section specifies variables on which to sort rows, and the order in which to process group control blocks in the FORMAT section. Its format is

Syntax
ORDER [ EXTERNAL ] BY sort-list

Explanation
ORDER BY EXTERNAL

are required keywords. is an optional keyword. is a list of one or more variables from the list of arguments to the REPORT routine.

sort-list

Notes
1. Include an ORDER BY section if your report uses group control blocks, and:

• You have not sorted the input rows. • You have already sorted the input rows, and you want to specify the
exact order in which the group control blocks are processed. (Without the ORDER BY section, INFORMIX-4GL chooses the order in which to process the group control blocks.) In this case, use the EXTERNAL keyword, so that the rows will not be sorted again. 2. The ORDER BY section specifies two things. First, it specifies the order in which INFORMIX-4GL orders the input rows. If sort-list contains a, b, and c in that order, then INFORMIX-4GL orders the input rows first by a. Within that ordering, INFORMIX-4GL orders the rows next by b. Finally, INFORMIX-4GL orders the resulting sets of rows by the values of variable c. Second, the ORDER BY section specifies the order in which INFORMIX-4GL processes group control blocks. (See the section “Control Blocks” later in this chapter for more information.) 3. The EXTERNAL keyword in the ORDER BY section specifies that the input rows are already sorted. INFORMIX-4GL does not resort the rows in this case.

5-18

Report Writing

ORDER BY Section

4. If there is an ORDER BY section without the EXTERNAL keyword, INFORMIX-4GL makes two passes through the input data. During the first pass, it sorts the data and stores it in a temporary file. During the second pass, it prints the report. If the input rows for your report come from the rows returned by only one cursor, you should use the ORDER BY clause in the SELECT statement associated with the cursor, and use the EXTERNAL keyword in the ORDER BY section of your report. 5. If you have just one variable named in group control blocks and the input rows are already sorted, then you do not need an ORDER BY section.

Example
REPORT r_invoice (c, stock_tot) DEFINE c RECORD LIKE customer.*, stock_tot SMALLINT ORDER BY stock_tot . . .

Report Writing

5-19

FORMAT Section

FORMAT Section
An INFORMIX-4GL REPORT routine must contain a FORMAT section. The FORMAT section determines what a report will look like. It works with the data that are passed to the routine through the argument list, or with data that you put in global variables for each row of the report. The FORMAT section begins with the FORMAT keyword, and ends with the END REPORT keywords. Two major types of FORMAT sections exist, both of which are described in the following sections. The simplest contains just one EVERY ROW statement between the FORMAT and END REPORT keywords. If you use an EVERY ROW statement, you cannot use any other statements or control blocks:

Syntax
FORMAT EVERY ROW END REPORT

More complex FORMAT sections can contain control blocks such as ON EVERY ROW and BEFORE GROUP OF. Each of these control blocks must contain at least one FORMAT statement such as PRINT or SKIP n LINES, and they can contain other statements. If you do not use an EVERY ROW statement, you can combine control blocks in any order within the FORMAT section. This type of non-default FORMAT section has the following structure:

Syntax
FORMAT [ PAGE HEADER control block ] [ PAGE TRAILER control block ] [ FIRST PAGE HEADER control block ] [ ON EVERY ROW control block ] [ ON LAST ROW control block ] [ BEFORE GROUP OF control block ...] [ AFTER GROUP OF control block ...] END REPORT

5-20

Report Writing

EVERY ROW

EVERY ROW
Overview
The EVERY ROW statement causes INFORMIX-4GL to output every row that you pass to the report. It uses a default format.

Syntax
EVERY ROW

Explanation
EVERY ROW

are required keywords.

Notes
1. The report consists of only the data that you pass to the routine through its arguments. 2. This statement is useful when you want to run a quick report using a default format. 3. The EVERY ROW statement stands by itself. You cannot modify it with any of the statements listed in the “Statements” section that appears later in this chapter. 4. When you use the EVERY ROW statement, you cannot use any control blocks in the FORMAT section. 5. A report generated by an EVERY ROW statement uses the variable names that you pass as arguments to the routine at run time as column headings. 6. If the variables passed as arguments fit on a line, INFORMIX-4GL produces a report with variable names across the top of each page; otherwise, it produces a report with the variable names down the left side of the page. 7. You can use the RIGHT MARGIN statement in the OUTPUT section to control the width of a report that uses the EVERY ROW statement. 8. To display every row in a format other than the default format, use the ON EVERY ROW control block (discussed in the “Control Blocks” section later in this chapter.)

Report Writing

5-21

EVERY ROW

Examples
This minimal REPORT routine uses the EVERY ROW statement:
REPORT minimal(customer) DEFINE customer RECORD LIKE customer.* FORMAT EVERY ROW END REPORT

Here is a portion of the output from the preceding default specification.
customer.customer_num customer.fname customer.lname customer.company customer.address1 customer.address2 customer.city customer.state customer.zipcode customer.phone customer.customer_num customer.fname customer.lname customer.company customer.address1 customer.address2 customer.city customer.state customer.zipcode customer.phone . . . INFORMIX-4GL prints only the column name when the column contains a NULL value. 101 Ludwig Pauli All Sports Supplies 213 Erstwild Court Sunnyvale CA 94086 408-789-8075 102 Carole Sadler Sports Spot 785 Geary St San Francisco CA 94117 415-822-1289

Following is another example of a brief report specification that uses the EVERY ROW statement. Assume that the cursor used to FETCH rows for this report was DECLAREd with an ORDER BY.
REPORT simple(order_num, customer_num, order_date) DEFINE order_num LIKE orders.order_num, customer_num LIKE orders.customer_num, order_date LIKE orders.order_date FORMAT EVERY ROW END REPORT

5-22

Report Writing

Control Blocks

The following display shows the output from the preceding REPORT routine.
order_num customer_num order_date 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 104 101 104 106 116 112 117 110 111 115 104 117 104 106 110 01/20/1989 06/01/1989 10/12/1989 04/12/1989 12/04/1989 09/19/1989 03/25/1989 11/17/1989 02/14/1989 05/29/1989 03/23/1989 06/05/1989 09/01/1989 05/01/1989 07/10/1989

Control Blocks
Control blocks provide the structure for a customized report. Each control block is optional but, if you do not use the EVERY ROW statement, you must include at least one control block in a REPORT routine. Each control block must include at least one statement. (See the “Statements” section later in this chapter.) When you use the BEFORE GROUP OF, AFTER GROUP OF, and ON EVERY ROW control blocks in a single REPORT routine, INFORMIX-4GL processes all BEFORE GROUP OF blocks before the ON EVERY ROW block and the ON EVERY ROW block before all AFTER GROUP OF blocks. The order in which INFORMIX-4GL processes the BEFORE GROUP OF control blocks and AFTER GROUP OF control blocks depends upon the hierarchy of variables listed in the ORDER BY section or, in the absence of an ORDER BY section, implied by the order of first mention of variables in either BEFORE or AFTER GROUP OF control blocks.

Report Writing

5-23

Control Blocks

Assume that the ORDER BY section orders by variables a, b, and c. Then the following display indicates the order by which INFORMIX-4GL processes control blocks:
BEFORE GROUP OF a BEFORE GROUP OF b BEFORE GROUP OF c ON EVERY ROW AFTER GROUP OF c AFTER GROUP OF b AFTER GROUP OF a Order of Group Processing

Figure 5-1

The pages that follow describe these control blocks in alphabetical order.

5-24

Report Writing

AFTER GROUP OF

AFTER GROUP OF
Overview
The AFTER GROUP OF control block specifies the action that INFORMIX-4GL takes after it processes a group of rows. Grouping is determined by the ordering that you did earlier.

Syntax
AFTER GROUP OF variable-name statement ...

Explanation
AFTER GROUP OF

are required keywords. is the name of one of the variables passed as an argument. is a FORMAT or INFORMIX-4GL statement.

variable-name statement

Notes
1. You must pass at least the value of variable-name through the arguments of the REPORT routine. 2. A group of rows is all rows that contain the same value for a given variable. INFORMIX-4GL automatically groups rows when you use an ORDER BY section in a REPORT routine, or the ORDER BY clause in a SELECT statement. That is, groups are formed when you order a list. When you specify more than one column in the ORDER BY section or clause, INFORMIX-4GL orders the rows first by the first variable that you specify (most significant). Rows having the same value on the first variable are then ordered by the second variable that you specify, and so on, until rows having the same value on all variables but the last are ordered by the last (least significant) variable that you specify.
INFORMIX-4GL processes the statements in an AFTER GROUP OF control block each time the specified column changes value, each time a more significant column changes value, and at the end of a report. (See Figure 5-1 at the beginning of the “Control Blocks” section.)

Report Writing

5-25

AFTER GROUP OF

3. You can have one AFTER GROUP OF control block for each variable on which you have ordered the data. 4. If you have an ORDER BY section and you have more than one AFTER GROUP OF control block, their order within the FORMAT section is not significant. 5. When INFORMIX-4GL finishes generating a report, it executes all of the statements in the AFTER GROUP OF control blocks before it executes those in the ON LAST ROW control block. 6. Group aggregates can be used only in AFTER GROUP OF control blocks. You cannot use group aggregates in any other type of control block. 7. When INFORMIX-4GL processes the statements in an AFTER GROUP OF control block, the variables of the report still have the values from the last row of the group. From this perspective, the AFTER GROUP OF control block could be called the ‘‘on last row of group’’ control block.

Examples
AFTER GROUP OF r.order_num PRINT " ",r.order_date,7 SPACES, r.order_num USING "###&", 8 SPACES,r.ship_date," ", GROUP SUM(r.total_price) USING "$$$$,$$$,$$$.&&" AFTER GROUP OF r.customer_num PRINT 42 SPACES,"---------------" PRINT 42 SPACES,GROUP SUM(r.total_price) USING "$$$$,$$$,$$$.&&"

5-26

Report Writing

BEFORE GROUP OF

BEFORE GROUP OF
Overview
The BEFORE GROUP OF control block specifies the action that INFORMIX-4GL takes before it processes a group of rows. Grouping is determined by the ordering that you did earlier.

Syntax
BEFORE GROUP OF variable-name statement ...

Explanation
BEFORE GROUP OF

are required keywords. is the name of one of the variables passed as an argument. is an INFORMIX-4GL or FORMAT statement.

variable-name statement

Notes
1. You must pass at least the value of variable-name through the arguments of the REPORT routine. 2. A group of rows is all rows that contain the same value for a given variable. INFORMIX-4GL automatically groups rows when you use an ORDER BY section of a REPORT routine or the ORDER clause of a SELECT statement. That is, groups are formed when you order a list. When you specify more than one variable in an ORDER BY section or clause, INFORMIX-4GL orders the rows first by the first variable that you specify (most significant), second by the second variable, and so on, until the last variable that you specify (least significant) is ordered.
INFORMIX-4GL processes the statements in a BEFORE GROUP OF control block at the start of a report, each time the specified variable changes value, and each time a more significant variable changes value. (See Figure 5-1 at the beginning of the “Control Blocks” section.)

3. You can have one BEFORE GROUP OF control block for each variable that you order.
Report Writing 5-27

BEFORE GROUP OF

4. If you have an ORDER BY section and you have more than one BEFORE GROUP OF control block, their order within the FORMAT section is not significant. 5. When INFORMIX-4GL starts to generate a report, it executes all the statements in the BEFORE GROUP OF control blocks before it executes those in the ON EVERY ROW control block. 6. You can use a SKIP TO TOP OF PAGE statement in a BEFORE GROUP OF control block to cause each group to start at the top of a page. 7. When INFORMIX-4GL processes the statements in a BEFORE GROUP OF control block, the report variables have the values from the first row of the new group. From this perspective, the BEFORE GROUP OF control block could be called the ‘‘on first row of group’’ control block.

Example
BEFORE GROUP OF r.customer_num SKIP TO TOP OF PAGE

5-28

Report Writing

FIRST PAGE HEADER

FIRST PAGE HEADER
Overview
The FIRST PAGE HEADER control block can specify what information appears at the top of the first page of the report.

Syntax
FIRST PAGE HEADER statement ...

Explanation
FIRST PAGE HEADER

are required keywords. is an INFORMIX-4GL or FORMAT statement.

statement

Notes
1. The TOP MARGIN (set in the OUTPUT section) affects how close to the top of the page INFORMIX-4GL displays the header. 2. The FIRST PAGE HEADER control block overrides a PAGE HEADER control block on the first page of a report. 3. You cannot use the SKIP TO TOP OF PAGE statement in a FIRST PAGE HEADER control block. 4. If you use an IF THEN ELSE statement in a FIRST PAGE HEADER control block, the number of lines displayed by the PRINT statements following the THEN keyword must be equal to the number of lines displayed by the PRINT statements following the ELSE keyword. 5. You cannot use the PRINT filename statement to read and display text from a file in a FIRST PAGE HEADER control block. 6. You can use a FIRST PAGE HEADER control block to produce a title page, as well as column headings.

Report Writing

5-29

FIRST PAGE HEADER

Example
This example is from a report that produces multiple labels across the page.
FIRST PAGE HEADER {Nothing is displayed in this control block. It just initializes variables that are used in the ON EVERY ROW control block.} {Initialize label counter.} LET i = 1 {Determine label width (allow eight spaces total between labels).} LET l_size = 72/count1 {Divide the eight spaces between the number of labels across the page.} LET white = 8/count1

This FIRST PAGE HEADER does not display any information. Because INFORMIX-4GL executes the FIRST PAGE HEADER control block before it generates any output, you can use this control block to initialize variables that you use in the FORMAT section.

5-30

Report Writing

ON EVERY ROW

ON EVERY ROW
Overview
The ON EVERY ROW control block specifies the action to be taken by INFORMIX-4GL for every row of data that you pass to the routine.

Syntax
ON EVERY ROW statement ...

Explanation
ON EVERY ROW

are required keywords. is an INFORMIX-4GL or FORMAT statement.

statement

Notes
1. INFORMIX-4GL processes the statements in an ON EVERY ROW control block as each new row is formatted. 2. If a BEFORE GROUP OF control block is triggered by a change in column value, all appropriate BEFORE GROUP OF control blocks are executed (in the order of their significance) before the ON EVERY ROW control block is executed. 3. If an AFTER GROUP OF control block is triggered by a change in column value, all appropriate AFTER GROUP OF control blocks are executed (in the reverse order of their significance) after the ON EVERY ROW control block is executed.

Examples
The following example is from a report that lists all the customers, their addresses, and their telephone numbers across the page.
ON EVERY ROW PRINT customer_num USING "####", COLUMN 12, fname CLIPPED, 1 SPACE, lname CLIPPED, COLUMN 35, city CLIPPED, ", " , state, COLUMN 57, zipcode, COLUMN 65, phone Report Writing 5-31

ON EVERY ROW

The next example is from a mailing label report.
ON EVERY ROW IF (city IS NOT NULL) AND (state IS NOT NULL) THEN PRINT fname CLIPPED, 1 SPACE, lname PRINT company PRINT address1 IF (address2 IS NOT NULL) THEN PRINT address2 PRINT city CLIPPED ", " , state, 2 SPACES, zipcode SKIP TO TOP OF PAGE END IF

5-32

Report Writing

ON LAST ROW

ON LAST ROW
Overview
The ON LAST ROW control block specifies the action that INFORMIX-4GL is to take after it processes the last row passed to the REPORT routine and encounters the FINISH REPORT statement.

Syntax
ON LAST ROW statement ...

Explanation
ON LAST ROW are required keywords.

statement

is an INFORMIX-4GL or FORMAT statement.

Notes
1. INFORMIX-4GL executes the statements in the ON LAST ROW control block after it executes those in the ON EVERY ROW and AFTER GROUP OF control blocks. 2. When INFORMIX-4GL processes the statements in an ON LAST ROW control block, the columns that the report is processing still have the values from the final row that the report processed. 3. The ON LAST ROW control block can display report totals.

Example
ON LAST ROW SKIP 1 LINE PRINT COLUMN 12, "TOTAL NUMBER OF CUSTOMERS:", COLUMN 57, COUNT(*) USING "##"

Report Writing

5-33

PAGE HEADER

PAGE HEADER
Overview
The PAGE HEADER control block specifies what information (if any) appears at the top of each page of the report.

Syntax
PAGE HEADER statement ...

Explanation
PAGE HEADER are required keywords.

statement

is an INFORMIX-4GL or FORMAT statement.

Notes
1. The TOP MARGIN (in the OUTPUT section) affects how close to the top of the page INFORMIX-4GL displays the page header. 2. The FIRST PAGE HEADER control block overrides a PAGE HEADER control block on the first page of a report. 3. You cannot use the SKIP TO TOP OF PAGE statement in a PAGE HEADER control block. 4. The number of lines produced by the PAGE HEADER control block cannot change from page to page, and must be expressed unambiguously. The following rules are special cases of this general principle:

• You cannot have a SKIP integer LINES statement inside a loop in the
PAGE HEADER control block.

• You cannot use a NEED statement in the PAGE HEADER control block. • If you use an IF THEN ELSE statement in a PAGE HEADER control
block, the number of lines displayed by the PRINT statements following the THEN keyword must be equal to the number of lines displayed by the PRINT statements following the ELSE keyword.

• If you use a CASE, FOR, or WHILE statement that contains a PRINT
statement in a PAGE HEADER control block, you must terminate the print statement with a semicolon. The semicolon suppresses RETURNs
5-34 Report Writing

PAGE HEADER

in the loop, keeping the number of lines in the header constant from page to page.

• You cannot use a PRINT filename statement to read and display text
from a file in a PAGE HEADER control block. 5. You can use a PAGE HEADER control block to display column headings in a report. 6. You can use the PAGENO expression in a PRINT statement within a PAGE HEADER control block to display the page number automatically at the top of every page.

Example
The following example produces the column headings for printing the customer data across the page.
PAGE HEADER PRINT "NUMBER", COLUMN 12, "NAME", COLUMN 35, "LOCATION", COLUMN 57, "ZIP", COLUMN 65, "PHONE" SKIP 1 LINE

Report Writing

5-35

PAGE TRAILER

PAGE TRAILER
Overview
The PAGE TRAILER control block specifies what information, if any, appears at the bottom of each page of the report.

Syntax
PAGE TRAILER statement ...

Explanation
PAGE TRAILER are required keywords.

statement

is an INFORMIX-4GL or FORMAT statement.

Notes
1. The BOTTOM MARGIN (in the OUTPUT section) affects how close to the bottom of the page INFORMIX-4GL displays the page trailer. 2. You cannot use the SKIP TO TOP OF PAGE statement in a PAGE TRAILER control block. 3. The number of lines produced by the PAGE TRAILER control block cannot change from page to page and must be unambiguously expressed. The following rules are special cases of this more general principle:

• You cannot have a SKIP integer LINES statement inside a loop in the
PAGE TRAILER control block.

• You cannot use a NEED statement in the PAGE TRAILER control block. • If you use an IF THEN ELSE statement in a PAGE TRAILER control
block, the number of lines displayed by the PRINT statements following the THEN keyword must be equal to the number of lines displayed by the PRINT statements following the ELSE keyword.

• If you use a CASE, FOR, or WHILE statement that contains a PRINT
statement in a PAGE TRAILER control block, you must terminate the PRINT statement with a semicolon. The semicolon suppresses

5-36

Report Writing

Statements

RETURNs in the loop, keeping the number of lines in the header con-

stant from page to page.

• You cannot use a PRINT filename statement to read and display text
from a file in a PAGE TRAILER control block. 4. INFORMIX-4GL executes the PAGE TRAILER control block before the PAGE HEADER control block when you issue a SKIP TO TOP OF PAGE statement anywhere. 5. You can use the PAGENO expression in a PRINT statement within a PAGE TRAILER control block to display the page number automatically at the bottom of every page.

Example
PAGE TRAILER PRINT COLUMN 28, PAGENO USING "page <<<<"

Statements
The control blocks determine when INFORMIX-4GL takes an action in a report, while the statements determine what action INFORMIX-4GL takes. You can use any INFORMIX-4GL statement in a control block, as well as a number of statements that can be used only in the FORMAT section of a REPORT routine.

Standard 4GL Statements
The most common INFORMIX-4GL statements used in the control blocks of reports are FOR, IF, LET, and WHILE. These statements have the same syntax that they have elsewhere in 4GL applications, as described in Chapter 7. (Remember that any local variables referenced in such statements must be specified in the DEFINE section of the REPORT routine.)

Statements Valid Only in the FORMAT Section
There are five statements that you can only use in the FORMAT section of a REPORT routine:
NEED PAUSE PRINT PRINT FILE SKIP

Descriptions of these FORMAT section statements follow.
Report Writing 5-37

NEED

NEED
Overview
This statement causes subsequent display to start on the next page if there is not the specified number of lines remaining on the current page.

Syntax
NEED num-expr LINES

Explanation
NEED

is a required keyword. is an expression that evaluates to an integer specifying the number of lines needed. is a required keyword.

num-expr
LINES

Notes
1. The NEED statement can prevent INFORMIX-4GL from splitting parts of the report that you want to keep together on a single page. 2. INFORMIX-4GL does not include the BOTTOM MARGIN value in the number of lines counted. 3. If INFORMIX-4GL triggers the NEED statement in printing a report, it prints both the PAGE TRAILER and the PAGE HEADER. 4. You cannot use this statement in PAGE HEADER or PAGE TRAILER control blocks.

Example
NEED 6 LINES

5-38

Report Writing

PAUSE

PAUSE
Overview
This statement causes output to the terminal to pause until the user presses RETURN.

Syntax
PAUSE [ "string" ]

Explanation
PAUSE

is a required keyword. is a quoted message that PAUSE displays. If you do not supply a message, PAUSE displays no message.

string

Notes
The PAUSE statement works only if the report goes to the screen. It has no effect if you include a REPORT TO clause in the OUTPUT section, or a TO clause in the START REPORT statement.

Example
The following example causes INFORMIX-4GL to pause while running the report.
AFTER GROUP OF item_num . . . SKIP TO TOP OF PAGE PAUSE "Press RETURN to continue"

Report Writing

5-39

PRINT

PRINT
Overview
This statement displays information, as specified in the OUTPUT section.

Syntax
PRINT [ exprlist ] [ ; ]

Explanation
PRINT

is a required keyword. is an optional list of one or more expressions, separated by commas. is an optional symbol that suppresses a RETURN at the end of the line.

exprlist ;

Notes
1. One PRINT statement displays its output on one line, no matter how many lines the statement occupies in the report specification, unless the exprlist includes the WORDWRAP function. 2. When a PRINT statement specifies WORDWRAP, it can also specify a temporary right margin. The character position of the current column becomes the temporary left margin, and the contents of the character string are then displayed on as many lines as necessary between these temporary margins. After the PRINT statement with WORDWRAP has executed, any explicit or default margins from the OUTPUT section are restored. 3. Unless you use the keyword CLIPPED or USING following an expression, INFORMIX-4GL displays variables with a width that depends on their data type, as shown in Figure 5-2.

5-40

Report Writing

PRINT

Data Type CHAR DATE DATETIME INTERVAL FLOAT SMALLINT INTEGER SMALLFLOAT DECIMAL SERIAL MONEY Figure 5-2

Default Size (in characters) declared size 10 depends on declared precision depends on declared precision (including sign) 14 (including sign and decimal point) 6 (including sign) 11 (including sign) 14 (including sign and decimal point) number of digits plus 2 (including sign and decimal point) 11 number of digits plus 3 (including sign, decimal point, and currency symbol) Default Display Widths

Examples
The following example is from a mailing label report:
FORMAT ON EVERY ROW PRINT fname, lname PRINT company PRINT address1 PRINT address2 PRINT city, ", " , state, 2 SPACES, zipcode SKIP 2 LINES

The following example is from a report that prints the customer list.
FIRST PAGE HEADER PRINT COLUMN 30, "CUSTOMER LIST" SKIP 2 LINES PRINT "Listings for the State of ", thisstate SKIP 2 LINES PRINT "NUMBER", COLUMN 12, "NAME", COLUMN 35, "LOCATION", COLUMN 57, "ZIP", COLUMN 65, "PHONE" SKIP 1 LINE PAGE HEADER PRINT "NUMBER", COLUMN 12, "NAME", COLUMN 35, "LOCATION", COLUMN 57, "ZIP", COLUMN 65, "PHONE" SKIP 1 LINE ON EVERY ROW PRINT customer_num USING "####", COLUMN 12, fname CLIPPED, 1 SPACE, lname CLIPPED, COLUMN 35, city CLIPPED, ", " , state, COLUMN 57, zipcode, COLUMN 65, phone

Report Writing

5-41

PRINT FILE

PRINT FILE
Overview
This statement displays the contents of a text file in a report.

Syntax
PRINT FILE "filename"

Explanation
PRINT FILE

are required keywords. is a required filename that can be a pathname. You must enclose filename in quotation ( " ) marks.

filename

Note
You can use the PRINT FILE statement to include the body of a form letter in a report that generates custom letters.

Example
PRINT FILE "/u/claire/occupant.let"

5-42

Report Writing

SKIP

SKIP
Overview
This statement skips lines in a report or skips to the top of the next page.

Syntax
SKIP { integer LINE[S] | TO TOP OF PAGE }

Explanation
SKIP

is a required keyword. is an integer specifying the number of lines to skip. is an optional keyword. You can use the keyword LINE in place of LINES if you like. are optional keywords.

integer
LINES TO TOP OF PAGE

Notes
1. You cannot use a SKIP LINES statement inside a CASE, FOR, or WHILE statement. 2. You cannot use a SKIP TO TOP OF PAGE statement in a FIRST PAGE HEADER, PAGE HEADER, or PAGE TRAILER control block.

Report Writing

5-43

Expressions and Built-in Functions

Examples
The following example is from a report that prints the customer list.
FIRST PAGE HEADER PRINT COLUMN 30, "CUSTOMER LIST" SKIP 2 LINES PRINT "Listings for the State of ", thisstate SKIP 2 LINES PRINT "NUMBER", COLUMN 12, "NAME", COLUMN 35, "LOCATION", COLUMN 57, "ZIP", COLUMN 65, "PHONE" SKIP 1 LINE PAGE HEADER PRINT "NUMBER", COLUMN 12, "NAME", COLUMN 35, "LOCATION", COLUMN 57, "ZIP", COLUMN 65, "PHONE" SKIP 1 LINE ON EVERY ROW PRINT customer_num USING "####", COLUMN 12, fname CLIPPED, 1 SPACE, lname CLIPPED, COLUMN 35, city CLIPPED, ", " , state, COLUMN 57, zipcode, COLUMN 65, phone

The next example is from a mailing label report.
FORMAT ON EVERY ROW IF (city IS NOT NULL) AND (state IS NOT NULL) THEN PRINT fname CLIPPED, 1 SPACE, lname PRINT company PRINT address1 IF (address2 IS NOT NULL) THEN PRINT address2 PRINT city CLIPPED, ", " , state, 2 SPACES, zipcode SKIP TO TOP OF PAGE END IF

Expressions and Built-in Functions
Expressions used within REPORT routines have the same syntax as expressions used elsewhere in INFORMIX-4GL. These expressions can include the built-in functions that are described in Chapter 2. You can also use the 4GL aggregate functions. In REPORT routines, these aggregates have effects that are slightly different from when they are used in a SELECT statement. The differences are described in the next pages.

5-44

Report Writing

Expressions and Built-in Functions

There are also built-in functions that you can use only in a REPORT routine. The following table lists all the functions that you can use in a REPORT routine. (The letter superscripts indicate where their descriptions appear in this manual.)
ASCIIa AVG()rs CLIPPEDa COLUMNa COUNT(*)rs CURRENTa DATEa DATE()a DAY()a EXTEND()a GROUPr LENGTH()a LINENOr MAX()rs MIN()rs MDY()a MONTH()a PAGENOr PERCENT(*)rs SPACESr SUM()rs TIMEa TODAYa UNITSa USINGa WEEKDAY()a WORDWRAPr YEAR()a

r rs

You can use these functions only within the FORMAT section of a REPORT routine. A description of these functions follows. You can use these functions only within the FORMAT section of a REPORT routine or in INSERT, SELECT, or UPDATE statements elsewhere. They are described both in the following pages and in Chapter 7. These functions are described in Chapter 2.

a

Report Writing

5-45

Aggregates

Aggregates
Overview
Aggregate functions can summarize information in a report.

Syntax
[ GROUP ] { COUNT ( * ) | PERCENT ( * ) | { SUM | AVG | MIN | MAX } ( expr1 ) } [ WHERE expr2 ]

Explanation
GROUP

is an optional keyword that causes the aggregate to reflect information for a specific group only. You can only use this keyword in an AFTER GROUP OF control block. is a keyword. This keyword is always evaluated as the total number of rows qualified by the optional WHERE clause. is the keyword that evaluates COUNT as a percent of the total number of rows in the report. evaluates as the total of expr1 in the rows qualified by the optional WHERE clause. SUM ignores rows with NULL value for expr1; it returns NULL if all rows have a NULL value for expr1. evaluates as the average of expr1 in the rows qualified by the optional WHERE clause. AVG ignores rows with NULL value for expr1; it returns NULL if all rows have a NULL value for expr1. evaluates as the minimum of expr1 in the rows qualified by the optional WHERE clause. MIN ignores rows with NULL value for expr1; it returns NULL if all rows have a NULL value for expr1. evaluates as the maximum of expr1 in the rows qualified by the optional WHERE clause. MAX ignores rows with NULL value for expr1; it returns NULL if all rows have a NULL value for expr1. is the expression that SUM, AVG, MIN, or MAX evaluate. It is typically a numeric variable or a numeric expression that includes a numeric variable.

COUNT ( * ) PERCENT ( * ) SUM

AVG

MIN

MAX

expr1

5-46

Report Writing

Aggregates

WHERE

is an optional keyword. is a Boolean expression that qualifies the aggregate.

expr2

Note
The WHERE clause allows you to select among the rows passed to the report. (See “The SELECT Statement” in Chapter 7 for the syntax of the WHERE clause. See also the section “Boolean Expressions” in Chapter 2.)

Examples
This fragment of a REPORT statement uses the AFTER GROUP OF control block and GROUP keyword to sum items within each order. The last PRINT statement calculates the total price of each order, then adds a shipping charge, and prints the result.
ON EVERY ROW PRINT snum USING "###", COLUMN 10, manu_code, COLUMN 18, description CLIPPED, COLUMN 38, quantity USING "###", COLUMN 43, unit_price USING "$$$$.&&", COLUMN 55, total_price USING "$$,$$$,$$$.&&" AFTER GROUP OF number SKIP 1 LINE PRINT 4 SPACES, "Shipping charges for the order: ", ship_charge USING "$$$$.&&" PRINT 4 SPACES, "Count of small orders: ", count(*) WHERE total_price < 200.00 USING "##,###" SKIP 1 LINE PRINT 5 SPACES, "Total amount for the order: ", ship_charge + GROUP SUM(total_price) USING "$$,$$$,$$$.&&"

Since no WHERE clause is specified, GROUP SUM combines the total_price of every item in the group comprising the order.

Report Writing

5-47

LINENO

LINENO
Overview
This expression has the value of the line number of the report line that INFORMIX-4GL is currently printing.

Syntax
LINENO

Explanation
LINENO

is a required keyword.

Note
INFORMIX-4GL computes the current line number by calculating the number of lines from the top of the page, including the TOP MARGIN.

Example
PRINT COLUMN 10, LINENO USING "Line <<<"

5-48

Report Writing

PAGENO

PAGENO
Overview
This expression has the value of the page number of the page that INFORMIX-4GL is currently printing.

Syntax
PAGENO

Explanation
PAGENO is a required keyword.

Note
You can use PAGENO in a PRINT statement in the PAGE HEADER or PAGE TRAILER control block to number the pages of a report. (You can also use PAGENO in other control blocks.)

Example
PAGE TRAILER PRINT COLUMN 28, PAGENO USING "page <<<<"

Report Writing

5-49

SPACES

SPACES
Overview
This function returns a string of spaces. It is identical to a quoted string of spaces.

Syntax
num-expr SPACE[S]

Explanation
num-expr is a number expression.
SPACES

is a required keyword. You can use the keyword SPACE in place of SPACES if you like.

Example
The following example is from a mailing label report.
FORMAT ON EVERY ROW PRINT fname, lname PRINT company PRINT address1 PRINT address2 PRINT city, ", " , state, 2 SPACES, zipcode SKIP 2 LINES

5-50

Report Writing

WORDWRAP

WORDWRAP
Overview
The WORDWRAP function automatically wraps successive segments of long character strings to the next line of a report. If the string is too long to fit in the current line, lines are broken between words at temporary left and right margins.

Syntax
char-expr WORDWRAP [ RIGHT MARGIN col ]

Explanation
char-expr
WORDWRAP

is an expression whose value is a character string. is a keyword to display long character strings on multiple lines of a report. are optional keywords to specify a temporary right margin. is an integer expression, specifying the column number of the temporary right margin.

RIGHT MARGIN col

Notes
1. The char-expr can include printable ASCII characters, and the TAB (ASCII 9), NEWLINE (ASCII 10), and RETURN (ASCII 13). A line break is forced wherever char-expr contains a NEWLINE, a RETURN, or a NEWLINE/ RETURN pair. 2. If you specify WORDWRAP RIGHT MARGIN in a report, the value of col overrides the specified or default right margin, until all of char-expr has been included in the report. 3. If you do not specify RIGHT MARGIN, the specified or default right margin of the report remains in effect. 4. The left margin is the current printing column. The contents of char-expr are displayed on as many lines as necessary between the temporary left and right margins. 5. When displaying text with WORDWRAP, INFORMIX-4GL starts a new line when a word plus the following space will not fit on the current line,
Report Writing 5-51

WORDWRAP

thereby assuring an even left margin when all words are separated by a single space. When a string of spaces will not fit on a line, INFORMIX-4GL prints enough of the spaces to fill the line, starts a new line, and prints the rest of the spaces. INFORMIX-4GL expands a TAB down to enough spaces to reach the next TAB stop. When the next TAB stop is past the right margin, INFORMIX-4GL expands just to the right margin, starts a new line, and fetches the next word. 6. INFORMIX-4GL will maintain page discipline while printing data with the WORDWRAP utility; it will print page footers, page trailers, page numbers, and page headers.

Examples
The following PRINT statement specifies a left margin in column 10 and a temporary right margin in column 70 to display the character string that is stored in the variable called mynovel:
print column 10, mynovel WORDWRAP RIGHT MARGIN 70

If the data string is too long to fit in the first line, successive segments are displayed in successive lines, until the last character of the string is displayed. Note: INFORMIX-OnLine supports additional data types. Refer to the INFORMIX-OnLine Programmer’s Manual for more information

5-52

Report Writing

Chapter

4GL Function Library
Chapter Overview 3 The 4GL Library Functions ARG_VAL 4 ARR_COUNT 6 ARR_CURR 7 DOWNSHIFT 9 ERR_GET 10 ERR_PRINT 11 ERR_QUIT 12 ERRORLOG 13 INFIELD 14 LENGTH 16 NUM_ARGS 17 SCR_LINE 18 SET_COUNT 20 SHOWHELP 21 STARTLOG 23 UPSHIFT 25 3

6

6-2

4GL Function Library

Chapter Overview
This chapter describes the INFORMIX-4GL library functions. You can include any of these functions in your 4GL source code. The 4GL compiler recognizes the name of the library function and automatically includes the function in your final program. See also the section “Expressions and Built-in Functions” near the end of Chapter 5 for a list of additional functions that you can include in 4GL programs.

The 4GL Library Functions
You cannot include a library function in an SQL statement. You must use the CALL statement to invoke a library function, unless its action returns a single value. The functions marked with an asterisk ( * ) in the following list can only be used in CALL statements. The functions listed without an asterisk can be used without CALL in 4GL expressions or in assignment statements.
Function arg_val arr_count arr_curr downshift err_get err_print err_quit errorlog infield length num_args scr_line set_count showhelp startlog upshift Returned Value or Effect Command-line argument(s) Total filled rows of program array Number of the current row within program array Lowers case of uppercase letters in string argument Current 4GL error message Prints a 4GL error message on the Error line Prints a 4GL error message and exits Appends argument to the error log TRUE if argument is the name of the current field Length in bytes of string argument Number of command-line arguments Number of the current row within screen array Sets number of rows of program array Displays the 4GL HELP Menu and a help message Opens an error log file Raises case of lowercase letters in string argument

* * *

* * *

The pages that follow describe these functions in alphabetical order.

ARG_VAL

ARG_VAL
Overview
The arg_val function returns an argument of the command line that executes your INFORMIX-4GL application program.

Syntax
arg_val ( expr )

Explanation
expr is an integer expression.

Notes
1. You can design your 4GL program to expect or allow arguments after the name of the program in the command line. Use the arg_val function to retrieve individual arguments during program execution. The num_args function can determine how many arguments followed the program name on the command line. The arg_val and num_args functions allow you to pass data to a compiled 4GL program from the command line that executes the program. 2. The function arg_val(n) returns the nth command-line argument as a CHAR variable. 3. The value of expr must be between 0 and the value returned by num_args, which is the number of command-line arguments. The value returned by arg_val(0) is the name of your 4GL application program.

Examples
Suppose that your 4GL program called myprog can accept one or more usernames as command-line arguments. Each of the following command lines includes four arguments: myprog.4ge joe bob sue les (C Compiler Version) fglgo myprog joe bob sue les (Rapid Development System)

6-4

4GL Function Library

ARG_VAL

In either case, statements in the following program fragment use the arg_val function to store in an array of CHAR variables all the names that the user entered as command-line arguments:
. . . DEFINE args ARRAY[8] OF CHAR(10), i SMALLINT . . . FOR i = 1 TO num_args() LET args[i] = arg_val(i) END FOR . . .

After the command-line arguments listed above, the num_args function returns the value 4. Executing the LET statements in the FOR loop assigns the following values to elements of the args array:
Variable args[1] args[2] args[3] args[4] Value joe bob sue les

Related Function
NUM_ARGS

4GL Function Library

6-5

ARR_COUNT

ARR_COUNT
Overview
The arr_count function returns the number of rows that are entered in a program array during or after an INPUT ARRAY statement.

Syntax
arr_count ( )

Notes
You can use arr_count to record the number of rows that are currently stored in a program array. The arr_count function returns an integer value.

Example
The following function uses the value returned by arr_count to set the upper limit of a FOR statement:
FUNCTION insert_items() DEFINE counter SMALLINT FOR counter = 1 TO arr_count() INSERT INTO items VALUES (p_items[counter].item_num, p_orders.order_num, p_items[counter].stock_num, p_items[counter].manu_code, p_items[counter].quantity, p_items[counter].total_price) END FOR END FUNCTION

Related Functions
ARR_CURR, SCR_LINE

6-6

4GL Function Library

ARR_CURR

ARR_CURR
Overview
The arr_curr function returns the number of the row within the program array that corresponds to the current screen array row, during or immediately after the INPUT ARRAY or DISPLAY ARRAY statement.

Syntax
arr_curr ( )

Notes
1. The current screen row is the row where the cursor is located at the beginning of a BEFORE ROW or AFTER ROW clause. 2. The arr_curr function returns an integer value. The first row of both the program array and the screen array is numbered 1. 3. The library functions arr_curr and scr_line can return different values if the program array is larger than the screen array.

4GL Function Library

6-7

ARR_CURR

Example
The following program segment tests the user input and rejects it if the customer is not from California. (See also the definition of the scr_line function later in this chapter.)
DEFINE p_array ARRAY[90] OF RECORD fname CHAR(15), lname CHAR(15), state CHAR(2) END RECORD, pa_curr, sc_curr SMALLINT INPUT ARRAY p_array FROM scr_array.* AFTER FIELD state LET pa_curr = arr_curr() LET sc_curr = scr_line() IF upshift(p_array[pa_curr].state) != "CA" THEN ERROR "Customers must be from California" INITIALIZE p_array[pa_curr].* TO NULL CLEAR scr_array[sc_curr].* NEXT FIELD fname END IF END INPUT

Related Functions
ARR_COUNT, SCR_LINE

6-8

4GL Function Library

DOWNSHIFT

DOWNSHIFT
Overview
The downshift function returns a string value in which all uppercase characters in its argument are converted to lowercase.

Syntax
downshift ( str )

Explanation
str is a quoted string or a variable of type CHAR.

Notes
1. Non-alphabetic characters in str are not altered by downshift. 2. You can use the downshift function in an expression (when such usage is allowed), or you can assign the value returned by the function to a variable. 3. The maximum length of str is 512 characters. 4. See also the DOWNSHIFT field attribute in Chapter 4.

Example
Suppose that the CHAR value ‘‘GEAR_4’’ is stored in the program variable p_string. The following statement takes the value of the expression downshift(p_string), namely gear_4, and assigns it to another CHAR variable called d_str:
LET d_str = downshift(p_string)

Related Function
UPSHIFT

4GL Function Library

6-9

ERR_GET

ERR_GET
Overview
The err_get function returns a CHAR string that is the 4GL error message corresponding to its argument.

Syntax
err_get ( expr )

Explanation
expr is an integer expression.

Notes
1. The expr is usually the global status variable. 2. The err_get function is most useful when you are developing a program. The message that it returns is probably not helpful to the user of your application.

Example
The LET statement in this segment assigns the text of a 4GL error message to errtext, a CHAR variable:
IF status < 0 THEN LET errtext = err_get(status) END IF

Related Functions
ERR_PRINT, ERR_QUIT, STARTLOG

6-10

4GL Function Library

ERR_PRINT

ERR_PRINT
Overview
The err_print function displays on the Error line the INFORMIX-4GL error message that corresponds to its argument.

Syntax
CALL err_print ( expr )

Explanation
expr is an integer expression.

Notes
1. The expr is usually the global status variable. 2. The err_print function is most useful when you are developing a program. The message that it returns is probably not helpful to the user of your application.

Example
This program segment sends any error message to the Error line:
IF status < 0 THEN CALL err_print(status) END IF

Related Functions
ERR_GET, ERR_QUIT, STARTLOG

4GL Function Library

6-11

ERR_QUIT

ERR_QUIT
Overview
The err_quit function prints on the Error line the INFORMIX-4GL error message specified by its argument, and then terminates the program.

Syntax
CALL err_quit ( expr )

Explanation
CALL

is a required keyword. is an integer expression.

expr

Notes
1. The expr is usually the global status variable. 2. The err_quit function is most useful when you are developing a program. The message that it returns is probably not helpful to the user of your application.

Example
If an error occurs, these statements display the error message on the Error line, and then terminate program execution:
IF status < 0 THEN CALL err_quit(status) END IF

Related Functions
ERR_GET, ERR_PRINT, STARTLOG

6-12

4GL Function Library

ERRORLOG

ERRORLOG
Overview
The errorlog function writes its argument in the current error log file.

Syntax
CALL errorlog ( str )

Explanation
CALL

is a required keyword. is a string constant or a CHAR variable.

str

Notes
1. The error log file is created by the startlog function. 2. You can use the errorlog function to identify errors in programs that you are developing and to customize error handling.

Example
Here the errorlog function has a string constant argument:
CALL startlog("/usr/steve/error.log") ... FUNCTION start_menu() CALL errorlog("Entering start_menu function")

Related Function
STARTLOG

4GL Function Library

6-13

INFIELD

INFIELD
Overview
The infield function tests whether its argument is the identifier of the current screen field.

Syntax
infield ( field-name )

Explanation
field-name is the name of a screen field.

Notes
1. The infield function is a Boolean function that returns the value true if field-name is the name of the current screen field. Otherwise infield returns the value false. (The “ATTRIBUTES Section” in Chapter 4 describes how to assign a field-name to a display field of a screen form.) 2. You can use infield during an INPUT or INPUT ARRAY statement to take field-dependent actions. 3. Outside of an INPUT or INPUT ARRAY statement, infield returns a true or false value, based on whether field-name corresponds to the screen field that was current when the user terminated the most recent INPUT or INPUT ARRAY statement. Be sure to specify the field-name, not the field tag. 4. If the current field is a multiple-column field, infield returns true only if field-name is the active name.

6-14

4GL Function Library

INFIELD

Example
The following INPUT statement uses infield with showhelp to give fielddependent help messages.
INPUT p_rec.* FROM sc_rec.* ON KEY(CONTROL-B) CASE WHEN infield(field1) CALL showhelp(101) WHEN infield(field2) CALL showhelp(102) WHEN infield(field3) CALL showhelp(103) ... END CASE END INPUT

Related Function
SCR_LINE

4GL Function Library

6-15

LENGTH

LENGTH
Overview
The length function returns the number of bytes in its string argument, after deleting all trailing spaces.

Syntax
length ( str )

Explanation
str is a string constant or a CHAR variable.

Note
In a SELECT statement, with str the name of a character column, this function returns the number of bytes in each CLIPPED value. (This is an exception to the rule that library functions cannot occur in SQL statements.)

Examples
These statements center a report title on an 80-column page:
LET title = "Invoice for ", fname CLIPPED, " ", lname CLIPPED LET offset = (80 - length(title))/2 PRINT COLUMN offset, title

The next statement retrieves the value in column1 and the length in bytes of the string in column2 (excluding trailing blanks).
SELECT column1, LENGTH(column2) FROM mytable

Note: INFORMIX-OnLine supports additional functionality. Refer to the INFORMIX-OnLine Programmer’s Manual for more information.

6-16

4GL Function Library

NUM_ARGS

NUM_ARGS
Overview
The num_args function returns the number of command-line arguments with which your INFORMIX-4GL program is run.

Syntax
num_args ( )

Note
The num_args function returns an integer, indicating the number of command-line arguments that followed the name of your program when the user invoked it. (You can use the arg_val library function to retrieve individual arguments.)

Example
Each of the following command lines includes three arguments: myprog.4ge kim sue joe fglgo myprog kim sue joe
(C Compiler Version) (Rapid Development System)

After either of these command lines, num_args sets 3 as the upper limit of i in the FOR statement of the program fragment that follows.
DEFINE args ARRAY[8] OF CHAR(10), i SMALLINT FOR i = 1 TO num_args() LET args[i] = arg_val(i) END FOR

Related Function
ARG_VAL

4GL Function Library

6-17

SCR_LINE

SCR_LINE
Overview
The scr_line function returns the number of the current screen row within its screen array during a DISPLAY ARRAY or INPUT ARRAY statement.

Syntax
scr_line ( )

Notes
1. The current screen row is the row where the cursor is located at the beginning of a BEFORE ROW or AFTER ROW clause. 2. The first row of both the program array and of the screen array is numbered 1. 3. The library functions scr_line and arr_curr can return different values if the program array is larger than the screen array.

6-18

4GL Function Library

SCR_LINE

Example
The following program segment tests the user input and rejects it if the customer is not from Alaska. (See also the definition of the arr_curr library function earlier in this chapter.)
DEFINE p_array ARRAY[90] OF RECORD fname CHAR(15), lname CHAR(15), state CHAR(2) END RECORD, pa_curr, sc_curr SMALLINT INPUT ARRAY p_array FROM scr_array.* AFTER FIELD state LET pa_curr = arr_curr() LET sc_curr = scr_line() IF upshift(p_array[pa_curr].state) != "AK" THEN ERROR "Customers must be from Alaska" INITIALIZE p_array[pa_curr].* TO NULL CLEAR scr_array[sc_curr].* NEXT FIELD fname END IF END INPUT

Related Functions
ARR_COUNT, ARR_CURR

4GL Function Library

6-19

SET_COUNT

SET_COUNT
Overview
The set_count function tells INFORMIX-4GL the number of filled rows in a program array.

Syntax
CALL set_count ( expr )

Explanation
CALL

is a required keyword. is an integer expression.

expr

Note
Before you use an INPUT ARRAY WITHOUT DEFAULTS or a DISPLAY ARRAY statement, you must call the set_count function with an integer argument that specifies the total number of filled rows in the program array. This function supplies an initial value for the arr_count library function to return.

Example
CALL set_count(23) INPUT ARRAY p_array WITHOUT DEFAULTS FROM s_array.*

Related Functions
ARR_COUNT, ARR_CURR

6-20

4GL Function Library

SHOWHELP

SHOWHELP
Overview
The showhelp function displays a help screen. When the user clears the help screen, INFORMIX-4GL restores the previous screen.

Syntax
CALL showhelp ( expr )

Explanation
CALL

is a required keyword. is an integer expression.

expr

Notes
1. When called with an argument that is the number of a help message in the help file named in an OPTIONS statement, showhelp clears the screen, displays the help message, and presents the user with a menu of help options. 2. If the help message is too long to fit on one screen, a Screen option of the HELP Menu allows the user to display the next part of the message. 3. When the user selects Resume from the HELP Menu, the help screen is cleared, and the previous screen is restored. 4. For information on setting up a help file, see the description of the mkmessage utility in Appendix E, or the section entitled ‘‘Creating Help Messages’’ in Chapter 8 of the INFORMIX-4GL User Guide.

4GL Function Library

6-21

SHOWHELP

Example
The following example uses infield with showhelp to display field-dependent help messages.
INPUT p_rec.* FROM sc_rec.* ON KEY(CONTROL-B) CASE WHEN infield(field1) CALL showhelp(101) WHEN infield(field2) CALL showhelp(102) WHEN infield(field3) CALL showhelp(103) ... END CASE END INPUT

Related Function
INFIELD

6-22

4GL Function Library

STARTLOG

STARTLOG
Overview
The startlog function opens an error log file.

Syntax
CALL startlog ( filename )

Explanation
CALL

is a required keyword. is a quoted string or a CHAR variable that evaluates to the name (or the pathname) of the error log file.

filename

Notes
1. If filename does not exist, startlog creates it. If the file exists, startlog opens it, and positions the file pointer so that subsequent error messages are appended to it. 2. If you do not want the error log file to reside in the current directory, you must specify a full pathname. 3. After you call the startlog function, a record of every subsequent error that occurs during the execution of your program is written to the error log file. 4. The error record consists of the date, time, source-module name and line number, error number, and error message. 5. You can write your own messages in the error log file by using the errorlog function.

4GL Function Library

6-23

STARTLOG

Example
In the following example, a CALL statement invokes the startlog library function, specifying the name of the error log file in a quoted string that includes a pathname and file extension.
... CALL startlog("/usr/steve/error.log") ... FUNCTION start_menu() CALL errorlog("Entering start_menu function") ...

Related Function
ERRORLOG

6-24

4GL Function Library

UPSHIFT

UPSHIFT
Overview
The upshift function returns a string in which all lowercase characters in its argument are converted to uppercase characters.

Syntax
upshift ( str )

Explanation
str is a quoted string or a variable of type CHAR.

Notes
1. Non-alphabetic characters in str are not altered. 2. You can use the upshift function in an expression (when such usage is allowed) or in a statement that assigns the value returned by the function to a program variable. 3. The maximum length of str is 512 characters. 4. See also the UPSHIFT field attribute in Chapter 4.

Example
Here the CHAR variables u_str and str are equivalent, except that u_str substitutes uppercase letters for any lowercase letters in str.
LET u_str = upshift(str) DISPLAY u_str

Related Function
DOWNSHIFT

4GL Function Library

6-25

UPSHIFT

6-26

4GL Function Library

Chapter

INFORMIX-4GL Statement Syntax
Types of Statements 5 Statements Supported Only on INFORMIX-SE 6 Statements Supporting INFORMIX-OnLine Enhancements 7 INFORMIX-4GL Extensions to ANSI Syntax 7 SELECT Statement 8 DECLARE Statement 9 UPDATE Statement 9 GRANT Statement 9 CREATE TABLE Statement 10 CREATE VIEW Statement 10 Definition of Statements 11 ALTER INDEX 12 ALTER TABLE ( O ) 14 BEGIN WORK 18 CALL 19 CASE 21 CLEAR 23 CLOSE 25 CLOSE DATABASE 27 CLOSE FORM 28 CLOSE WINDOW 30 COMMIT WORK 31 CONSTRUCT 32 CONTINUE 38 CREATE AUDIT 39 CREATE DATABASE ( O ) CREATE INDEX 44 CREATE SYNONYM 47

7
41

CREATE TABLE ( O ) 49 CREATE VIEW 57 CURRENT WINDOW 60 DATABASE 62 DECLARE 64 DEFER 69 DEFINE 71 DELETE 73 DISPLAY 75 DISPLAY ARRAY 79 DISPLAY FORM 83 DROP AUDIT 85 DROP DATABASE 86 DROP INDEX 88 DROP SYNONYM 89 DROP TABLE 90 DROP VIEW 91 ERROR 92 EXECUTE 94 EXIT 96 FETCH 98 FINISH REPORT 101 FLUSH 102 FOR 104 FOREACH 106 FREE ( O ) 109 FUNCTION 110 GLOBALS 112 GOTO 114 GRANT 115 IF 118 INITIALIZE 120 INPUT 122 INPUT ARRAY 129 INSERT 138 LABEL 141 LET 142 LOAD 143 LOCK TABLE 146 MAIN 148 MENU 149 MESSAGE 154 OPEN 156
7-2 INFORMIX-4GL Statement Syntax

OPEN FORM 159 OPEN WINDOW 160 OPTIONS 165 OUTPUT TO REPORT 170 PREPARE 171 PROMPT 173 PUT 177 RECOVER TABLE 179 RENAME COLUMN 181 RENAME TABLE 182 REPORT 184 RETURN 186 REVOKE 187 ROLLBACK WORK 189 ROLLFORWARD DATABASE RUN 191 SCROLL 192 SELECT 193 SET EXPLAIN 194 SET LOCK MODE ( O ) 197 SLEEP 199 START DATABASE 200 START REPORT 202 UNLOAD 203 UNLOCK TABLE 205 UPDATE 206 UPDATE STATISTICS 210 VALIDATE 211 WHENEVER 213 WHILE 216 The SELECT Statement 218 SELECT Clause 222 INTO Clause 224 FROM Clause 226 WHERE Clause 228 Comparison Condition Join Conditions 234 Subquery 237 GROUP BY Clause 240 HAVING Clause 242 ORDER BY Clause 243 INTO TEMP Clause 245 UNION Operator 246

190

228

INFORMIX-4GL Statement Syntax

7-3

Functions in SQL Statements 248 Aggregate Functions 249 LENGTH( ) 251 DATE( ) 252 DAY( ) 253 MDY( ) 254 MONTH( ) 255 WEEKDAY( ) 256 YEAR( ) 257 CURRENT 258 EXTEND( ) 260

7-4

INFORMIX-4GL Statement Syntax

Types of Statements
Twelve types of INFORMIX-4GL statements are available:

• Program Organization Statements
FUNCTION MAIN REPORT

• Variable Definition Statements
DEFINE GLOBALS

• Assignment Statements
INITIALIZE LET

• Program Flow Statements
CALL CASE CONTINUE DEFER EXIT FOR FOREACH GOTO IF LABEL RETURN RUN SLEEP WHENEVER WHILE

• Screen Interaction Statements
CLEAR CLOSE FORM CLOSE WINDOW CONSTRUCT CURRENT WINDOW DISPLAY DISPLAY ARRAY DISPLAY FORM ERROR INPUT INPUT ARRAY MENU MESSAGE OPEN FORM OPEN WINDOW OPTIONS PROMPT SCROLL

• Report Generation Statements
FINISH REPORT OUTPUT TO REPORT START REPORT

INFORMIX-4GL Statement Syntax

7-5

Statements Supported Only on INFORMIX-SE

• Data Definition Statements
ALTER INDEX ALTER TABLE CLOSE DATABASE CREATE DATABASE CREATE INDEX CREATE SYNONYM CREATE TABLE CREATE VIEW DATABASE DROP DATABASE DROP INDEX DROP SYNONYM DROP TABLE DROP VIEW RENAME COLUMN RENAME TABLE SET EXPLAIN UPDATE STATISTICS

• Data Manipulation Statements
DELETE INSERT LOAD SELECT UNLOAD UPDATE

• Cursor Manipulation Statements
CLOSE DECLARE FETCH FLUSH OPEN PUT SET EXPLAIN

• Dynamic Management Statements
EXECUTE FREE PREPARE

• Data Access Statements
GRANT LOCK TABLE REVOKE SET LOCK MODE UNLOCK TABLE

• Data Integrity Statements
BEGIN WORK COMMIT WORK CREATE AUDIT DROP AUDIT RECOVER TABLE ROLLBACK WORK ROLLFORWARD DATABASE START DATABASE VALIDATE

Statements Supported Only on INFORMIX-SE
The following SQL statements are supported only on INFORMIX-SE. They cannot be used in INFORMIX-OnLine applications.
CREATE AUDIT DROP AUDIT RECOVER TABLE ROLLFORWARD DATABASE START DATABASE 7-6 INFORMIX-4GL Statement Syntax

Statements Supporting INFORMIX-OnLine Enhancements

Statements Supporting INFORMIX-OnLine Enhancements
The INFORMIX-OnLine database engine recognizes extensions to several SQL statements. Refer to the INFORMIX-OnLine Programmer’s Manual for details of the additional functionality available with INFORMIX-OnLine.
INFORMIX-4GL statements that support INFORMIX-OnLine enhancements

are listed here. They are identified in the following descriptions with an ( O ) after the name of the statement. Do not include the (O) when you type the statement.
ALTER TABLE ( O ) CREATE DATABASE ( O ) CREATE TABLE ( O ) FREE ( O ) SET LOCK MODE ( O )

INFORMIX-4GL Extensions to ANSI Syntax
Regardless of whether or not your database is MODE ANSI, you can check the SQL statements in your 4GL programs for ANSI compatibility. To check your programs at run time, you can set the DBANSIWARN environment variable. To check your programs at compile time, you can set the DBANSIWARN environment variable or use the -ansi flag when you compile your 4GL sourcecode files at the system prompt. Examples:
c4gl -ansi file.4gl -o program.4ge fglpc -ansi file.4gl (C Compiler Version)

(Rapid Development System)

When you compile with the -ansi flag or with the DBANSIWARN environment variable set, SQL statements that include Informix extensions to ANSI syntax cause warning messages to be written to the .err file. (See Appendix C for more information about DBANSIWARN.) Note: You cannot use the -ansi flag with i4gl or r4gl. When you run a compiled program after you have set DBANSIWARN, any extension to ANSI syntax in an SQL statement causes the characters SQLAWARN[1] and SQLAWARN[6] to be set to W.

INFORMIX-4GL Statement Syntax

7-7

INFORMIX-4GL Extensions to ANSI Syntax

The following SQL statements generate warnings when Informix extension checking is initiated:
ALTER INDEX ALTER TABLE BEGIN WORK CLOSE DATABASE CREATE AUDIT CREATE DATABASE CREATE INDEX CREATE SYNONYM CREATE TABLE CREATE VIEW DATABASE DROP AUDIT DROP DATABASE DROP INDEX DROP SYNONYM DROP TABLE DROP VIEW FLUSH FREE GRANT LOAD LOCK TABLE PUT RECOVER TABLE RENAME COLUMN RENAME TABLE REVOKE ROLLFORWARD DATABASE SET EXPLAIN SET LOCK MODE START DATABASE UNLOAD UNLOCK TABLE UPDATE STATISTICS

Note: The BEGIN WORK, LOAD, and UNLOAD statements generate warnings at compile time only. The next section lists keywords or features of INFORMIX-4GL that are extensions to ANSI standard syntax. A warning is generated if you include these keywords or features in an SQL statement, and then initiate Informix extension checking with the -ansi flag or with the DBANSIWARN environment variable.

SELECT Statement
The following keywords or features are Informix extensions to the SELECT statement:

• Column labels • Column subscripts • Numbers as position indicators (for example, in a GROUP BY clause) • INTO TEMP clause • MATCHES keyword • OUTER keyword • UNIQUE keyword • UNITS keyword

7-8

INFORMIX-4GL Statement Syntax

INFORMIX-4GL Extensions to ANSI Syntax

• The following functions: • CURRENT • DATE( ) • DAY( ) • EXTEND( ) • LENGTH( ) • MDY( ) • MONTH( ) • TODAY • WEEKDAY( ) • YEAR( )
DECLARE Statement
The following keywords are Informix extensions to the DECLARE statement:

• • • •

INSERT SCROLL WITH HOLD FOR UPDATE clause

UPDATE Statement
Specifying multiple columns in an UPDATE statement is an extension to the ANSI standard.

GRANT Statement
The following keywords are extensions to the GRANT statement:

• • • •

AS CONNECT DBA RESOURCE

Use of the GRANT statement in INFORMIX-4GL always generates a warning when Informix extension checking is initiated. The ANSI standard requires that the GRANT statement be issued within the CREATE SCHEMA

INFORMIX-4GL Statement Syntax

7-9

INFORMIX-4GL Extensions to ANSI Syntax

AUTHORIZATION statement. For more information about the CREATE SCHEMA AUTHORIZATION statement, refer to the INFORMIX-SQL Reference

Manual.

CREATE TABLE Statement
The following features and keywords are Informix extensions to the CREATE
TABLE statement:

• DISTINCT keyword • IN keyword • UNIQUE CONSTRAINT keywords • TEMP keyword • The following data types: • DATE • MONEY • SERIAL • SMALLFLOAT • DATETIME • INTERVAL
Use of the CREATE TABLE statement in INFORMIX-4GL always generates a warning when Informix extension checking is initiated. The ANSI standard requires that the CREATE TABLE statement be issued within the CREATE SCHEMA AUTHORIZATION statement. For more information about the CREATE SCHEMA AUTHORIZATION statement, refer to the INFORMIX-SQL Reference Manual.

CREATE VIEW Statement
Use of the CREATE VIEW statement in INFORMIX-4GL always generates a warning when Informix extension checking is initiated. The ANSI standard requires that the CREATE VIEW statement be issued within the CREATE SCHEMA AUTHORIZATION statement. For more information about the CREATE SCHEMA AUTHORIZATION statement, refer to the INFORMIX-SQL Reference Manual. Note: INFORMIX-OnLine supports additional keywords that are extensions. See the INFORMIX-OnLine Programmer’s Manual for more information.

7-10

INFORMIX-4GL Statement Syntax

Definition of Statements

Definition of Statements
The following section describes the INFORMIX-4GL statements. The statements appear in alphabetical order. (See also Chapter 5, which describes additional statements that can only appear in the FORMAT section of a REPORT routine, such as NEED, PAUSE, PRINT, PRINT FILE, and SKIP.)

INFORMIX-4GL Statement Syntax

7-11

ALTER INDEX

ALTER INDEX
Overview
Use the ALTER INDEX statement to cluster a table in the order of an existing index, or to release an index from the clustering attribute.

Syntax
ALTER INDEX index-name TO [ NOT ] CLUSTER

Explanation
ALTER INDEX

are required keywords. is the identifier of an existing index. is a required keyword. is an optional keyword. is a required keyword.

index-name
TO NOT CLUSTER

Notes
1. The TO CLUSTER option causes INFORMIX-4GL to reorder the rows in the physical table to agree with the order of index-name. Reordering causes the entire file to be rewritten. This process may take a long time and requires sufficient disk space to maintain two copies of the table. After all rows have been copied to the reordered table, the original version of the table is automatically deleted, releasing the additional disk space. 2. Since there can be only one clustered index per table, you must use the NOT option to release the cluster attribute from one index before assigning it to another. The NOT option does not affect the physical table; it merely drops the cluster attribute on index-name from the system catalogs. 3. When INFORMIX-4GL executes ALTER INDEX with the TO CLUSTER option, it locks the table in EXCLUSIVE MODE. If some other process is using the table to which index-name belongs, INFORMIX-4GL cannot execute ALTER INDEX with the TO CLUSTER option and returns an error. 4. You cannot use a ROLLBACK statement to undo the effect of the ALTER INDEX statement.

7-12

INFORMIX-4GL Statement Syntax

ALTER INDEX

5. As rows are added and deleted, you can expect the benefit of an earlier clustering to disappear. You can recluster the table by issuing another ALTER INDEX TO CLUSTER statement on the clustered index. 6. You do not need to drop a cluster index before issuing another ALTER INDEX TO CLUSTER statement on a currently clustered index.

Example
The following example creates two indexes on the orders table and clusters the physical table in ascending order on the customer_num column. Later, the example clusters the physical table in ascending order on the order_num column.
CREATE UNIQUE INDEX ix_ord ON orders (order_num) CREATE CLUSTER INDEX ix_cust ON orders (customer_num) ... ALTER INDEX ix_cust TO NOT CLUSTER ALTER INDEX ix_ord TO CLUSTER

Related Statement
CREATE INDEX

INFORMIX-4GL Statement Syntax

7-13

ALTER TABLE ( O )

ALTER TABLE ( O )
Overview
Use the ALTER TABLE statement to add a column to a table, delete a column from a table, modify the data type of a column, add a UNIQUE CONSTRAINT to a column or a composite list of columns, or drop a UNIQUE CONSTRAINT associated with a column or composite list of columns.

Syntax
ALTER TABLE table-name { ADD ( newcol-name newcol-type [NOT NULL] [ UNIQUE [ CONSTRAINT constr-name ] ] [ , . . . ] ) [ BEFORE oldcol-name ] | DROP ( oldcol-name [ , . . . ] ) | MODIFY ( oldcol-name newcol-type [ NOT NULL ] [ , . . . ] ) | ADD CONSTRAINT UNIQUE ( oldcol-name [ , . . . ] ) [ CONSTRAINT constr-name ] | DROP CONSTRAINT ( constr-name [ , . . . ] ) } [ , . . . ]

Explanation
ALTER TABLE

are required keywords. is the name of an existing table. is a keyword you use to add a column. is the name of the column you want to add. is either the data type of the column you are adding or the data type of the column you are modifying. are optional keywords. is a keyword specifying that the column or composite column list accepts only unique values. is a keyword you use to indicate that constr-name is assigned in the statement. is the name of the constraint. is an optional keyword you use to indicate where you want newcol-name placed in the list of columns. The default is at the end of the list of columns. is the name of an existing column. is a keyword you use to drop a column.

table-name
ADD

newcol-name newcol-type
NOT NULL UNIQUE CONSTRAINT

constr-name
BEFORE

oldcol-name
DROP 7-14 INFORMIX-4GL Statement Syntax

ALTER TABLE ( O )

MODIFY

is a keyword you use to change the data type of an existing column. are keywords you use to place a constraint on a column or composite column list. are keywords you use to drop a UNIQUE CONSTRAINT on a table column.

ADD CONSTRAINT DROP CONSTRAINT

Notes
1. In a MODE ANSI database, the name of a table is qualified by the owner of the table (owner. table-name). You must specify owner when you refer to a table owned by another user. The use of the prefix owner. is optional in a non-MODE ANSI database. INFORMIX-4GL does check the accuracy of owner, however, if you include it in a statement. See the section “Owner Naming” in Chapter 3 for more information. 2. You can use one or more of the ADD, DROP, MODIFY, ADD CONSTRAINT, or DROP CONSTRAINT clauses, and you can place them in any order. Use a comma ( , ) to separate clauses. The actions are performed in the order specified. If any of the actions fail, the entire operation is canceled. 3. You cannot add a SERIAL column to a table. You must create a SERIAL column with the CREATE TABLE statement. You cannot add it with the ALTER TABLE statement. 4. You can modify an existing column that formerly permitted NULLs to be NOT NULL, provided that it does not already contain any NULL values. Specify MODIFY with the same oldcol-name and data type and the NOT NULL keywords. 5. You can modify an existing column that did not permit NULLs to permit NULLs. Specify MODIFY with the oldcol-name and the existing data type and omit NOT NULL. 6. When you add a new column to an existing table, it is filled with NULL values. Therefore, you cannot use the NOT NULL option or specify a UNIQUE CONSTRAINT when you add a column unless the table contains no data. 7. If you change the data type of an existing column, all data are converted to the new data type, including number to character and character to number (if the characters represent numbers). When there is a UNIQUE CONSTRAINT, however, conversion takes place only if it does not violate the constraint. If a data conversion would result in duplicate values (by changing FLOAT to SMALLFLOAT, for example, or
INFORMIX-4GL Statement Syntax 7-15

ALTER TABLE ( O )

by truncating CHAR values), then the ALTER TABLE command fails. You will receive error 212 (Cannot add index) and ISAM error 100 (There is already a record with the same value in a unique index). 8. When you drop a column that is part of a multiple-column constraint, you automatically drop the corresponding UNIQUE CONSTRAINT. 9. You can use ALTER TABLE with the ADD and CONSTRAINT keywords to specify a UNIQUE CONSTRAINT on a new or existing column, or on a composite list of columns. The following rules apply when adding a UNIQUE CONSTRAINT:

• • • • •

The columns can contain only unique values. A UNIQUE CONSTRAINT cannot already apply to the columns. An ascending index cannot already apply to the columns. A composite list can include no more than eight column names. An existing UNIQUE CONSTRAINT cannot have the same name.

10. To drop an existing constraint, specify DROP CONSTRAINT and the name of the constraint. If no constr-name name was specified when the constraint was created, the system generated the name. You can query the sysconstraints system catalog for the names (including the owner) of constraints. 11. If you own the table or have alter permission on the table, you can create a constraint on the table and specify yourself as the owner. If you have DBA permission, you can create constraints for other users. 12. You must own table-name, have DBA privilege, or be granted ALTER permission to use ALTER TABLE. 13. Altering a table on which a view depends may invalidate the view. 14. You cannot use a ROLLBACK WORK statement to undo an ALTER TABLE statement. 15. The keyword DISTINCT is a synonym for UNIQUE.

7-16

INFORMIX-4GL Statement Syntax

ALTER TABLE ( O )

Examples
ALTER TABLE items ADD (item_weight DECIMAL(6,2) BEFORE total_price) ALTER TABLE items DROP (total_price) ALTER TABLE items MODIFY (manu_code CHAR(4)) ALTER TABLE manufact ADD CONSTRAINT UNIQUE (manu_name) CONSTRAINT con_name ALTER TABLE manufact DROP CONSTRAINT (con_name)

Since they refer to the same table, you can combine the first two examples into a single statement:
ALTER TABLE items ADD (item_weight DECIMAL(6,2) BEFORE total_price), DROP (total_price)

Related Statements
CREATE TABLE, CREATE INDEX, RENAME COLUMN, RENAME TABLE

INFORMIX-4GL Statement Syntax

7-17

BEGIN WORK

BEGIN WORK
Overview
Use the BEGIN WORK statement to start a transaction (a sequence of database operations that are terminated by the COMMIT WORK or ROLLBACK WORK statement) in a non-MODE ANSI database. See the section “Transactions” in Chapter 3 for a description of transactions.

Syntax
BEGIN WORK

Explanation
BEGIN WORK

are keywords to start a transaction.

Notes
1. Each row affected by an UPDATE, DELETE, or INSERT statement during a transaction is locked and remains locked throughout the transaction. A transaction that contains a large number of such statements, or that contains statements affecting a large number of rows, may exceed the limits placed by your operating system on the maximum number of simultaneous locks. If you encounter this error, you may need to lock the entire table immediately after beginning the transaction. See the section “Locking” in Chapter 3 for a more detailed description of table-level and rowlevel locking in INFORMIX-4GL. 2. Do not use the BEGIN WORK statement with a database CREATEd or STARTed as MODE ANSI. In a program that accesses a MODE ANSI database, the BEGIN WORK statement generates a run-time error unless it appears immediately after one of the following statements:
CREATE DATABASE DATABASE START DATABASE COMMIT WORK ROLLBACK WORK

3. See the “Transactions” section in Chapter 3 for a full description of transactions.

Related Statements
COMMIT WORK, ROLLBACK WORK

7-18

INFORMIX-4GL Statement Syntax

CALL

CALL
Overview
Use the CALL statement to invoke a function.

Syntax
CALL function ( [ argument-list ] ) [ RETURNING variable-list ]

Explanation
CALL

is a required keyword. is the name of a function. is a list of zero or more expressions, separated by commas and enclosed in parentheses, that are passed to the function. The parentheses are required, even if there are no arguments. is an optional keyword to specify variables that the function will return to the calling routine. is a list of one or more program variables, separated by commas.

function argument-list

RETURNING

variable-list

Notes
1. You can use the CALL statement to call INFORMIX-4GL functions and C language functions. See “C Functions” in Chapter 2 for the rules on using such functions in INFORMIX-4GL programs. 2. The arguments specified in argument-list will be passed by value. 3. You can define INFORMIX-4GL functions in the same source file as the MAIN program block, or you can compile them separately and link them later to the MAIN program block.

Example
CALL statistics(rec.*) RETURNING mean, std_dev

INFORMIX-4GL Statement Syntax

7-19

CALL

Related Statements
DEFINE, FUNCTION

7-20

INFORMIX-4GL Statement Syntax

CASE

CASE
Overview
Use the CASE statement to select a sequence of statements, depending on the current value of an expression.

Syntax
CASE [ ( expr ) ] WHEN { expr | Boolean-expr } statement ... [ EXIT CASE ] ... WHEN { expr | Boolean-expr } statement ... [ EXIT CASE ] ... ... [ OTHERWISE ] statement ... [ EXIT CASE ] ... END CASE

Explanation
CASE

is a required keyword. is an expression that returns an INTEGER, SMALLINT, DECIMAL, or CHAR(1) value. is a required keyword. is an expression that is either TRUE or FALSE. is an INFORMIX-4GL statement. is an optional statement that causes program control to pass to the statement following the END CASE keywords. is an optional keyword introducing a sequence of statements to be executed if none of the WHEN clauses is executed. are required keywords that terminate the CASE statement.

expr
WHEN

Boolean-expr statement
EXIT CASE OTHERWISE END CASE

INFORMIX-4GL Statement Syntax

7-21

CASE

Notes
1. The CASE statement is equivalent to a set of nested IF statements. 2. If you use the OTHERWISE option, it must be the last in the list. 3. If the optional parenthesized expression following the CASE keyword is missing, you must follow the WHEN keyword with a Boolean expression. If there is an expression following the CASE keyword, you must follow the WHEN keyword with an expression that evaluates to the same data type. 4. There is an implied EXIT CASE statement at the end of each sequence of statements following a WHEN clause. Program control will pass to the sequence of statements following the END CASE statement.

Example
LABEL question: ... CASE WHEN answer MATCHES "[Yy]" CALL process() WHEN answer MATCHES "[Nn]" CALL abort() OTHERWISE CALL retry() END CASE

Related Statements
IF, EXIT

7-22

INFORMIX-4GL Statement Syntax

CLEAR

CLEAR
Overview
Use the CLEAR statement to clear the whole screen, a window, all fields in a screen form, or a set of fields.

Syntax
CLEAR { SCREEN | WINDOW window-name | FORM | field-list }

Explanation
CLEAR SCREEN WINDOW

is a required keyword. is the keyword to clear the whole screen. is the keyword to clear a window. is the name of the window that you want to clear, or the keyword SCREEN. is the keyword to clear the values in all screen fields of a form. is a list of one or more names of fields to be cleared.

window-name
FORM

field-list

Notes
1. The CLEAR statement does not change the value of any variable. It simply clears the display from the region indicated. 2. The CLEAR SCREEN statement makes the screen the current window and clears it. 3. The CLEAR WINDOW statement clears the specified window, retaining any border. (The specified window need not be the current window. This option does not affect which window is the current window.) 4. If you specify SCREEN as the window-name in a CLEAR WINDOW statement, INFORMIX-4GL clears the screen, except for the area occupied by any open windows. 5. CLEAR FORM and CLEAR field-list apply to the form in the current window.

INFORMIX-4GL Statement Syntax

7-23

CLEAR

Examples
CLEAR fname, lname, address1, city, state, zipcode CLEAR FORM CLEAR SCREEN CLEAR WINDOW win1 CLEAR WINDOW SCREEN

7-24

INFORMIX-4GL Statement Syntax

CLOSE

CLOSE
Overview
Use the CLOSE statement when you no longer need to refer to the active set of a SELECT cursor, or when you want to flush the insert buffer and close an INSERT cursor.

Syntax
CLOSE cursor-name

Explanation
CLOSE

is a required keyword. is the name of a cursor that has been DECLAREd for a SELECT or INSERT statement.

cursor-name

Notes
1. If cursor-name is associated with a SELECT statement, the CLOSE statement puts the cursor in a closed state and leaves the active set undefined. 2. After you CLOSE a SELECT cursor, you cannot execute a FETCH statement until you reopen the cursor. 3. If cursor-name is associated with an INSERT statement, the CLOSE statement flushes any rows in the buffer into the database (writes to disk) and closes the cursor. 4. After you CLOSE an INSERT cursor, you cannot execute a PUT or FLUSH statement until after you use an OPEN command to reopen the cursor. 5. The global variables status (whose value is taken from the SQLCA.SQLCODE ) and SQLCA. SQLERRD [3] indicate the result of each FLUSH and CLOSE statement for an INSERT cursor. If INFORMIX-4GL successfully inserts the buffered rows into the database, it sets status to zero, and SQLCA. SQLERRD [3] to the number of rows that were inserted into the database. If INFORMIX-4GL encounters an error while inserting the buffered rows into the database, it sets status to a negative number (specifically, the number of the error message) and sets variable SQLCA. SQLERRD [3] to the number of rows successfully inserted into the database. Any buffered
INFORMIX-4GL Statement Syntax 7-25

CLOSE

rows following the last successfully inserted row are discarded. In this case, the cursor remains open. 6. Although the COMMIT WORK and ROLLBACK WORK statements CLOSE all open cursors (except cursors declared WITH HOLD ), do not use them for this purpose. You should explicitly CLOSE each INSERT cursor before committing the work, so that you can verify that the insertion was successful. 7. INFORMIX-4GL does not provide a global variable containing the total number of rows successfully inserted into the database with an INSERT cursor. If you want to know the total number of inserts performed, you must set a counter in your program and increment it upon each PUT statement. 8. If your database is not MODE ANSI but has transactions, you must issue the CLOSE statement within a transaction.

Examples
CLOSE query_cursor CLOSE icurs

Related Statements
DECLARE, FETCH, FLUSH, OPEN, PUT

7-26

INFORMIX-4GL Statement Syntax

CLOSE DATABASE

CLOSE DATABASE
Overview
Use the CLOSE DATABASE statement to close the current database.

Syntax
CLOSE DATABASE

Explanation
CLOSE DATABASE

are required keywords.

Notes
1. Following the CLOSE DATABASE statement, the only legal SQL statements are CREATE DATABASE, DATABASE, DROP DATABASE, ROLLFORWARD DATABASE, and START DATABASE. 2. Issue the CLOSE DATABASE statement before you DROP the current database. 3. The CLOSE DATABASE statement cannot appear in a multi-statement PREPARE.

Example
CLOSE DATABASE

Related Statements
CREATE DATABASE, DROP DATABASE, ROLLFORWARD DATABASE, START DATABASE

INFORMIX-4GL Statement Syntax

7-27

CLOSE FORM

CLOSE FORM
Overview
Use the CLOSE FORM statement to release the memory required for a screen form.

Syntax
CLOSE FORM form-name

Explanation
CLOSE FORM

are required keywords. is an INFORMIX-4GL identifier that you assigned to a screen form in an OPEN FORM statement.

form-name

Notes
1. After you execute the CLOSE FORM statement, form-name is no longer associated with a screen form. Executing a subsequent DISPLAY FORM statement will give an error message. 2. If you execute a new OPEN FORM statement with the same form-name, INFORMIX-4GL will close the existing form before opening the new one. 3. When you execute the OPEN FORM statement, the compiled form is loaded into memory, where it remains until you execute a CLOSE FORM statement for that form. If you have displayed another form and wish to regain the memory allocated to the first form, you can execute CLOSE FORM on the old form. 4. The CLOSE FORM statement affects memory use only and does not affect the logic of the program. Since allocating memory and reading a form from the disk takes time, you should leave forms open that you use repeatedly. 5. The CLOSE WINDOW statement closes any open form in the specified window, releasing the memory allocated to that form.

Example
CLOSE FORM order_entry 7-28 INFORMIX-4GL Statement Syntax

CLOSE FORM

Related Statements
CLOSE WINDOW, DISPLAY FORM, FREE, OPEN FORM

INFORMIX-4GL Statement Syntax

7-29

CLOSE WINDOW

CLOSE WINDOW
Overview
Use the CLOSE WINDOW statement to close a window.

Syntax
CLOSE WINDOW window-name

Explanation
CLOSE WINDOW

are required keywords. is the name of the window to be closed.

window-name

Notes
1. When you close a window, INFORMIX-4GL frees all resources used by the window, including forms, and restores the underlying display. 2. When you close the current window, the next window on the stack becomes the current window. When you close any other window, INFORMIX-4GL simply removes the window from the stack, leaving the current window unchanged. In both cases, INFORMIX-4GL restores the underlying display. 3. If you close a window that is currently being used for input, INFORMIX-4GL generates a run-time error. For example, closing the current window in the middle of a DISPLAY ARRAY, INPUT, INPUT ARRAY, or MENU statement produes a run-time error. 4. You cannot issue a CLOSE WINDOW screen command.

Example
CLOSE WINDOW win 1

Related Statements
CLEAR WINDOW, CURRENT WINDOW, OPEN WINDOW, OPTIONS

7-30

INFORMIX-4GL Statement Syntax

COMMIT WORK

COMMIT WORK
Overview
Use the COMMIT WORK statement to commit all modifications made to the database during a transaction.

Syntax
COMMIT WORK

Explanation
COMMIT WORK

are required keywords.

Notes
1. Use the COMMIT WORK statement when you are satisfied with all changes made during the transaction to the database. Use the ROLLBACK WORK statement if you do not want to commit modifications made during the transaction to the database. 2. The COMMIT WORK statement closes all open cursors, except cursors declared WITH HOLD. Do not use the COMMIT WORK statement within a FOREACH loop. 3. The COMMIT WORK statement releases all row and table locks. 4. See the section “Transactions” in Chapter 3 for details of how the the COMMIT WORK statement works.

Related Statements
BEGIN WORK, ROLLBACK WORK

INFORMIX-4GL Statement Syntax

7-31

CONSTRUCT

CONSTRUCT
Overview
Use the CONSTRUCT statement to create a CHAR variable that contains the Boolean expression constructed from a screen-generated query by example. The resulting CHAR variable contains conditions for the WHERE clause of a SELECT statement, corresponding to user-specified selection criteria.

Syntax
CONSTRUCT { BY NAME char-variable ON column-list | char-variable ON column-list FROM { field-list | screen-record [ [ n ] ].* } [ , . . . ] } [ ATTRIBUTE ( attribute-list) ]

Explanation
CONSTRUCT BY NAME

is a required keyword. are keywords instructing INFORMIX-4GL to match names of database columns to screen field names. is an identifier of a CHAR type program variable (to contain the selection criteria). is a required keyword to specify database columns. is a list of one or more database column names, separated by commas. You can use the syntax table.*. is a keyword to specify screen fields for user entry of search values, and for display of query results. is a list of one or more screen field names. is the identifier of a collection of field names defined in a form specification as a screen record. is an integer or integer variable, enclosed in brackets, to specify the row in a screen array in which the CONSTRUCT takes place. is a keyword to specify screen display attributes. is a list (in parentheses) of one or more screen display attributes, separated by commas.

char-variable
ON

column-list
FROM

field-list screen-record [n]

ATTRIBUTE

(attribute-list)

7-32

INFORMIX-4GL Statement Syntax

CONSTRUCT

Notes
1. The CONSTRUCT statement allows the user to enter query-by-example search parameters in a screen form, with this syntax:
Symbol = > < >= <= <> : .. * ? | Name equal to greater than less than greater than or equal to less than or equal to not equal to range range wildcard for any string single-character wildcard or Data Types all all all all all all all DATETIME and INTERVAL CHAR CHAR all Pattern =x >x <x >=x <=x <>x x:y x..y *x, x*, *x* ?x, x?, ?x?, x?? a|b...

Explanation of Symbols

• The equal sign ( = ) is the default query symbol for non-character columns, and for character columns in which the user enters a search value that does not contain wildcards: char-column = "value" If the user enters a character value that contains a wildcard character (either * or ? ), then MATCHES is the default query symbol: char-column MATCHES "value"

• The equal ( = ) sign with no value searches for a database row that contains a NULL column. Enter = * to find a row that contains a column with only an asterisk.

• The x means any value of the appropriate data type for the search field.
Enter the value immediately after any one of the first six query symbols in the preceding table. Do not leave a space between the query symbol and the value.

• The symbols >, <, > =, and < = imply an ordering of the data in the column. For CHAR data, ‘‘greater than’’ means later in the ASCII collating

INFORMIX-4GL Statement Syntax

7-33

CONSTRUCT

sequence (where a < A < 1 ), as listed in Appendix H. For DATE and DATETIME data, ‘‘greater than’’ means after.

• Colon in x : y searches for all values between x and y, inclusive. Here
value y must be larger than x. The search criterion 1 : 10 would find all rows with a value in that column from 1 through 10.

• Substitute two periods ( . . ) for the colon in DATETIME and INTERVAL
ranges to avoid ambiguity with the field separator in hh:mi:ss values.

• Asterisk ( * ) is the string wildcard, representing zero or more characters. An *ts* search value in the field corresponding to the lname column of the customer table would find two names, Watson and Albertson. An S* search value in the same field would find Sadler and Sipes. An *er search value would find the four names Sadler, Miller, Jaeger, and Baxter.

• The question mark ( ? ) is the single-character wildcard. The user can
use the question mark to find values that match a pattern where the number of characters is fixed. For example, the user can enter Eriks?n to search for names like ‘‘Erikson’’ and ‘‘Eriksen.’’ Similarly, the user can enter New??n to search for names like ‘‘Newton,’’ ‘‘Newman,’’ and ‘‘Newson.’’

• The symbo| between values a and b means the logical OR. In the field
corresponding to the column customer_num, this entry retrieves any of three numbers: 102|105|118 2. You can use the BY NAME option when the field names on the screen form have the same names as the corresponding column names in column-list. If you do not, you must specify a screen record or name the fields explicitly in field-list. 3. The CONSTRUCT statement is terminated when the user enters ESC or the key specified as the Accept key in the OPTIONS statement. For single-item CONSTRUCTs, pressing RETURN is equivalent to pressing the Accept key, unless the INPUT WRAP option is in effect. For multiple-item CONSTRUCTs, a RETURN after the last item is equivalent to pressing the Accept key, unless INPUT WRAP is in effect. 4. By default, both ESC and Interrupt exit from CONSTRUCT statements. If the DEFER INTERRUPT statement has been executed, an Interrupt sets the global variable int_flag to nonzero and terminates the CONSTRUCT statement (but not the 4GL program). Otherwise, an Interrupt causes an immediate program stop.

7-34

INFORMIX-4GL Statement Syntax

CONSTRUCT

5. In addition to the RETURN, ESC, ARROW, and Interrupt keys, the user can employ the following keys for editing during a CONSTRUCT statement: CTRL-A CTRL-D CTRL-H CTRL-L CTRL-R CTRL-X toggles between insert and typeover mode. deletes characters from the current cursor position to the end of the field. moves the cursor nondestructively one space to the left inside a field. It is equivalent to pressing the [←] key. moves the cursor nondestructively one space to the right inside a field. It is equivalent to pressing the [→] key. redisplays the screen. deletes the character beneath the cursor.

6. The user can query for only those fields displayed on the screen that you have specified in the FROM clause or implied in the BY NAME clause. The number of fields in the FROM clause must be the same as the number of columns in the ON clause. The order of fields in the FROM clause must match the order of columns in the ON clause. INFORMIX-4GL constructs char-variable by associating the column name in the ON clause with the search condition that the user entered into the corresponding field in the FROM clause. 7. The UPSHIFT and DOWNSHIFT attributes work during a CONSTRUCT statement. The COMMENTS attribute works, but with the following restriction: if a field that displays a comment is too short to hold the search criteria that the user enters, INFORMIX-4GL opens a work space on the Comment line, erasing any comment that is displayed. 8. If the column names in a CONSTRUCT BY NAME statement are associated with field names in a screen array, the construct takes place in the first row of the screen array. If you want to use screen-array field names in the FROM clause of a CONSTRUCT statement, then you must use the notation screen-record [n ]. field-name to specify the row in which the construct takes place. 9. You can use the information stored in char-variable in the WHERE clause of a PREPAREd SELECT statement to retrieve a set of rows from the database. 10. A compile-time error results if you use the BY NAME clause when the column names include an owner name. You must use the FROM clause to specify table aliases in the field-list when any column names contain an owner name.

INFORMIX-4GL Statement Syntax

7-35

CONSTRUCT

11. When you use screen-record.* or table.* as shorthands for explicit lists, be sure that the order of the fields implied in the screen-record.* notation corresponds to the order of the columns implied in the screen-record.* notation. The order of the fields in screen-record.* depends on its definition in the screen form. The order of the columns in table.* depends on the order in the syscolumns system catalog at the time you compile your program. If you have used ALTER TABLE to change the order or number of the columns in table since you compiled your program, you may need to modify your program and the forms that depend on it. 12. Any screen attributes specified in attribute-list apply to all the fields in field-list or screen-record. 13. If you use the ATTRIBUTE clause, none of the default attributes listed in syscolatt or in the form specification file for fields in field-list or screenrecord apply. The attribute-list temporarily overrides any attributes specified in an OPTIONS, DISPLAY FORM, or OPEN WINDOW statement for these fields. 14. These keywords can appear in the ATTRIBUTE clause:
WHITE = NORMAL YELLOW = BOLD MAGENTA = BOLD RED = BOLD CYAN = DIM GREEN = DIM BLUE = DIM BLACK = INVISIBLE REVERSE BLINK UNDERLINE

You can specify zero or one of the keywords in the left-hand columns, and from zero to three from the right-hand column (but some terminals may not support some combinations). On color terminals, NORMAL is interpreted as WHITE, BOLD as RED, DIM as BLUE, and INVISIBLE as BLACK. Do not include the equal ( = ) sign, which in this table shows the effect on monochrome terminals of keywords that specify color. These keywords cannot produce the effects indicated unless the termcap or terminfo files and the physical terminals support the attribute. (See Appendix I, “Modifying termcap and terminfo.”’) 15. On UNIX systems that use terminfo files rather than termcap, INFORMIX-4GL does not support attributes that specify colors, and the only valid attribute-list keywords are REVERSE and UNDERLINE. 16. You must first execute OPEN FORM or OPEN WINDOW WITH FORM before you can use the CONSTRUCT statement.

7-36

INFORMIX-4GL Statement Syntax

CONSTRUCT

Example
The following program fragment illustrates the use of the CONSTRUCT statement to specify the search condition of a WHERE clause. The cursor_1 cursor is DECLAREd and used to execute the query.
CONSTRUCT query_1 ON order_num, customer_num, order_date, ship_date FROM order_num, customer_num, order_date, ship_date ATTRIBUTE(BOLD) LET s1 = "select * from orders where ", query_1 PREPARE s_1 FROM s1 DECLARE cursor_1 CURSOR FOR s_1 FOREACH cursor_1 INTO order_rec.* ... END FOREACH

Related Statements
DECLARE, PREPARE, OPEN FORM, OPTIONS, SELECT

INFORMIX-4GL Statement Syntax

7-37

CONTINUE

CONTINUE
Overview
Use the CONTINUE statement to cause a FOR, FOREACH, or WHILE statement to start a new cycle immediately, if the conditions permit, or to return to the menu from an option in the MENU statement.

Syntax
CONTINUE { FOR | FOREACH | MENU | WHILE }

Explanation
CONTINUE FOR FOREACH MENU WHILE

is a required keyword. is a required keyword in a FOR statement. is a required keyword in a FOREACH statement. is a required keyword in a MENU statement. is a required keyword in a WHILE statement.

Related Statements
END, EXIT

7-38

INFORMIX-4GL Statement Syntax

CREATE AUDIT

CREATE AUDIT
Overview
Use the CREATE AUDIT statement to create an audit trail file, and to start writing the audit trail.

Syntax
CREATE AUDIT FOR table-name IN "pathname"

Explanation
CREATE AUDIT FOR table-name
IN

are required keywords. is the name of the table for which to create an audit trail file. is a required keyword. is the full pathname for the audit trail file. It must be enclosed in quotation ( " ) marks.

pathname

Notes
1. You create audit trails to keep a record of all modifications of a table. An audit trail is a complete history of all additions, deletions, and updates to the table. INFORMIX-4GL can use the audit trail to reconstruct the table from a backup copy made at the time the audit trail is created. (See the RECOVER TABLE statement.) See the section “Audit Trails” in Chapter 3 for more information. 2. If an audit trail file with the same pathname already exists for the same table, the CREATE AUDIT statement does nothing. If an audit trail file for the same table exists with a different pathname, INFORMIX-4GL displays an error message. 3. Make a backup copy of your database files as soon as you run the CREATE AUDIT statement, but before you make any further changes to the database. (See the RECOVER TABLE statement for an example.) If possible, put the audit trail file on a different physical device from the one that holds your data, so that a failure of one does not damage the data on the other. 4. Audit trails slow INFORMIX-4GL slightly because each alteration of the table is recorded in the audit trail file, as well as in the database files.
INFORMIX-4GL Statement Syntax 7-39

CREATE AUDIT

5. You must own table-name or have DBA status to use the CREATE AUDIT statement. 6. You must set execute permission for all directories below root in pathname for each class of user (owner, owner’s group, and public) that accesses your database. 7. You cannot create an audit file for a view. 8. You cannot create a cluster index on a table that has an audit trail.

Example
CREATE AUDIT FOR orders IN "/dbdir/safe"

Related Statements
DROP AUDIT, RECOVER TABLE

7-40

INFORMIX-4GL Statement Syntax

CREATE DATABASE ( O )

CREATE DATABASE ( O )
Overview
Use the CREATE DATABASE statement to create a new database. INFORMIX-4GL will create the system catalogs that will contain the data dictionary describing the structure of the database. The database that you create automatically becomes the current database.

Syntax
CREATE DATABASE database-name [ WITH LOG IN "pathname" [ MODE ANSI ] ]

Explanation
CREATE DATABASE

are required keywords. is the name that you assign to the database. The databasename can be a program variable of type CHAR containing the name of the database you want to create. are optional keywords to support transactions. is the full pathname, enclosed in quotation ( " ) marks, of the transaction log file. are optional keywords that specify the database as MODE
ANSI.

database-name

WITH LOG IN

pathname
MODE ANSI

Notes
1. INFORMIX-4GL creates a subdirectory in the current directory with the name database-name.dbs. All of the system catalogs, data, and index files will be placed in this subdirectory, except for tables that you explicitly instruct INFORMIX-4GL to create elsewhere. 2. A database name can be up to 10 characters long and can contain only letters, digits, and underscores ( _ ). The first character must be a letter. If you store more than one database in a single directory, the database names must be unique.

INFORMIX-4GL Statement Syntax

7-41

CREATE DATABASE ( O )

3. For a user to have access to a database, the user must have execute (search) permission for each directory in the full pathname of database-name.dbs, as well as appropriate database privileges. (See the “GRANT” statement later in this chapter.) 4. See Appendix B for a description of the system catalogs. 5. The WITH LOG IN clause creates a transaction log file. Without this file, you cannot use the BEGIN WORK, COMMIT WORK, or the ROLLBACK WORK statements. You can use the START DATABASE statement to assign a log file to an existing database. See the section “Transactions” in Chapter 3 for further details. You must include the WITH LOG IN keywords and specify a transaction log file when you use the MODE ANSI keywords in the CREATE DATABASE statement. 6. A database created as MODE ANSI supports implicit transactions. All statements automatically appear within a transaction. (Do not use the BEGIN WORK statement in a program that accesses a MODE ANSI database.) You explicitly terminate a transaction when you issue a COMMIT WORK or ROLLBACK WORK statement. 7. You can determine the type of database that a user selects by checking the warning flag after a DATABASE statement in the SQLCA.SQLAWARN structure. See the section “SQLCA Record” in Chapter 3 for more information about the SQLCA.SQLAWARN character string. 8. You cannot drop MODE ANSI from a database. Once created or started as such, a database remains MODE ANSI. 9. The CREATE DATABASE statement cannot appear in a multi-statement PREPARE.

Examples
This CREATE DATABASE statement creates the stores database with a transaction log file:
CREATE DATABASE stores WITH LOG IN "/s/log/stores.log"

This CREATE DATABASE statement creates the stores database as MODE ANSI:
CREATE DATABASE stores WITH LOG IN "/u/myname/stores.log" MODE ANSI

7-42

INFORMIX-4GL Statement Syntax

CREATE DATABASE ( O )

Related Statements
DROP DATABASE, GRANT, START DATABASE

INFORMIX-4GL Statement Syntax

7-43

CREATE INDEX

CREATE INDEX
Overview
Use the CREATE INDEX statement to create an index for one or more columns in a table, and optionally to cluster the physical table in the order of the index. When more than one column is listed, the concatenation of the set of columns is treated as a single composite column for indexing.

Syntax
CREATE [ UNIQUE ] [ CLUSTER ] INDEX index-name ON table-name ( column-name [ ASC | DESC ] [ , . . . ] )

Explanation
CREATE INDEX are required keywords. UNIQUE CLUSTER

is a keyword to prevent duplicate entries in the column or composite column to which the index applies. is an optional keyword that causes the physical table to be ordered according to the order of the index. is the SQL identifier you want to assign to the index. You must assign a different identifier to each index in the database. is a required keyword. is the name of the table containing the column or columns that you want to index. is the name of a column to be indexed. To create an index that applies to several columns, enter a list of column names, separated by commas. All the columns must belong to the same table. is a keyword that specifies an index that INFORMIX-4GL maintains in ascending order. ASC is the default. is a keyword that specifies an index that INFORMIX-4GL maintains in descending order.

index-name

ON

table-name column-name

ASC DESC

7-44

INFORMIX-4GL Statement Syntax

CREATE INDEX

Notes
1. When INFORMIX-4GL executes the CREATE INDEX statement, it locks table-name in EXCLUSIVE mode. If another process is using table-name, INFORMIX-4GL cannot execute CREATE INDEX and returns an error. 2. You can include up to eight columns in a composite index. 3. The total length of all columns indexed in a single CREATE INDEX statement cannot exceed 120 bytes. 4. See the section “Indexing Strategy” in Chapter 3 for a discussion of indexing strategy. 5. The CREATE CLUSTER INDEX statement fails if a CLUSTER index already exists. 6. The CREATE CLUSTER INDEX statement fails if the table has an audit trail. 7. Only one index on a particular sequence of columns is allowed. 8. You cannot use the ROLLBACK WORK statement to undo a CREATE INDEX statement. 9. When you create a table, you can specify that a column or composite column will allow only unique values. You use the UNIQUE keyword in the CREATE TABLE statement. 10. You cannot create an ascending index on a column defined as UNIQUE in a CREATE TABLE statement. 11. A column list defined as having a UNIQUE CONSTRAINT in a CREATE TABLE statement receives a unique ascending composite index. You cannot use the CREATE INDEX statement to create an identical unique composite index. 12. In a composite index, you can include a column defined as UNIQUE. Similarly, in a composite index you can include a composite column list defined as UNIQUE. However, the column list in the CREATE INDEX statement cannot be identical to the column list defined as UNIQUE in the CREATE TABLE statement. 13. When more than one column is listed, the concatenation of the set of columns is treated as a single composite column for the purpose of indexing. 14. DISTINCT is a synonym for UNIQUE.

INFORMIX-4GL Statement Syntax

7-45

CREATE INDEX

Examples
CREATE UNIQUE INDEX i_ordnum ON orders (order_num)

CREATE CLUSTER INDEX i_ordnum2 ON orders (order_num DESC)

Related Statements
ALTER INDEX, CREATE TABLE, DROP INDEX

7-46

INFORMIX-4GL Statement Syntax

CREATE SYNONYM

CREATE SYNONYM
Overview
Use the CREATE SYNONYM statement to provide an alternative name for a table or view.

Syntax
CREATE SYNONYM synonym FOR table-name

Explanation
CREATE SYNONYM synonym
FOR

are required keywords. is an SQL identifier. is a required keyword. is the name of a table or view.

table-name

Notes
1. In a MODE ANSI database, the name of a synonym is qualified by the owner of the synonym (owner. synonym). You must specify owner when you refer to a synonym owned by another user. The use of the prefix owner is optional in a non-MODE ANSI database. INFORMIX-4GL does check the accuracy of owner, however, if you include it in a statement. See the section “Owner Naming” in Chapter 3 of this manual. 2. A user has no privileges under a synonym that were not granted for the table to which it applies. 3. When a synonym is created in an INFORMIX-4GL program, the owner of the synonym is the person who runs the program. 4. Synonyms are not to be confused with table aliases in SELECT statements. A synonym persists until you drop it with the DROP SYNONYM statement. Table aliases are useful only in the SELECT statement. 5. The CREATE SYNONYM statement cannot be rolled back. 6. For a database created or started as MODE ANSI, owner.synonym must be unique among all the synonyms, tables, and views in the database. In a non-MODE ANSI database, synonym must be unique.
INFORMIX-4GL Statement Syntax 7-47

CREATE SYNONYM

Example
CREATE SYNONYM cust FOR customer

Related Statements
DROP SYNONYM, SELECT

Note: Synonyms are very useful for referencing external objects with INFORMIX-OnLine. Refer to the INFORMIX-OnLine Programmer’s Manual for more information.

7-48

INFORMIX-4GL Statement Syntax

CREATE TABLE ( O )

CREATE TABLE ( O )
Overview
Use the CREATE TABLE statement to create a new table in the current database.

Syntax
CREATE [ TEMP ] TABLE table-name ( column-name datatype [ NOT NULL ] [ UNIQUE [ CONSTRAINT constr-name ] ] [ , . . . ] [ UNIQUE ( unique-col-list ) [ CONSTRAINT constr-name ] ] [ , . . . ] ) [ WITH NO LOG ] [ IN pathname ]

Explanation
CREATE TABLE TEMP

are required keywords. is an optional keyword. is the SQL identifier that you assign to the table. The first ten characters must be unique within a database. is the SQL identifier that you assign to each column. specifies the data type for each column. (See the following list for valid SQL data types.) are optional keywords to prevent entry of NULL values. is an optional keyword specifying that the column or composite unique-col-list cannot contain duplicate values. is a list (in parentheses) of the names of columns to include in a composite UNIQUE CONSTRAINT. is a keyword to indicate that constr-name is assigned in the statement. is the name of the UNIQUE CONSTRAINT. A constr-name must be a valid identifier that does not conflict with an existing constraint name. It can be optionally prefixed with the username of the owner of the table or, if you have DBA privileges, the username of another user.

table-name column-name datatype
NOT NULL UNIQUE

(unique-col-list)
CONSTRAINT

constr-name

INFORMIX-4GL Statement Syntax

7-49

CREATE TABLE ( O )

WITH NO LOG

are optional keywords that prevent logging of TEMP tables. In a database that uses logging, the default is to log TEMP tables also. is an optional keyword. specifies the full pathname in which to store the database table, with no extension to the filename. A pathname cannot be longer than 64 characters and must be enclosed within quotes ( " ). A pathname is of the form:
[ /directory-name/ . . . ] filename

IN

pathname

A list of valid SQL data types follows:
CHAR ( n ) CHARACTER SMALLINT INTEGER INT

is a character string of length n (where 1 ≤ n ≤ 32,511). is a synonym for CHAR. is a whole number from -32,767 to +32,767. is a whole number from -2,147,483,647 to +2,147,483,647. is a synonym for INTEGER. significant digits (precision) and n (≤ m) digits to the right of the decimal point (scale). See the section “Database Data Types” in Chapter 3 for more information.

DECIMAL [(m[,n])] is a decimal floating-point number with a total of m (≤ 32)

DEC NUMERIC SMALLFLOAT REAL FLOAT [(n)]

is a synonym for DECIMAL. is a synonym for DECIMAL. is a binary floating-point number corresponding to the ‘‘float’’ data type in the C language. is a synonym for SMALLFLOAT. is a binary floating-point number corresponding to the ‘‘double’’ data type in the C language. You can use n to specify the precision of a FLOAT data type, although the precision is ignored by INFORMIX-4GL. n must be a whole number between 1 and 14. is a synonym for FLOAT. is a DECIMAL type number, displayed with leading $. MONEY (m) = DECIMAL(m,2) and MONEY = DECIMAL(16,2). See the section “Database Data Types”’ in Chapter 3 for more information.

DOUBLE PRECISION MONEY [(m[,n])]

7-50

INFORMIX-4GL Statement Syntax

CREATE TABLE ( O )

SERIAL [(n)]

is a sequential integer assigned automatically by 4GL. You can assign an initial value n. The default starting integer is 1. is a date entered as a character string in one of the formats described in the following notes. is a moment in time that can include the year, month, day, hour, minute, second, and fraction of a second. See the following notes and the section “Database Data Types” in Chapter 3 for more information. is a positive or negative span of time that can include years and months, or else days, hours, minutes, seconds, and fractions of a second. See the following notes and the section “Database Data Types”’ in Chapter 3 for more information. See also Appendix J, “Working with DATETIME and INTERVAL Data.”

DATE DATETIME

INTERVAL

Notes
1. In a database created as MODE ANSI, the name of a table is qualified by the owner of the table (owner. table-name). You must specify owner when you refer to a table owned by another user. The use of the prefix owner is optional in a non-MODE ANSI database. INFORMIX-4GL checks the accuracy of owner, however, if you include it in a statement. See the section “Owner Naming” in Chapter 3 of this manual. 2. Table names must be unique within a database. If the database is MODE ANSI, the combination owner.tablename must be unique. 3. Column names must be unique within each table, but you can use duplicate names in different tables in the same database. See “SQL Identifiers” in Chapter 3 for guidelines on table names and column names. 4. Temporary tables created with the TEMP option exist for the duration of the program. 5. Users with CONNECT privilege can create temporary tables. 6. The default value in a column is NULL unless you include the NOT NULL keywords after the data type of the column. 7. If you designate a column as NOT NULL, users must enter a value into this column when performing an INSERT or UPDATE to the table.

INFORMIX-4GL Statement Syntax

7-51

CREATE TABLE ( O )

8. When you create a table in a database that is not MODE ANSI, all tablelevel privileges (except ALTER) are automatically granted to all users (PUBLIC). To restrict access privileges at the table level, you must revoke all privileges and grant those you want. In a database created as MODE ANSI, no default table-level privileges exist. You must explicitly grant these privileges. 9. You can specify no more than one SERIAL column in a table. 10. Enter DATE data type values in the sequence of month, day, and year, with any non-numeric character, including a blank, as a separator. Represent the month as the number of the month (January = 1 or 01, February = 2 or 02, and so on). Represent the day as the day of the month (1 or 01, 2 or 02, and so on). The year is stored as a four-digit number (0001 to 9999). If you enter two digits yy for the year, INFORMIX-4GL assumes that the year is 19yy. The following values are all acceptable representations of June 1, 1989: 06/01/89, 6.1.89, and 6-1-1989. 11. The DATE type is actually stored as the integer number of days since December 31, 1899. You can sort DATE columns and make chronological comparisons between two DATE columns. 12. The following table shows the file space requirements (in bytes) for each data type:
SERIAL SMALLINT INTEGER SMALLFLOAT FLOAT CHAR(n) DECIMAL(m,n) MONEY(m,n) DATE DATETIME INTERVAL 4 2 4 4 8 n 1 + m/2 1 + m/2 4 Depends on precision (see below) Depends on precision (see below)

Values in a DATETIME column are stored as decimal numbers, containing a sequence of digits representing the following fields: year, month, day, hour, minute, second, and fraction(n). All fields of a DATETIME column occupy two digits, except for the year and fraction fields. The year field requires four digits. The fraction field requires n digits, rounded up to an even number. The number of bytes required for a DATETIME column is equal to half the total number of digits for all fields, plus 1. Values in an INTERVAL column are stored as decimal numbers, containing a sequence of digits representing the following fields: year and month, or else year, month, day, hour, minute, second, and fraction(n). All
7-52 INFORMIX-4GL Statement Syntax

CREATE TABLE ( O )

fields of an INTERVAL column are represented by two digits, except for the first field and the fraction field. The number of digits in the first field is two, unless otherwise specified as part of the qualifier. The fraction field requires n digits. The number of bytes required for an INTERVAL column is equal to half the total number of digits for all fields, rounded up to an even number, plus 1. 13. The CREATE TABLE statement cannot be rolled back. 14. You can use the UNIQUE keyword to require that a single column or set of columns accept only unique data. A column or composite column list specified as UNIQUE is referred to as having a UNIQUE CONSTRAINT. 15. Each column in unique-col-list must be a column in the table and must not appear in the list more than once. 16. You cannot insert duplicate values into a UNIQUE column. 17. You cannot create an ascending index on a UNIQUE column. You cannot create an ascending composite index on an identical composite column list declared as UNIQUE. 18. You can include a UNIQUE column in a composite index created with the CREATE INDEX statement. 19. Use the ALTER TABLE statement to add or drop a UNIQUE CONSTRAINT from a column or composite column list. You can query the sysconstraints system catalog for the names of constraints. 20. You can include up to eight columns in a unique-col-list. The total length of all the columns in a unique-col-list cannot exceed 120 bytes. 21. If you do not specify a constr-name, INFORMIX-4GL generates one using the template u<tabid>_<index number>. If this name conflicts with an existing identifier, INFORMIX-4GL returns an error, and you must supply constr-name. 22. INFORMIX-4GL implements the UNIQUE CONSTRAINT by creating a unique index for every column declared as UNIQUE in the CREATE TABLE statement. A row is added to the sysindexes file for each index. Each index name is created with the format
[space]<tabid>_<index number>.

23. The keyword DISTINCT is a synonym for UNIQUE. 24. If the pathname in an IN clause specifies a filename that is different from the table-name, always use the table-name (rather than the filename) to refer to the table in subsequent SQL statements.

INFORMIX-4GL Statement Syntax

7-53

CREATE TABLE ( O )

25. The pathname in an IN clause can specify any valid directory and is not restricted to the directory that contains the current database. Use this feature if your database is becoming too large for your current disk volume. 26. If you use the WITH NO LOG keywords in a CREATE TABLE statement and the database does not use logging, the WITH NO LOG option is ignored. The WITH NO LOG option is supported on a MODE ANSI database. 27. Once you create a temporary table WITH NO LOG, you cannot turn on logging. A temporary table is, therefore, always logged or never logged.

Examples
The sequence of statements that creates the stores database follows:
CREATE DATABASE stores CREATE TABLE customer ( customer_num SERIAL(101), fname CHAR(15), lname CHAR(15), company CHAR(20), address1 CHAR(20), address2 CHAR(20), city CHAR(15), state CHAR(2), zipcode CHAR(5), phone CHAR(18) ) CREATE TABLE orders ( order_num order_date customer_num ship_instruct backlog po_num ship_date ship_weight ship_charge paid_date )

SERIAL(1001), DATE, INTEGER, CHAR(40), CHAR(1), CHAR(10), DATE, DECIMAL(8,2), MONEY(6), DATE

CREATE TABLE items ( item_num order_num 7-54 INFORMIX-4GL Statement Syntax

SMALLINT, INTEGER,

CREATE TABLE ( O )

stock_num manu_code quantity total_price ) CREATE TABLE stock ( stock_num manu_code description unit_price unit unit_descr )

SMALLINT, CHAR(3), SMALLINT, MONEY(8)

SMALLINT, CHAR(3), CHAR(15), MONEY(6), CHAR(4), CHAR(15)

CREATE TABLE manufact ( manu_code CHAR(3), manu_name CHAR(15) ) CREATE TABLE state ( code sname )

CHAR(2), CHAR(15)

The following statement creates the tab1 table. In tab1, column c1 is UNIQUE and the constraint is named uc1. A UNIQUE CONSTRAINT is also applied to the composite columns c3 and c4.
CREATE TABLE tab1 ( c1 INTEGER NOT NULL UNIQUE CONSTRAINT uc1, c2 INTEGER, c3 INTEGER NOT NULL, c4 CHAR(10) NOT NULL, UNIQUE (c3,c4) )

INFORMIX-4GL Statement Syntax

7-55

CREATE TABLE ( O )

The following statement creates the employee table. The data for the table is stored in the file /a/work/employ.dat. The index information is stored in the file /a/work/employ.idx.
CREATE TABLE employee ( employ_num SERIAL(101), fname CHAR(15), lname CHAR(15), address CHAR(20), city CHAR(15), state CHAR(2), zipcode CHAR(5), phone CHAR(18) hire_date DATE ) IN "/a/work/employ"

The following example shows a use of the DATETIME and INTERVAL data types:
CREATE TABLE tv_programs ( prog_title CHAR(32), air_date DATETIME YEAR TO DAY NOT NULL, air_time DATETIME HOUR TO MINUTE, duration INTERVAL HOUR TO SECOND )

The following example shows how to prevent logging of TEMP tables in a database that uses logging:
CREATE TEMP TABLE tab2 (fname CHAR(15), lname CHAR(15)) WITH NO LOG

Related Statements
ALTER TABLE, CREATE DATABASE, CREATE INDEX, DROP DATABASE, DROP TABLE, GRANT, REVOKE

7-56

INFORMIX-4GL Statement Syntax

CREATE VIEW

CREATE VIEW
Overview
Use CREATE VIEW to create a new view based on existing tables and views in the database.

Syntax
CREATE VIEW view-name [ ( column-list ) ] AS SELECT-statement [ WITH CHECK OPTION ]

Explanation
CREATE VIEW

are required keywords. is an SQL identifier. is a list of one or more identifiers that name the columns of view-name. is a required keyword. is a SELECT statement. are optional keywords.

view-name column-list
AS SELECT-statement WITH CHECK OPTION

Notes
1. In a database created as MODE ANSI, the name of a view is qualified by the owner of the view (owner.view-name). You must specify owner when you refer to a view owned by another user. The use of the prefix owner. is optional in a non-MODE ANSI database. INFORMIX-4GL does check the accuracy of owner if you include it in a statement, however. See the section “Owner Naming” in Chapter 3 of this manual. 2. Except for the statements in the following list, you can use a view in any SQL statement (including form specifications) where you can use a table.
ALTER TABLE ALTER INDEX CREATE INDEX DROP INDEX LOCK TABLE RENAME TABLE

The view behaves like a table with the name view-name and consists of the set of rows and columns returned by the SELECT-statement each time the
INFORMIX-4GL Statement Syntax 7-57

CREATE VIEW

SQL statement is executed using the view. The view reflects changes to the

underlying tables, but with one exception. If the view is defined with a SELECT * clause, it has only the columns that are in the underlying tables at the time the view is created. New columns added subsequently to the underlying tables using the ALTER TABLE statement will not appear in the view. See the section “Views” in Chapter 3 for more information. 3. When you do not specify column-list for view-name, the view inherits the column names of the underlying tables. If the SELECT-statement returns an expression, the corresponding column in the view is called a virtual column. You must provide a name for virtual columns. You must also provide a column name when the select-list has duplicate column names when the table prefixes are stripped. For example, when both orders.order_num and items.order_num appear in the select-list, you must provide two separate column names to label them in the CREATE VIEW statement. 4. Data types of the columns of the view are inherited from the tables from which they come. Data types of virtual columns are determined from the nature of the expression. 5. For a database created as MODE ANSI, owner.view-name must be unique among all the tables, views, and synonyms in the database. In a nonMODE ANSI database, view-name must be unique. 6. You can define a view in terms of other views, except that you must abide by the restrictions on queries listed in the section “Querying Through Views” in Chapter 3. 7. The SELECT-statement cannot have an ORDER BY clause nor a UNION operator. 8. You must have SELECT privilege on all columns from which the view is derived. 9. The WITH CHECK OPTION clause instructs INFORMIX-4GL to ensure that all modifications to the underlying tables made through the view satisfy the definition of the view. 10. The CREATE VIEW statement cannot be rolled back.

Example
CREATE VIEW palo_alto AS SELECT * FROM customer WHERE city = "Palo Alto"

7-58

INFORMIX-4GL Statement Syntax

CREATE VIEW

Related Statements
CREATE TABLE, DROP VIEW

INFORMIX-4GL Statement Syntax

7-59

CURRENT WINDOW

CURRENT WINDOW
Overview
Use the CURRENT WINDOW statement to make a window the current or topmost window.

Syntax
CURRENT WINDOW IS { window-name | SCREEN }

Explanation
CURRENT WINDOW IS

are required keywords. is the name of the window that you want to be the current window. is a keyword that refers to the entire screen.

window-name
SCREEN

Notes
1. A window becomes completely visible when it becomes the current window. In the process, other inactive windows may be obscured. 2. All input and output is done in the current window. 3. If window-name contains a screen form, the screen form becomes the current form. 4. The terminal screen is the current window when a program starts. 5. If you specify SCREEN as the window-name, the entire screen becomes the current window. 6. See also the CLEAR statement, which removes any text from the screen, and makes the entire screen the current window. 7. The DISPLAY ARRAY, INPUT, INPUT ARRAY, and MENU statements run in the current window. When you change the current window while one of these statements is active and then resume the statement, the original window is restored as the current window. For example, you can use an ON KEY clause in an INPUT statement to allow the user to open a new win-

7-60

INFORMIX-4GL Statement Syntax

CURRENT WINDOW

dow by pressing a specific key during input. When the user presses the designated key, INFORMIX-4GL executes the statements in the ON KEY clause and then resumes input from the window that was current before the ON KEY break. 8. The context of each window includes the values for the Prompt, Message, Form, and Comment lines. When a window becomes the current window, these values are restored. 9. When working with multiple windows, INFORMIX-4GL maintains a list or ‘‘stack’’ of all open windows. It adds the current window to its window list whenever you open a new window. The new window then becomes the current window. When you close a window, INFORMIX-4GL removes it from its window list. The topmost window (of those that remain) becomes the current window. 10. When you specify a current window, INFORMIX-4GL adjusts the window list by moving the new current window to the top, and closing the gap in the list left by this window.

Examples
CURRENT WINDOW IS win1 CURRENT WINDOW IS SCREEN

Related Statements
CLEAR WINDOW, CLOSE WINDOW, OPEN WINDOW, OPTIONS

INFORMIX-4GL Statement Syntax

7-61

DATABASE

DATABASE
Overview
Use the DATABASE statement to declare an accessible database as the current database.

Syntax
DATABASE database-name [ EXCLUSIVE ]

Explanation
DATABASE

is a required keyword. is the name of a database, or a program variable that evaluates to the name of a database. is an optional keyword.

database-name
EXCLUSIVE

Notes
1. If you want to specify a database that does not reside in your current directory or in a directory specified by the DBPATH environment variable (described in Appendix C), you must follow the DATABASE keyword with a program variable that evaluates to the full pathname of the database (excluding the .dbs extension). 2. In an INFORMIX-4GL program, the DATABASE statement can serve two purposes, one procedural and the other non-procedural. It makes the named database the current database (procedural), and it tells the compiler where to find information about variables defined LIKE columns in a table (non-procedural). To serve the non-procedural purpose, the DATABASE statement must occur outside any routine and precede the GLOBALS statements when you use indirect data typing with the LIKE clause. The database-name must be explicitly expressed and not given as a program variable. You cannot use the EXCLUSIVE keyword in this context. If you use the DATABASE statement in this non-procedural way, INFORMIX-4GL begins the MAIN program block with the database-name as the current database. Ordinarily, you use only one database, and the preceding procedure is enough. If you do not have global variables defined LIKE database columns, but still want to interact with a database, you can use the
7-62 INFORMIX-4GL Statement Syntax

DATABASE

DATABASE statement in a purely procedural way. In this case, it must occur within a routine and must follow any DEFINE statements within that routine. In this case, database-name can be a program variable, and you can use the EXCLUSIVE keyword.

3. The DATABASE statement closes any other current database. 4. If you close one database and open another in a program, you cannot define variables LIKE columns in the second database. 5. The EXCLUSIVE option opens the database in an exclusive mode and allows only the current user access to the database. To allow others access to the database, you must execute the CLOSE DATABASE statement and then reopen the database. 6. You can determine the type of database a user selects by checking the warning flag after a DATABASE statement in the SQLCA.SQLAWARN structure. See the section “SQLCA Record” in Chapter 3 for more information about SQLCA.SQLAWARN. 7. You cannot include the DATABASE statement in a multi-statement PREPARE.

Example
DATABASE stores

Related Statements
CREATE DATABASE, DROP DATABASE, CLOSE DATABASE

INFORMIX-4GL Statement Syntax

7-63

DECLARE

DECLARE
Overview
Use the DECLARE statement to assign a cursor name to a SELECT or INSERT statement. A cursor is required for a SELECT statement that selects more than one row.

Syntax
DECLARE cursor-name [ SCROLL ] CURSOR [ WITH HOLD ] FOR { SELECT-statement [ FOR UPDATE [ OF column-list ] ] | INSERT-statement | statement-id }

Explanation
DECLARE

is a required keyword. is an INFORMIX-4GL identifier. is an optional keyword that can be used only with a statement or a statement_id of a SELECT statement that you PREPAREd. are required keywords. are optional keywords to prevent the cursor from being closed when each transaction ends. is a SELECT statement. are keywords that are required if the cursor will be used to modify existing rows. is an optional keyword. is a list of column names from tables listed in the FROM clause of SELECT-statement. is an INSERT statement. is the identifier of an INSERT or SELECT statement that you previously PREPAREd.

cursor-name
SCROLL

CURSOR FOR WITH HOLD SELECT-statement FOR UPDATE OF

column-list
INSERT-statement

statement-id

Notes
1. You must DECLARE a SELECT cursor before you can use it in an OPEN, FETCH, FOREACH, DELETE, UPDATE, or CLOSE statement. You must
7-64 INFORMIX-4GL Statement Syntax

DECLARE

DECLARE an INSERT cursor before you can use it in an OPEN, PUT, FLUSH, or CLOSE statement.

2. You can DECLARE a cursor as SCROLL or WITH HOLD or both. 3. SCROLL cursors, INSERT cursors, and cursors WITH HOLD are Informix extensions to ANSI standard syntax. You receive a warning if you compile with the -ansi flag, or if you have set the DBANSIWARN environment variable and include the SCROLL, INSERT, or WITH HOLD keywords in a program. 4. Unless you include the WITH HOLD keywords, INFORMIX-4GL closes the cursor after each transaction. (A CLOSE DATABASE statement closes all cursors, including cursors WITH HOLD.) 5. The following rules apply when you use cursor manipulation statements in a non-MODE ANSI database with explicit transactions:

• You must OPEN and CLOSE a regular cursor that is FOR UPDATE and
an INSERT cursor within a transaction.

• All FLUSH and PUT statements must appear within a transaction. • Each UPDATE, INSERT, or DELETE action must take place within a
transaction.

• You can OPEN and CLOSE a cursor WITH HOLD that is FOR UPDATE
outside a transaction. Any FETCH using it, however, must take place within a transaction. These requirements are automatically satisfied if the current database is a MODE ANSI database. 6. Unlike other cursors, a cursor WITH HOLD is not closed when you execute a COMMIT WORK or ROLLBACK WORK statement. You must explicitly CLOSE a cursor WITH HOLD. (A CLOSE DATABASE statement closes all cursors, including cursors WITH HOLD.) 7. You must include the SCROLL keyword in the DECLARE statement for a SELECT cursor if you are going to issue a statement that includes the PREVIOUS, LAST, FIRST, CURRENT, RELATIVE, or ABSOLUTE keywords. SCROLL enables a cursor to FETCH rows in random order. 8. You must specify the statement-id to identify a SELECT or INSERT statement in a previous PREPARE statement. 9. The column names in an OF column-list clause do not need to be in the select-list of the SELECT clause. 10. If the SELECT statement has no INTO clause, the subsequent FETCH statement must specify INTO variable-list.

INFORMIX-4GL Statement Syntax

7-65

DECLARE

11. Do not use INTO with an array element subscripted by a variable in the SELECT statement because the subscript is evaluated at the time of the DECLARE, not at the time of any subsequent FETCH. You can use a constant to indicate the array element. Use FETCH INTO when the output variable is an array element subscripted by a variable or a constant. 12. You cannot use the FOR UPDATE clause in the DECLARE statement for a SELECT cursor that includes the SCROLL keyword or an ORDER BY clause. 13. If you use the FOR UPDATE clause, the SELECT statement is limited to a single table. 14. You must use the FOR UPDATE clause in the DECLARE statement for a non-scrolling SELECT cursor if you will later use either the UPDATE or the DELETE statement with the WHERE CURRENT OF cursor-name option. The cursor FOR UPDATE can include or omit WITH HOLD. 15. If you specify one or more columns in the FOR UPDATE clause, you can update only those columns in a subsequent UPDATE WHERE CURRENT OF statement. (If you do not specify any columns in the FOR UPDATE clause, you can update any column in a subsequent UPDATE WHERE CURRENT OF statement.) 16. When you DECLARE a cursor FOR UPDATE, each FETCH executed on that cursor locks the FETCHed row in exclusive mode. For a database without transactions, the lock is released when you execute the next FETCH statement or when you CLOSE the cursor (whichever occurs first), regardless of whether you UPDATE the row. For a database with transactions, each row that you UPDATE remains locked for the duration of the transaction. These locks are released only when you end the transaction (issue a COMMIT WORK or ROLLBACK WORK statement). See the section“Locking” in Chapter 3 for a more detailed description of table-level and row-level locking. 17. If your database has a transaction log but is not MODE ANSI, you must issue a BEGIN WORK statement before you OPEN a cursor that you DECLAREd FOR UPDATE but not WITH HOLD. (You can DECLARE a cursor WITH HOLD FOR UPDATE outside a transaction, but you cannot roll back any changes to a non-MODE ANSI database that the cursor performs outside a transaction. In this situation, each UPDATE is automatically committed as a singleton transaction.)

7-66

INFORMIX-4GL Statement Syntax

DECLARE

18. INFORMIX-4GL evaluates the variables in a DECLARE statement at the time when you OPEN the cursor, except for those variables that include subscripts. INFORMIX-4GL evaluates the subscript when you DECLARE the cursor and evaluates the variable when you OPEN the cursor. In the following example, INFORMIX-4GL selects rows where the value in the customer_num column equals 106:
LET a = 101 DECLARE q_curs CURSOR FOR SELECT * FROM orders WHERE customer_num = a LET a = 106 OPEN q_curs

In the next example, INFORMIX-4GL selects rows where the value in the customer_num column equals a[5]:
LET i = 5 DECLARE q_curs CURSOR FOR SELECT * FROM orders WHERE customer_num = a[i] LET i = 2 OPEN q_curs

19. You cannot DECLARE a cursor for an INSERT statement that contains an embedded SELECT statement. 20. If you DECLARE a cursor for an INSERT statement that has a VALUES clause containing only constants, INFORMIX-4GL does not create a buffer, but merely keeps count of the number of inserts. Such inserts are never flushed as the result of a PUT statement. Flushing occurs when you issue a FLUSH or CLOSE cursor statement. 21. The DECLARE statement for a cursor must physically appear before any statement that specifies the cursor. The cursor-name has meaning from the point at which you DECLARE it, to the end of the same source file. It is not a global identifier that can be referenced in a separate source file. 22. You cannot specify a SCROLL INSERT cursor.

INFORMIX-4GL Statement Syntax

7-67

DECLARE

Examples
DECLARE scurs CURSOR FOR SELECT * FROM customer DECLARE wh_curs CURSOR WITH HOLD FOR st_1 DECLARE ucurs CURSOR FOR SELECT * FROM customer WHERE customer_num > 110 FOR UPDATE OF fname, lname DECLARE icurs CURSOR FOR INSERT INTO stock VALUES (stock_no, man_code, descr, u_price, unit, u_desc) DECLARE s_curs SCROLL CURSOR FOR SELECT * FROM orders WHERE customer_num = 104

Related Statements
CLOSE, DELETE, FETCH, FLUSH, FOREACH, FREE, OPEN, PREPARE, PUT, SELECT, UPDATE

7-68

INFORMIX-4GL Statement Syntax

DEFER

DEFER
Overview
Use the DEFER statement to keep INFORMIX-4GL from terminating your program whenever a user presses the Interrupt key (usually CTRL-C or DEL) or the QUIT key (usually CTRL-\).

Syntax
DEFER { INTERRUPT | QUIT }

Explanation
DEFER INTERRUPT QUIT

is a required keyword. is an optional keyword. is an optional keyword.

Notes
1. In the absence of the DEFER statement, your program will stop immediately whenever Interrupt or Quit is pressed. 2. The DEFER statement sets a global flag (int_flag for INTERRUPT and quit_flag for QUIT) to non-zero whenever the user presses the Interrupt or Quit key. The programmer must reset the flags to zero. 3. If the DEFER INTERRUPT statement has been executed and the user subsequently enters an Interrupt during an INPUT statement, program control will leave the INPUT statement and int_flag will be set. This applies to the CONSTRUCT, INPUT ARRAY, and PROMPT statements, as well. 4. The DEFER INTERRUPT statement can occur only once in a program, and then only in the MAIN program block. After being executed, it remains in effect for the duration of the program. This characteristic applies as well to the DEFER QUIT statement.

Example
DEFER INTERRUPT

INFORMIX-4GL Statement Syntax

7-69

DEFER

Related Statement
WHENEVER

7-70

INFORMIX-4GL Statement Syntax

DEFINE

DEFINE
Overview
Use the DEFINE statement to define identifiers in your program and to set aside adequate memory for each 4GL program variable.

Syntax
DEFINE variable-list { type | LIKE table.column | RECORD { LIKE table.* | variable-list [ , . . . ] END RECORD } } [ , . . . ]

Explanation
DEFINE

is a required keyword. is one or more identifiers of program variable. is one of these data types (as defined in Chapter 2):
SMALLINT INTEGER INT DECIMAL [ (m [ , n ] ) ] DEC [ ( m [ , n ] ) ] NUMERIC [ (m [ , n ] ) ] SMALLFLOAT REAL RECORD [ LIKE table. * ] FLOAT [ ( n ) ] DOUBLE PRECISION [ ( n ) ] MONEY [ (m [ , n ] ) ] CHAR [ ( n ) ] CHARACTER [ ( n ) ] DATE DATETIME qualifier INTERVAL qualifier

variable-list type

ARRAY [ i , j , k ] OF type

LIKE

is a keyword to specify the data type indirectly. is the full identifier for a column in the current database. The DATABASE statement must precede DEFINE statements that use indirect typing. is a data type that describes a set of variables of possibly differing database data types. is the name of a database table. are keywords that follow the declaration of the last element of a program record.
INFORMIX-4GL Statement Syntax 7-71

table.column

RECORD

table
END RECORD

DEFINE

Notes
1. Elements of records are addressed as record_name. column_name. 2. If the DEFINE statement is used in a function or MAIN program block, it must be the first statement to appear in that function or MAIN program block. 3. See the “Data Types” section in Chapter 2 for a full discussion of 4GL data types for 4GL variables. 4. The section “Language Conventions” in Chapter 2 describes the identifiers of 4GL variables and their scope of reference.

Example
DEFINE p_customer RECORD LIKE customer.*, p_orders RECORD order_num LIKE orders.order_num, order_date LIKE orders.order_date, po_num LIKE orders.po_num, ship_instruct LIKE orders.ship_instruct END RECORD, p_stock ARRAY[30] OF RECORD s_num LIKE stock.stock_num, m_code LIKE stock.manu_code END RECORD, stock_tot SMALLINT

Related Statements
GLOBALS, LET

Note: INFORMIX-OnLine supports additional data types. Refer to the INFORMIX -Online Programmer’s Manual for more information.

7-72

INFORMIX-4GL Statement Syntax

DELETE

DELETE
Overview
Use the DELETE statement to delete one or more rows from a table.

Syntax
DELETE FROM table-name [ WHERE { condition | CURRENT OF cursor-name } ]

Explanation
DELETE FROM are required keywords.

table-name
WHERE

is the name of the table from which you want to delete rows. is a keyword. is a condition of a standard WHERE clause. (See the SELECT statement for further information.) INFORMIX-4GL deletes all rows that satisfy the condition in the WHERE clause. are keywords. is the SQL identifier of a previously DECLAREd and positioned cursor.

condition

CURRENT OF

cursor-name

Notes
1. When you create a database with transactions that is not MODE ANSI, each DELETE statement you execute is treated as a single transaction, even if you do not use the BEGIN WORK and COMMIT WORK or ROLLBACK WORK statements. 2. Each row affected by a DELETE statement within a transaction is locked for the duration of the transaction; therefore, a single DELETE statement that affects a large number of rows locks the rows until the entire operation is completed. If the number of rows affected is very large, you might exceed the limits that your operating system places on the maximum number of simultaneous locks. If you exceed these limits, you may want to either reduce the scope of the DELETE statement or lock the entire table before executing the statement. See the section “Locking” in Chapter 3 for a more detailed description of table-level and row-level locking in INFORMIX-4GL.
INFORMIX-4GL Statement Syntax 7-73

DELETE

3. To use the WHERE CURRENT OF option, you must have previously DECLAREd the cursor-name with the FOR UPDATE option. 4. If you use the CURRENT OF option, DELETE removes the row of the active set at the current position of the cursor. The cursor is left pointing between the remaining rows and you cannot use it for DELETE or UPDATE until you reposition it with a FETCH statement. 5. If your database has transactions and you use the WHERE CURRENT OF clause, you must execute the DELETE statement within a transaction.

Examples
DELETE FROM items WHERE order_num = onum DELETE FROM orders WHERE CURRENT OF query_cursor

These statements remove all items belonging to the order number set in the program variable onum from the items table and remove the row from the orders table pointed to by the cursor query_cursor.

Related Statements
DECLARE, INSERT, UPDATE

7-74

INFORMIX-4GL Statement Syntax

DISPLAY

DISPLAY
Overview
Use the DISPLAY statement to display data values on the screen.

Syntax
DISPLAY{ BY NAME variable-list | variable-list [ TO { field-list | screen-record [ [ n ] ].* } [ , . . . ] | AT row, column ] } [ ATTRIBUTE ( attribute-list ) ]

Explanation
DISPLAY BY NAME

is a required keyword. are keywords instructing INFORMIX-4GL to match the names of variables with screen field names. is a required list of one or more program variables and/or constants, separated by commas. is a keyword to specify that INFORMIX-4GL will display the variable_list in screen fields or in a screen array. is a list of one or more screen field names in the current screen form. is the identifier of a collection of field names defined in a form specification as a SCREEN RECORD. is an integer, enclosed in brackets, to specify the row of a screen array (beginning with line 1) where the variable-list should be displayed. is a keyword to specify coordinates of a location on the screen or in the current window. is an integer variable or constant, indicating a row of the screen or current window. is an integer variable or constant, indicating a column of the screen or current window. is a keyword to specify screen display attributes. is a list (in parentheses) of one or more screen display attributes, separated by commas.

variable-list
TO

field-list screen-record [n]

AT

row column
ATTRIBUTE

(attribute-list)

INFORMIX-4GL Statement Syntax

7-75

DISPLAY

Notes
1. The DISPLAY statement (without the BY NAME, TO, or AT keywords) displays variable-list on the next line. This can format displayed values with CLIPPED, USING, and COLUMN, but not with the ATTRIBUTE (attribute-list) clause. 2. Changing the data stored in program variables has no effect on the current screen display until this statement is executed again. 3. INFORMIX-4GL displays number values right justified, and character strings left justified in the screen field. 4. If a character value does not fit in the field, its display is truncated. If a number value does not fit in the field, INFORMIX-4GL fills the field with asterisks (*) to indicate an overflow. 5. The DISPLAY BY NAME option selects screen fields, based on the identity of the program variable name and the field name. INFORMIX-4GL uses only the suffix portion of these variable names and field names. This option results in an error (setting status < 0) unless the suffixes are unique and unambiguous. 6. The DISPLAY TO screen-record [n].* option lists constants or program variables on the nth row of a screen array. You can move such values up or down with the SCROLL statement. 7. You can use the DISPLAY AT statement to display variable-list at a specified location on the screen or in the current window. You can use CLIPPED and USING to format displayed values. 8. The coordinates start with row 1 and column 1 in the upper left corner of the screen or current 4GL window. The row coordinates increase as you go down, and the column coordinates increase as you move from left to right. On a standard terminal screen, the lower right corner has the coordinates (24, 80). 9. An error occurs (setting status < 0 ) if either the row or column exceeds the dimensions of the screen or of the current window. 10. If you use the AT option when the last element of variable-list is a NULL CHAR value, INFORMIX-4GL clears to the end of the line. For example,
DISPLAY "" AT n,1

clears the nth line of the screen or of the current window. 11. If your program includes a DISPLAY statement followed by a DISPLAY AT statement, INFORMIX-4GL clears the screen or the current window before producing the second display.

7-76

INFORMIX-4GL Statement Syntax

DISPLAY

12. If no TO clause or AT clause specifies a location, a compile-time error occurs if you use the ATTRIBUTE clause. 13. In a DISPLAY TO statement, any screen attributes specified in attribute-list apply to all the fields in field-list or screen-record. 14. If you use the ATTRIBUTE clause, none of the default attributes listed in syscolatt or in the form specification file for fields in field-list or screen-record apply. The attribute-list temporarily overrides any attributes specified in an OPTIONS, DISPLAY FORM, or OPEN WINDOW statement for these fields. 15. These keywords can appear in the ATTRIBUTE clause:
WHITE = NORMAL YELLOW = BOLD MAGENTA = BOLD RED = BOLD CYAN = DIM GREEN = DIM BLUE = DIM BLACK = INVISIBLE REVERSE BLINK UNDERLINE

You can specify zero or one of the keywords in the left-hand columns, and from zero to three from the right-hand column (but some terminals may not support some combinations). On color terminals, NORMAL is interpreted as WHITE, BOLD as RED, DIM as BLUE, and INVISIBLE as BLACK. Do not include the equal ( = ) sign, which in this table shows the effect on monochrome terminals of keywords that specify color. These keywords cannot produce the effects suggested by their names unless the termcap or terminfo files and the physical terminals support the attribute. (See Appendix I, “Modifying termcap and terminfo.”) Note: Some terminal entries in termcap or terminfo include the sg#1 or xmc#1 capabilities. On these terminals, the first character of variable-list is replaced by a blank if you use the DISPLAY AT statement with any display attribute. To be safe, make sure that the first character of the variable-list is a blank if you specify any display attributes. 16. On UNIX systems that use terminfo files rather than termcap, INFORMIX-4GL does not support attributes that specify colors, and the only valid attribute-list keywords are REVERSE and UNDERLINE.

INFORMIX-4GL Statement Syntax

7-77

DISPLAY

Examples
DISPLAY BY NAME lname, fname DISPLAY "There are ", num USING "-####", " items in the list" AT 12,1 ATTRIBUTE(REVERSE, BLUE) DISPLAY add_cust.* TO sc_addr[4].*

Related Statements
INPUT, DISPLAY ARRAY, DISPLAY FORM, OPEN WINDOW

7-78

INFORMIX-4GL Statement Syntax

DISPLAY ARRAY

DISPLAY ARRAY
Overview
Use the DISPLAY ARRAY statement to display a program array in a screen array, and to permit scrolling through the array.

Syntax
DISPLAY ARRAY record-array TO screen-array.* [ ATTRIBUTE ( attribute-list ) ] { ON KEY ( key-list ) statement ... [ EXIT DISPLAY ] ... END DISPLAY | [ END DISPLAY ] }

Explanation
DISPLAY ARRAY

are required keywords. is a program array name. Usually, record-array is an array of records. is a required keyword. is the name of a screen record, defined in a form specification file, that corresponds to the fields in a row of a screen array. is an optional keyword. is a list of one or more screen-display attributes. are optional keywords. is usually a list of one or more function or CTRL key designations. It can also include ESC (if you have specified another key as the Accept key in the OPTIONS statement) or INTERRUPT (if you have executed a DEFER INTERRUPT statement). is an INFORMIX-4GL statement. is a statement that causes INFORMIX-4GL to exit from the DISPLAY ARRAY statement. is a statement that terminates a DISPLAY ARRAY statement. It is required only when an ON KEY clause is used,
INFORMIX-4GL Statement Syntax 7-79

record-array
TO

screen-array

ATTRIBUTE

attribute-list
ON KEY

key-list

statement
EXIT DISPLAY END DISPLAY

DISPLAY ARRAY

or when the DISPLAY ARRAY statement appears as the last statement in a clause and is followed by an ON KEY clause.

Notes
1. You must call set_count() with the number of filled rows in record-array prior to executing DISPLAY ARRAY. 2. The user can use the [ ↓ ] key to move the cursor down one row at a time and to scroll to the bottom of the screen array; the [ ↑ ] key to move the cursor up one row at a time and to scroll to the top of the screen array; [ F3 ] to scroll to the next page; and [ F4 ] to scroll to the previous page. You can use the OPTIONS statement to assign these functions to other keys. In addition, you must define the key assignments properly in the termcap or terminfo files. 3. The user can exit from the DISPLAY ARRAY statement by pressing ESC, or by pressing the key specified as the ACCEPT KEY in the OPTIONS statement. The program should tell the user to do this. 4. The following conditions require that an END DISPLAY statement appear in your program:

• The DISPLAY ARRAY statement includes one or more ON KEY clauses. • The DISPLAY ARRAY statement appears as the last statement in a
clause (within an INPUT statement, for example) and is followed by an
ON KEY clause.

5. By default, INFORMIX-4GL displays number variables right-justified and character variables left-justified in the screen field. 6. If a displayed character value is larger than the field, INFORMIX-4GL truncates the value. If a displayed number value is larger than the field, INFORMIX-4GL fills the field with asterisks (*). 7. The attributes listed in attribute-list apply to all the fields in screen-array. 8. If you use the ATTRIBUTE clause, none of the default attributes listed in syscolatt or in the form specification file for the fields in screen-array will apply.

7-80

INFORMIX-4GL Statement Syntax

DISPLAY ARRAY

9. The following list shows the screen attributes allowed in the ATTRIBUTE clause:
WHITE = NORMAL YELLOW = BOLD MAGENTA = BOLD RED = BOLD CYAN = DIM GREEN = DIM BLUE = DIM BLACK = INVISIBLE REVERSE BLINK UNDERLINE

On color terminals, NORMAL is interpreted as WHITE; BOLD as RED; DIM as BLUE; and INVISIBLE as BLACK. If you have a colornames file, you can use the color names listed there. 10. INFORMIX-4GL passes control to the statements following an ON KEY clause when the user presses a key in key-list. After executing the statements in the ON KEY clause, INFORMIX-4GL resumes the display with the cursor in the same location as before the ON KEY break, unless NEXT FIELD and EXIT DISPLAY are implemented. 11. The notation for function keys is F1, F2, F3, . . . F36 . The notation for CTRL keys is CONTROL-key where key is any letter except A, D, H, L, R, or X. The notation for is ESC or ESCAPE. The notation for the Interrupt key is INTERRUPT. 12. By default, both ESCAPE and INTERRUPT are exits from the DISPLAY ARRAY statement. If the DEFER INTERRUPT statement has been executed, an INTERRUPT causes INFORMIX-4GL to set int_flag to non-zero, and terminates the DISPLAY ARRAY statement (unless the Interrupt key has been redefined in an ON KEY clause). Otherwise, an Interrupt causes an immediate program stop. 13. You can include the following keys in a key-list under the stated conditions:

ESCAPE, if you have specified another key as the Accept key in the OPTIONS statement.

• [ F3 ], if you have specified another key as the Next key in the OPTIONS
statement.

• [ F4 ], if you have specified another key as the Previous key in the
OPTIONS statement.

• The Interrupt key, if you have executed a DEFER INTERRUPT statement. (When the user presses the Interrupt key under these conditions, INFORMIX-4GL executes the statements in the ON KEY

INFORMIX-4GL Statement Syntax

7-81

DISPLAY ARRAY

clause and sets int_flag to non-zero but does not terminate the DISPLAY ARRAY statement.) Do not use the following keys in a key-list:

CTRL-A, CTRL-D, CTRL-H, CTRL-L, CTRL-R, or CTRL-X since these CTRL keys are reserved for editing functions in the CONSTRUCT, INPUT, and INPUT ARRAY statements.

• Other keys that have special meaning for your operating system.
14. Do not execute PROMPT, INPUT, or INPUT ARRAY statements within the ON KEY clause of a DISPLAY ARRAY statement. You can, however, call a function that executes one of these statements.

Examples
DISPLAY ARRAY pa_array TO sc_array.* DISPLAY ARRAY p_items TO s_items.* ON KEY (CONTROL-E) MESSAGE "Highlight an item and ", "press the ACCEPT key." END DISPLAY INPUT BY NAME p_customer.* AFTER FIELD company ... DISPLAY ARRAY pa_array TO sc_array.* END DISPLAY ON KEY (CONTROL-B) ... END INPUT

Related Statements
DISPLAY, SCROLL

7-82

INFORMIX-4GL Statement Syntax

DISPLAY FORM

DISPLAY FORM
Overview
Use the DISPLAY FORM statement to display a pre-compiled screen form.

Syntax
DISPLAY FORM form-name [ ATTRIBUTE ( attribute-list ) ]

Explanation
DISPLAY FORM are required keywords.

form-name
ATTRIBUTE

is an INFORMIX-4GL identifier that has been associated with a screen form in an OPEN FORM statement. is an optional keyword. is a list of one or more screen attributes that will apply to the delimiters of the screen form, and to any text outside display fields.

attribute-list

Notes
1. DISPLAY FORM displays the screen form starting on the third line of the terminal screen or window. You can change the starting line for all windows (including the screen) by using the OPTIONS statement or for a specific window by using an ATTRIBUTE clause in the appropriate OPEN WINDOW statement. 2. The following list shows the screen attributes allowed in the ATTRIBUTE clause:
WHITE = NORMAL YELLOW = BOLD MAGENTA = BOLD RED = BOLD CYAN = DIM GREEN = DIM BLUE = DIM BLACK = INVISIBLE REVERSE BLINK UNDERLINE

On color terminals, NORMAL is interpreted as WHITE, BOLD as RED, DIM as BLUE, and INVISIBLE as BLACK. If you have a colornames file, you can use the color names listed there. (See Appendix I.)
INFORMIX-4GL Statement Syntax 7-83

DISPLAY FORM

3. INFORMIX-4GL issues an error if a window is not large enough to display a form. See Chapter 13 of the INFORMIX-4GL User Guide and the OPEN WINDOW statement in this chapter for more information about displaying a form in a window. 4. The DISPLAY FORM statement is not required if you opened and displayed a form using the WITH FORM option of the OPEN WINDOW statement.

Examples
DISPLAY FORM order_entry DISPLAY FORM inventory ATTRIBUTE(BLUE)

Related Statements
CLEAR, CLOSE FORM, OPEN FORM, OPEN WINDOW

7-84

INFORMIX-4GL Statement Syntax

DROP AUDIT

DROP AUDIT
Overview
Use the DROP AUDIT statement to delete an audit trail file.

Syntax
DROP AUDIT FOR table-name

Explanation
DROP AUDIT FOR

are required keywords. is the name of the table whose audit trail file you want to delete.

table-name

Notes
1. Us e the DROP AUDIT statement to remove the old audit trail file when you have made a backup of your database files. Use the CREATE AUDIT statement to start a new audit trail and then back up the table. See the section “Audit Trails” in Chapter 3 for more information. 2. You must own table-name or have DBA status to use the DROP AUDIT statement.

Example
DROP AUDIT FOR orders

Related Statements
CREATE AUDIT, RECOVER TABLE

INFORMIX-4GL Statement Syntax

7-85

DROP DATABASE

DROP DATABASE
Overview
Use the DROP DATABASE statement to delete an entire database, including all system catalogs, indexes, data, and the transaction log.

Syntax
DROP DATABASE { database-name | char-variable }

Explanation
DROP DATABASE

are required keywords. is the name of the database you want to delete. is a program variable of type CHAR containing the name of the database you want to delete.

database-name char-variable

Notes
1. You must own all the tables in the database or have DBA status to run the DROP DATABASE statement. 2. The DROP DATABASE statement does not delete the database directory if there are any files in the database directory other than those created for database tables and their indexes. 3. You cannot drop the current database. You must execute the CLOSE DATABASE statement first. 4. The DROP DATABASE statement cannot be rolled back. 5. For databases with transactions, the DROP DATABASE statement deletes the transaction log. 6. The DROP DATABASE statement cannot appear in a multi-statement PREPARE.

Example
DROP DATABASE stores

7-86

INFORMIX-4GL Statement Syntax

DROP DATABASE

Related Statements
CREATE DATABASE, CLOSE DATABASE

INFORMIX-4GL Statement Syntax

7-87

DROP INDEX

DROP INDEX
Overview
Use the DROP INDEX statement to delete an index.

Syntax
DROP INDEX index-name

Explanation
DROP INDEX

are required keywords. is the name of the index you want to delete.

index-name

Notes
1. You must own the index or have DBA privilege to use the DROP INDEX statement. 2. You cannot roll back the DROP INDEX statement. 3. You cannot drop the index created when a column or composite column list is identified as having a UNIQUE CONSTRAINT in the CREATE TABLE statement.

Example
DROP INDEX i_ordnum

Related Statement
CREATE INDEX

7-88

INFORMIX-4GL Statement Syntax

DROP SYNONYM

DROP SYNONYM
Overview
Use the DROP SYNONYM statement to delete a previously defined synonym for a table or view.

Syntax
DROP SYNONYM synonym

Explanation
DROP SYNONYM are required keywords.

synonym

is a 4GL identifier.

Notes
1. You must be the owner of the synonym or have DBA status to use the DROP SYNONYM statement. 2. When you compile a program containing a synonym, the synonym is replaced in the compiled program by the real identifier of the table or view (as listed in the systables system catalog). If you subsequently drop the synonym, the compiled program will still run. 3. The DROP SYNONYM statement cannot be rolled back.

Example
DROP SYNONYM cust

Related Statement
CREATE SYNONYM

INFORMIX-4GL Statement Syntax

7-89

DROP TABLE

DROP TABLE
Overview
Use the DROP TABLE statement to delete a table, along with its associated indexes and data.

Syntax
DROP TABLE table-name

Explanation
DROP TABLE

are required keywords. is the name of the table you want to delete.

table-name

Notes
1. When you delete a table, you also delete the data stored in it, the indexes on columns, any synonyms assigned to it, and any authorizations you have granted on the table. You also delete all views based on the table. 2. You cannot drop any of the system catalog tables. 3. You must be the owner of a table or have DBA privilege to use the DROP TABLE statement. 4. The DROP TABLE statement cannot be rolled back.

Example
DROP TABLE customer

Related Statement
CREATE TABLE

7-90

INFORMIX-4GL Statement Syntax

DROP VIEW

DROP VIEW
Overview
Use the DROP VIEW statement to delete a view from the database.

Syntax
DROP VIEW view-name

Explanation
DROP VIEW

are required keywords. is the identifier of a view.

view-name

Notes
1. You must be the owner of the view or have DBA status to use the DROP VIEW statement. 2. When you drop view-name, you also drop all views that have been defined in terms of view-name. 3. You cannot roll back the DROP VIEW statement. 4. See the section “Views” in Chapter 3 for more information.

Example
DROP VIEW cust1

Related Statements
CREATE VIEW, DROP TABLE

INFORMIX-4GL Statement Syntax

7-91

ERROR

ERROR
Overview
Use the ERROR statement to display an error message on the Error line (by default, the bottom line of the screen), and to ring the terminal bell.

Syntax
ERROR display-list [ ATTRIBUTE ( attribute-list ) ]

Explanation
ERROR

is a required keyword. is a list of one or more program variables and/or string constants (enclosed in quotation marks), separated by commas. is an optional keyword. is a list of one or more screen attributes, separated by commas.

display-list
ATTRIBUTE

attribute-list

Notes
1. The string generated by substituting values for the variables in display-list must fit on a single display line. The string is displayed in a window on the Error line. 2. You can change the position of the Error line with the OPTIONS statement. The location of the Error line is relative to the screen, rather than to the current window. 3. The display-list can contain the CLIPPED and USING functions. 4. REVERSE is the default attribute for the ERROR display. You can alter the default attribute with the ATTRIBUTE clause.

7-92

INFORMIX-4GL Statement Syntax

ERROR

5. The following list shows the screen attributes allowed in the ATTRIBUTE clause:
WHITE = NORMAL YELLOW = BOLD MAGENTA = BOLD RED = BOLD CYAN = DIM GREEN = DIM BLUE = DIM BLACK = INVISIBLE REVERSE BLINK UNDERLINE

On color terminals, NORMAL is interpreted as WHITE, BOLD as RED, DIM as BLUE, and INVISIBLE as BLACK. If you have a colornames file, you can use the color names listed there. (See Appendix I.)

Example
ERROR "There is no match for ", pattern

Related Statements
DISPLAY, MESSAGE, OPTIONS

INFORMIX-4GL Statement Syntax

7-93

EXECUTE

EXECUTE
Overview
Use the EXECUTE statement to run a statement specified by a previous PREPARE statement.

Syntax
EXECUTE statement-id [ USING input-list ]

Explanation
EXECUTE

is a required keyword. is an SQL statement identifier that you named in a previous PREPARE statement. is an optional keyword. is a list of program variables to be substituted as values for the question marks (?) in the statement indicated by statement-id. Use this option when you know the number and data types of the values that the PREPAREd statement requires.

statement-id
USING

input-list

Notes
1. After you PREPARE an SQL statement, you can EXECUTE it as often as you desire. 2. To use the USING clause, you must know the number of the parameters of the PREPAREd statement. The data type of each variable in input-list must be compatible with the value expected in the PREPAREd statement for the corresponding parameter. 3. You cannot EXECUTE a PREPAREd SELECT statement. You must use DECLARE with a FOREACH loop, or use the OPEN, FETCH, and CLOSE statements to execute a statement-id that references a SELECT statement. 4. You cannot EXECUTE a PREPAREd INSERT statement that uses a cursor. You must use DECLARE with a FOREACH loop, or else use the OPEN, PUT, and CLOSE statements to execute INSERT statements that you want to process as a group.

7-94

INFORMIX-4GL Statement Syntax

EXECUTE

5. The scope of reference of the statement-id is from the PREPARE statement that names it until the end of its source-code module. The EXECUTE statement cannot reference a statement-id that you PREPARE in a different module, or later in the same module. 6. PREPAREd statements require database engine resources that are not unlimited. If you specify FREE statement-id to release engine resources, you cannot subsequently EXECUTE that statement unless you PREPARE it again.

Example
LET s1 = "UPDATE orders SET po_num = ?, order_date = ?" PREPARE statement_1 FROM s1 EXECUTE statement_1 USING purchase_num, order_date

Related Statements
DECLARE, FREE, PREPARE

INFORMIX-4GL Statement Syntax

7-95

EXIT

EXIT
Overview
Use the EXIT statement to terminate the program; to break out of a FOR, a FOREACH, or a WHILE loop; to leave the CASE statement; to leave the INPUT or INPUT ARRAY statement; or to leave a menu.

Syntax
EXIT { CASE | DISPLAY | FOR | FOREACH | INPUT | MENU | PROGRAM [ ( integer-expr ) ] | WHILE }

Explanation
EXIT CASE DISPLAY FOR FOREACH INPUT MENU PROGRAM

is a required keyword. is an optional keyword. is an optional keyword. is an optional keyword. is an optional keyword. is an optional keyword. is an optional keyword. is an optional keyword. is an expression that evaluates as an integer. is an optional keyword.

integer-expr
WHILE

Notes
1. You can use the CASE option only within a CASE statement, the DISPLAY option only within a DISPLAY ARRAY statement, the FOR option only within a FOR statement, the FOREACH option only within a FOREACH statement, the INPUT option only within an INPUT or INPUT ARRAY statement, the MENU option only following a COMMAND clause of a MENU statement, and the WHILE option only within a WHILE statement. In each case, program control passes to the first statement following the END CASE, END DISPLAY, END FOR, END FOREACH, END INPUT, END MENU, or END WHILE statements, respectively.

7-96

INFORMIX-4GL Statement Syntax

EXIT

2. You can use the PROGRAM option anywhere; it immediately terminates the program. 3. Use the optional integer argument of EXIT PROGRAM to return a status code to the operating system upon program termination.

Related Statement
CONTINUE

INFORMIX-4GL Statement Syntax

7-97

FETCH

FETCH
Overview
Use the FETCH statement to move the cursor to a new row in the active set and to retrieve the values from that row.

Syntax
FETCH [ NEXT | { PREVIOUS | PRIOR } | FIRST | LAST | CURRENT | RELATIVE m | ABSOLUTE n ] cursor-name [ INTO variable-list ]

Explanation
FETCH NEXT PREVIOUS PRIOR FIRST LAST CURRENT RELATIVE m

is a required keyword. is a keyword indicating the next row in the active list. NEXT is the default. is a keyword indicating the prior row in the active list. is a keyword that is synonymous with PREVIOUS. is a keyword indicating the first row of the active list. is a keyword indicating the last row of the active list. is a keyword indicating the current row of the active list. is a keyword indicating the mth row relative to the current cursor position in the active list. Here m can be either an integer or a program variable and can be either positive or negative. is a keyword indicating the nth row in the active list. Here n can be either an integer or a program variable. is a 4GL identifier that you specified in a previous DECLARE statement. You must also OPEN cursor-name. is an optional keyword. is a list of 4GL program variables that contains the column values of the row pointed to by cursor-name.

ABSOLUTE n

cursor-name
INTO

variable-list

7-98

INFORMIX-4GL Statement Syntax

FETCH

Notes
1. FETCH NEXT is the default condition. 2. You must DECLARE a SCROLL cursor before issuing a FETCH statement that includes the PRIOR, PREVIOUS, FIRST, LAST, CURRENT, RELATIVE m, or ABSOLUTE n keywords. 3. If the SELECT statement associated with the cursor has an INTO clause, there must be no INTO clause in any FETCH statement referring to that cursor. If the SELECT statement has no INTO clause, the FETCH statement must have one. 4. You can FETCH into a program array element only by using an INTO clause in the FETCH statement. Do not refer to an array element in the SELECT-statement of a DECLARE statement. 5. Under any of the following circumstances, INFORMIX-4GL returns a ‘‘row not found’’ code (status = NOTFOUND ).

• You issue a FETCH NEXT statement when the cursor points to the last
row in the active set.

• You issue a FETCH PRIOR or FETCH PREVIOUS statement when the
cursor points to the first row in the active set.

• You issue a FETCH ABSOLUTE n statement when no nth row exists in
the active set.

• You issue a FETCH RELATIVE m statement when no mth row exists in
the active set. You can use the WHENEVER NOT FOUND statement to specify an action to take if status = NOTFOUND. 6. FETCH does not lock a row unless the DECLARE statement contains a SELECT with a FOR UPDATE clause. It is possible to retrieve a row that is being UPDATEd or DELETEd by a concurrent process. 7. If the cursor was DECLAREd FOR UPDATE and the current database is not MODE ANSI but uses explicit transactions, you can include FETCH only within a transaction (that is, following a BEGIN WORK statement). In a MODE ANSI database, all operations take place inside a transaction, so a FETCH can be done at any time while cursor-name is OPEN.

INFORMIX-4GL Statement Syntax

7-99

FETCH

Examples
FETCH query_curs INTO cnum, lname FETCH PREVIOUS q_curs INTO orders.* FETCH LAST q_curs INTO orders.* FETCH ABSOLUTE 8 q_curs INTO orders.* FETCH RELATIVE -10 q_curs INTO orders.*

Related Statements
CLOSE, DECLARE, DELETE, FOREACH, OPEN, PREPARE, PUT, SELECT, UPDATE, WHENEVER

7-100

INFORMIX-4GL Statement Syntax

FINISH REPORT

FINISH REPORT
Overview
Use the FINISH REPORT statement to cause INFORMIX-4GL to finish processing a report.

Syntax
FINISH REPORT report-name

Explanation
FINISH REPORT

are required keywords. is the identifier of a report.

report-name

Note
You must use the FINISH REPORT statement to let INFORMIX-4GL know that no more statements are to be included in the report processing.

Example
FINISH REPORT cust_ords

Related Statements
OUTPUT TO REPORT, START REPORT

INFORMIX-4GL Statement Syntax

7-101

FLUSH

FLUSH
Overview
Use the FLUSH statement to force INFORMIX-4GL to insert the buffered rows into the database without closing the cursor.

Syntax
FLUSH cursor-name

Explanation
FLUSH

is a required keyword. is the name of a cursor that has been DECLAREd for an INSERT statement.

cursor-name

Notes
1. The global variables status (whose value is taken from SQLCA.SQLCODE) and SQLCA.SQLERRD[3] indicate the result of each FLUSH statement. If INFORMIX-4GL successfully inserts all the buffered rows into the database, it sets status to zero and sets SQLCA.SQLERRD[3] to the number of rows inserted. If INFORMIX-4GL is unsuccessful in its attempt to insert the rows into the database, it sets status to a negative number (specifically, the number of the error message) and sets SQLCA.SQLERRD[3] to the number of rows successfully inserted into the database. 2. You can use the FLUSH statement to force the insertion. You cannot delay insertion by not using the FLUSH statement. INFORMIX-4GL automatically flushes the buffer when it is full. 3. Insert cursors that contain only constants in the values clause are not buffered. INFORMIX-4GL keeps a count of the number of rows to be inserted into the database, and the database is updated only when you issue a FLUSH or CLOSE statement. 4. If you exit a program without closing the cursor, the buffer is left unflushed. Rows inserted into the buffer and remaining since the last flush are lost. Do not expect the end of program to close the cursor and flush the buffer.

7-102

INFORMIX-4GL Statement Syntax

FLUSH

Example
FLUSH icurs

Related Statements
CLOSE, DECLARE, OPEN, PUT

INFORMIX-4GL Statement Syntax

7-103

FOR

FOR
Overview
Use the FOR statement to cause a sequence of statements to be executed a specified number of times.

Syntax
FOR integer-var = integer-expr TO integer-expr [STEP integer-expr] statement ... [CONTINUE FOR] ... [EXIT FOR] ... END FOR

Explanation
FOR

is a required keyword. is a program variable of type INTEGER or SMALLINT that serves as a counter. is an expression that evaluates to an INTEGER or a SMALLINT.

integer-var integer-expr
TO STEP

is a required keyword. is an optional keyword. is an INFORMIX-4GL statement. is an optional statement. is an optional statement. are required keywords.

statement
CONTINUE FOR EXIT FOR END FOR

7-104

INFORMIX-4GL Statement Syntax

FOR

Notes
1. The FOR statement repeats the sequence of statements up to the END FOR as integer-var takes on the values of the first integer-expr TO the second integer-expr in STEPs of the third integer-expr. The default STEP is 1. 2. The CONTINUE FOR statement interrupts the sequence and causes the program control to return to the top of the sequence and to increment and test the counter integer-var. 3. The EXIT FOR statement interrupts the sequence and causes the program control to jump to the first statement following the END FOR keywords. 4. If integer-var is greater than the TO integer-expr upon entry and the STEP value is positive, none of the statements up to END FOR is executed. 5. The STEP value may be negative.

Example
DEFINE order_total MONEY(8), i INTEGER LET order_total = 0.00 FOR i = 1 TO ARR_COUNT() LET order_total = order_total + p_items[i].total_price END FOR

Related Statements
CONTINUE, EXIT, FOREACH, WHILE

INFORMIX-4GL Statement Syntax

7-105

FOREACH

FOREACH
Overview
Use the FOREACH statement to cause a sequence of statements to be executed for each row returned from a query.

Syntax
FOREACH cursor-name [INTO variable-list] statement ... [CONTINUE FOREACH] ... [EXIT FOREACH] ... END FOREACH

Explanation
FOREACH

is a required keyword. is the name of a cursor that previously was DECLAREd. is an optional keyword. is a list of one or more program variables, separated by commas. is an optional statement. is an optional statement. are required keywords.

cursor-name
INTO

variable-list
CONTINUE FOREACH EXIT FOREACH END FOREACH

7-106

INFORMIX-4GL Statement Syntax

FOREACH

Notes
1. The FOREACH statement repeats the sequence of statements up to END FOREACH for each row returned by the query associated with cursorname. The FOREACH statement OPENs the cursor and performs successive FETCHes until the active list of the cursor is exhausted. 2. The INTO clause is required only if there is no INTO clause in the SELECT statement associated with cursor-name, and vice versa. It lists the variables into which INFORMIX-4GL places the values returned by the query. 3. When FETCHing into a program array, you must place the INTO clause on the FOREACH statement and not on the SELECT-statement of a DECLARE statement. 4. The CONTINUE FOREACH statement interrupts the sequence and causes program control to return to the top of the sequence and to FETCH the next row of the query. 5. The EXIT FOREACH statement interrupts the sequence and causes program control to jump to the first statement following the END FOREACH keywords. 6. If the query returns no rows, none of the statements up to the END FOREACH is executed, and program control passes immediately to the first statement following END FOREACH. If you need to know whether any rows were returned, you can set up a flag or a counter as in the example that follows these notes. 7. The FOREACH statement performs an implied OPEN statement. You cannot use the FOREACH statement if the OPEN statement must have a USING clause to define unknown parameters in the SELECT statement. 8. If your database has transactions, the FOREACH statement must appear inside a transaction. 9. If, within the FOREACH statement, the WHENEVER NOT FOUND statement evaluates to TRUE, the open cursor is automatically closed.

INFORMIX-4GL Statement Syntax

7-107

FOREACH

Example
PROMPT "Enter cut-off date for query: " FOR o_date DECLARE q_curs CURSOR FOR SELECT order_num, o.customer_num, company FROM orders o, customer c WHERE o.customer_num = c.customer_num AND order_date < o_date LET counter = 0 FOREACH q_curs INTO ord_num, cust_num, comp LET counter = counter + 1 CALL scan(ord_num, cust_num, comp) END FOREACH IF counter = 0 THEN ERROR "No orders before ", o_date END IF

Related Statements
CONTINUE, EXIT, FETCH, FOR, OPEN, WHILE, WHENEVER

7-108

INFORMIX-4GL Statement Syntax

FREE ( O )

FREE ( O )
Overview
The FREE statement releases database engine resources allocated to a PREPAREd statement or to an OPENed and CLOSEd cursor.

Syntax
FREE { statement-id | cursor-name }

Explanation
FREE

is a required keyword. is the name of a statement that has been PREPAREd. is the name of a cursor whose DECLARE statement includes the keywords SELECT or INSERT.

statement-id cursor-name

Notes
1. After you FREE statement-id, a cursor or EXECUTE statement cannot use it until you PREPARE it again. 2. If cursor-name is DECLAREd FOR SELECT or FOR INSERT, a statement is automatically PREPAREd when you OPEN the cursor. The statement has no programmer-assigned statement-id. To release engine resources from that statement, use FREE cursor-name. Afterward, you cannot use the cursor unless you OPEN it again. 3. Do not FREE a cursor-name that was DECLAREd FOR statement-id. Use instead FREE statement-id.

Examples
FREE query_2 FREE scurs

INFORMIX-4GL Statement Syntax

7-109

FUNCTION

FUNCTION
Overview
Use the FUNCTION statement to define a function.

Syntax
FUNCTION function-name ( [ argument-list ] ) statement ... [ RETURN expr-list ] ... END FUNCTION

Explanation
FUNCTION

is a required keyword. is a program identifier for the name of the function. is a list (enclosed in parentheses) of one or more variables, separated by commas. is an INFORMIX-4GL statement. is an optional keyword that causes program control to return to the calling program. is a list of zero or more expressions that yield the values returned by function-name. are required keywords that terminate the FUNCTION statement.

function-name (argument-list) statement
RETURN

expr-list
END FUNCTION

Notes
1. All arguments are passed by value. 2. You must DEFINE the arguments to the function, as well as other variables used locally within the function.

7-110

INFORMIX-4GL Statement Syntax

FUNCTION

3. When passing an entire record as an argument to a function, use the .* notation. In the FUNCTION statement, however, use only a record name that you define within the FUNCTION routine. Thus you call the following function with the notation:
CALL example(orders.*) . . . FUNCTION example(r) DEFINE r RECORD LIKE orders.* ... END FUNCTION

4. Variables DEFINEd within a function are local to the function. 5. If function-name returns a single value, it may be used in an expression in place of a variable. Otherwise, it must be CALLed. 6. The number and data type of expressions in expr-list must be the same, and in the same order, as the number and type of program variables in the RETURNING clause of the CALL statement that calls the function. 7. The function-name must conform to the rules for 4GL identifiers, as described in Chapter 2. An error results if function-name is the same as the identifier of a global variable or of another function in the same program.

Related Statement
CALL

INFORMIX-4GL Statement Syntax 7-111

GLOBALS

GLOBALS
Overview
Use the GLOBALS statement to DEFINE one or more variables to be global variables or to refer to the file where global variables are DEFINEd.

Syntax
GLOBALS {‘‘filename’’ | DEFINE-statement ... END GLOBALS}

Explanation
GLOBALS

is a required keyword. is the pathname of the file where the global variables are defined. is a DEFINE statement for the global variable. are required keywords that terminate the GLOBALS statement when variables are DEFINEd.

filename
DEFINE-statement END GLOBALS

Notes
1. You may have at most one GLOBALS statement where global variables are defined. This statement may be in a separate file or in the file containing the MAIN program block. 2. The GLOBALS filename statement must occur earlier in every file than any function that makes reference to a global variable. 3. The GLOBALS statement must lie outside the MAIN program block and any FUNCTION or REPORT routines. 4. If any global variable is DEFINEd LIKE a database column, the DATABASE statement naming the database must precede the GLOBALS statement.

7-112

INFORMIX-4GL Statement Syntax

GLOBALS

Examples
DATABASE stores GLOBALS DEFINE p_customer RECORD LIKE customer.* ... END GLOBALS GLOBALS "d4_globals.4gl"

Related Statement
DEFINE

INFORMIX-4GL Statement Syntax

7-113

GOTO

GOTO
Overview
Use the GOTO statement to transfer program control unconditionally to a designated point.

Syntax
GOTO [ : ]label-id

Explanation
GOTO

is a required keyword. is an optional prefix to label-id and conforms to the ANSI standard for SQL syntax. is a 4GL identifier.

: label-id

Notes
1. After a GOTO label-id statement successfully executes, program control is transferred to the statement that follows LABEL label-id:. See the syntax of the LABEL statement later in this chapter. 2. The label-id must be in the FUNCTION, REPORT, or MAIN routine in which the GOTO statement is used. You cannot transfer into or out of a FUNCTION or a REPORT with a GOTO statement.

Related Statements
LABEL, WHENEVER

7-114

INFORMIX-4GL Statement Syntax

GRANT

GRANT
Overview
Use the GRANT statement to specify user access privileges to a database or to the tables and views in a database.

Syntax
GRANT tab-privilege ON table-name TO { PUBLIC | user-list } [ WITH GRANT OPTION ] [ AS grantor ] GRANT db-privilege TO { PUBLIC | user-list }

Explanation
GRANT

is a required keyword. is one or more of the following table-level access types (multiple privileges must be separated by commas):
ALTER DELETE INDEX INSERT

tab-privilege

Add or delete columns or modify data types of columns. Delete rows. Create indexes. Insert rows.

SELECT [(cols)] Retrieve data from specified columns. UPDATE [(cols)] Change values in specified columns. ALL of the above access types. [ PRIVILEGES ] SELECT and UPDATE take column names as

arguments, allowing you to specify columns that the user may select or update. Separate column names with commas. The keyword PRIVILEGES following ALL is optional.
ON

is a required keyword. is the name of the table or view for which you are granting access privileges. is a required keyword.
INFORMIX-4GL Statement Syntax 7-115

table-name
TO

GRANT

PUBLIC

is the keyword that you use to specify access privileges for all users. is a list of login names for the users to whom you are granting access privileges. You can enter one login name or a series of login names, separated by commas. are optional keywords. is an optional keyword. is the username of the user issuing the GRANT statement. is one of the following database-level access types:
CONNECT

user-list

WITH GRANT OPTION AS

grantor db-privilege

Allows access to database tables without permission to create permanent tables and indexes. Allows access to database tables with permission to create permanent tables and indexes. Allows full database administrator privileges.

RESOURCE DBA

Notes
1. Database-level permissions (CONNECT, RESOURCE, and DBA) control access to the database. Table-level permissions (ALTER, DELETE, INDEX, INSERT, SELECT, UPDATE, and ALL) control access to a table. 2. With CONNECT privilege, you can create views and temporary tables. (The table-level SELECT privilege is required, however, on all columns from which the view is derived.) 3. The RESOURCE privilege includes the CONNECT privilege and adds the permission to create tables and indexes. 4. The DBA privilege includes the following:

• The RESOURCE privilege • Permission to drop, start, and roll forward the database. User INFORMIX also has permission to alter the system catalogs.

• Permission to grant and revoke CONNECT, RESOURCE, and DBA privileges to and from other users. 5. When you create a database, you are the Database Administrator and have DBA privileges. 6. A DBA can use the AS keyword to grant table-level privileges on behalf of another user.
7-116 INFORMIX-4GL Statement Syntax

GRANT

7. You can grant privileges only on tables or views that you create, or on tables or views for which you have been given the GRANT OPTION. 8. When you use the WITH GRANT OPTION phrase to GRANT table-level privileges to another user, you give that user the power to GRANT the same privileges to another user. 9. If you do not specify one or more column names, the SELECT or UPDATE access that you grant applies to all columns. 10. You cannot roll back the GRANT statement. 11. The most restrictive privileges always take precedence. For example, if you grant RESOURCE privileges to a user but do not grant INDEX privileges at the table level, that user is not able to create indexes for that table. 12. You can grant DELETE, INSERT, or UPDATE privileges only on a simple view. You can grant SELECT privilege on a simple or complex view.

Examples
The following statements grant all table-level privileges (except ALTER) to all users who have CONNECT privileges to the database:
GRANT ALL ON customer TO PUBLIC REVOKE ALTER ON customer FROM PUBLIC

When you create a table in a database that is not MODE ANSI, all table-level privileges except ALTER are automatically granted to all users (PUBLIC). To restrict access privileges at the table level, you must revoke all privileges and grant those that you want:
REVOKE ALL ON customer FROM PUBLIC GRANT ALL ON customer TO joe, mary GRANT SELECT (fname, lname, company, city) ON customer TO PUBLIC

In a database created as MODE ANSI, no default table-level privileges exist. You must explicitly grant these privileges.

Related Statement
REVOKE

INFORMIX-4GL Statement Syntax

7-117

IF

IF
Overview
Use the IF statement to execute one or more statements conditionally.

Syntax
IF Boolean-expr THEN statement ... [ ELSE statement ... ] END IF

Explanation
IF

is a required keyword. is an expression that can be TRUE or FALSE. is a required keyword. is any INFORMIX-4GL statement, including another IF statement. is an optional keyword. are required keywords.

Boolean-expr
THEN

statement
ELSE END IF

Notes
1. If Boolean-expr is true, the statements following THEN down to an optional ELSE (if present) or to END IF (if there is no ELSE) are executed. 2. If Boolean-expr is false, the statements following THEN down to an optional ELSE (if present) or to END IF (if there is no ELSE) are skipped. If an ELSE is present, the statements following the ELSE are executed. 3. If Bool-expr evaluates as UNKNOWN because the expression contains NULL values, the IF statement behaves as though it were FALSE.

7-118

INFORMIX-4GL Statement Syntax

IF

Example
IF p_index <= 1 THEN ERROR "No more stock items in this direction" ELSE LET p_index = p_index - 1 DISPLAY dp_stock[p_index].* TO s_stock.* END IF

Related Statements
CASE, WHENEVER

INFORMIX-4GL Statement Syntax

7-119

INITIALIZE

INITIALIZE
Overview
Use the INITIALIZE statement to initialize a program variable.

Syntax
INITIALIZE variable-list { LIKE column-list | TO NULL }

Explanation
INITIALIZE

is a required keyword. is a list of one or more variables, separated by commas. is an optional keyword. is a list of column names, preceded by table names and separated by commas. are optional keywords to assign NULL values.

variable-list
LIKE

column-list
TO NULL

Notes
1. If you include a column-list, it must specify as many columns as there are variables in variable-list. 2. You must use a table-name prefix in the designation of the column names. 3. In a MODE ANSI database, the name of a table is qualified by the owner of the table (owner. table-name). You must specify owner when you refer to a table owned by another user. The use of the prefix owner is optional in a non-MODE ANSI database. INFORMIX-4GL does check the accuracy of owner, however, if you include it in a statement. See the section “Owner Naming” in Chapter 3 for more information. 4. You can use the upscol utility to create and update the values in syscolval. (See the discussion of the “The upscol Utility” in Appendix E.) 5. In a non-MODE ANSI database, there is a single syscolval table for all users. The INITIALIZE statement assigns to individual variables in variable-list the DEFAULT values specified in this table. 6. In a MODE ANSI database, each user has his or her own syscolval table. This means that the values entered into these tables apply only to variables that correspond to columns in tables owned by the specified user. If
7-120 INFORMIX-4GL Statement Syntax

INITIALIZE

no owner name is specified, and the user compiling the program owns the table, INFORMIX-4GL uses the values in the syscolval table owned by that user. 7. If any columns corresponding to components of variable-list have not been assigned DEFAULT values in syscolval, INFORMIX-4GL substitutes NULL values. 8. Since upscol does not support DATETIME or INTERVAL values, these data types will default to NULL when you include them in a column-list. 9. You can use the * notation in variable-list and column-list. 10. The TO NULL option requests initialization with the appropriate NULL value for each variable.

Examples
INITIALIZE var1, var2, var3 LIKE tab1.col1, tab1.col2, tab1.col3 INITIALIZE v_cust.* LIKE customer.* INITIALIZE v_orders.* TO NULL INITIALIZE var1, var2, var3 LIKE tab1.var1, eileen.tab2.var2, fred.tab3.var3

Related Statements
LET, VALIDATE

INFORMIX-4GL Statement Syntax

7-121

INPUT

INPUT
Overview
Use the INPUT statement to assign values to program variables from data that the user enters into fields of a screen form.

Syntax
INPUT { BY NAME variable-list [ WITHOUT DEFAULTS ] | variable-list [ WITHOUT DEFAULTS ] FROM { field-list | screen-record [ [ n ] ] .* } [ , . . . ] } [ ATTRIBUTE ( attribute-list ) ] [ HELP help-number ] [ { BEFORE FIELD field-sublist | AFTER { FIELD field-sublist | INPUT } | ON KEY ( key-list ) } statement ... [ NEXT FIELD field-name ] ... [ EXIT INPUT ] ... ... END INPUT ]

Explanation
INPUT BY NAME

is a required keyword. The INPUT statement allows the user to change the data displayed on the screen. are keywords instructing INFORMIX-4GL to match names of variables to screen field names. is a list of program variables to display. are keywords to display on the screen the current values in variable-list. is a keyword to specify the screen fields whose values will be assigned to variable-list. is a list of one or more names of screen fields. is the identifier of a collection of field names defined in a form specification as a SCREEN RECORD. is an integer, enclosed in brackets, to specify the row of a screen array (beginning with line 1).

variable-list WITHOUT DEFAULTS
FROM

field-list screen-record [n]

7-122

INFORMIX-4GL Statement Syntax

INPUT

ATTRIBUTE

is a keyword to specify screen input attributes. is a list (in parentheses) of screen attributes. is a keyword to specify a help message. is an integer to identify a help message for this INPUT statement in the help file that was specified in the OPTIONS statement. cursor enters a field in the field-sublist.

(attribute-list)
HELP

help-number

BEFORE FIELD are keywords to transfer control to a 4GL statement when the

field-sublist
AFTER FIELD AFTER INPUT ON KEY

is a list of one or more of the fields either explicitly or implicitly referenced in the INPUT statement. are keywords to transfer control to a 4GL statement when the cursor leaves a field in the field-sublist. are keywords to transfer control to a 4GL statement when the user has finished entering input. are keywords to specify keys of the keyboard. is a list (in parentheses) of key designation(s), usually of function or CTRL keys. If one of these is pressed during input, a 4GL statement is executed. is a 4GL statement. It is executed during input, if BEFORE FIELD, AFTER FIELD, or ON KEY clause conditions are satisfied. It is executed after input, if an AFTER INPUT clause is used. are keywords that cause INFORMIX-4GL to move the cursor immediately to a specified field. identifies a field from field-list or screen-record (or implied by the BY NAME clause). are keywords that direct INFORMIX-4GL to leave the INPUT statement immediately. are keywords that terminate the INPUT statement. These keywords are required if you include a BEFORE clause, AFTER clause, or ON KEY clause.

(key-list)

statement

NEXT FIELD

field-name
EXIT INPUT END INPUT

INFORMIX-4GL Statement Syntax

7-123

INPUT

Notes
1. When you execute the INPUT statement with the WITHOUT DEFAULTS clause, INFORMIX-4GL displays the current values of variable-list in the screen fields. This option is appropriate when you are requesting input prior to updating an existing row of a table. 2. If an INPUT statement omits the WITHOUT DEFAULTS clause, INFORMIX-4GL displays on the form the default values from the form specification (or from syscolval, if no default valuess were specified by the DEFAULT attribute in the form specification) and initializes the variables in variable-list accordingly. INFORMIX-4GL assigns NULL values to all variables for which no default has been set. This option is appropriate when you are requesting input prior to inserting a new row in a table. 3. The INPUT BY NAME option selects the screen fields based on the identity of the program variable name and the screen field name. INFORMIX-4GL uses only the suffix portion of the name of the program variable and the screen field. You must use the FROM option if the suffixes are not unique and unambiguous. 4. If you use the FROM option, the number of variables in variable-list must be the same as the number of field names in field-list or screen-record, and of the corresponding data type. 5. INPUT is terminated when the user presses ESCAPE (or the key specified as the Accept key in the OPTIONS statement). For single-item INPUTs (or after the last item of multiple-item INPUTs), a RETURN is equivalent to pressing the Accept key. You can use the AFTER FIELD clause on the last field to override the terminating power of the RETURN by setting NEXT FIELD to the first field. This option wraps the field-list into a loop. Alternatively, use the INPUT WRAP option in the OPTIONS statement for the same effect. 6. The user triggers the AFTER INPUT clause (and the set of statements that follow that clause) by attempting to terminate the INPUT statement. (See the previous note.) If there is an AFTER INPUT clause, program control passes to the statements following that clause, rather than to the statements following the END INPUT clause. This feature allows the programmer to perform data validity checks before allowing the INPUT statement to terminate. 7. INFORMIX-4GL passes control to the statements following a BEFORE clause when the cursor enters a field in field-list. It passes control to the statements following an AFTER clause when the cursor leaves a field in field-list (after the user has pressed RETURN, indicating that data has been

7-124

INFORMIX-4GL Statement Syntax

INPUT

entered into the field). It passes control to the statements following an ON KEY clause after the user presses a key in key-list. 8. If there is no NEXT FIELD statement in the sequence of statements following a BEFORE or AFTER clause, the cursor moves to the next field in the direction that the user indicated (forward for [ → ], [ ↓ ], TAB, or RETURN, and backward for [ ← ] or [ ↑ ]). 9. If the user triggers an ON KEY clause while entering data into a field, INFORMIX-4GL suspends the input of the current field while it executes the statements in the ON KEY clause. It preserves the input buffer containing the characters that the user typed before triggering the ON KEY clause and restores them when the ON KEY clause returns. It resumes the input in the same field with the cursor at the end of the buffered list of characters. If you want to use the ON KEY clause to fill the field with another value, be sure to move to a new field with the NEXT FIELD statement to prevent the INPUT statement from ignoring the new value. 10. The notation for function keys is F1 through F36. The notation for CONTROL keys is CTRL-key, where key is any letter except A, D, H, L, R, or X. The notation for ESCAPE is ESCAPE or ESC. The notation for the Interrupt key is INTERRUPT. Appendix I, “Modifying termcap and terminfo,” describes how to verify that the termcap and terminfo entries for your terminal allow INFORMIX-4GL to recognize function keys. 11. By default, both ESCAPE and Interrupt are exits from the INPUT statement. If the DEFER INTERRUPT statement has been executed, an Interrupt causes INFORMIX-4GL to set the global variable int_flag to nonzero and terminate the INPUT statement (unless the function of Interrupt is redefined in an ON KEY clause). Otherwise, Interrupt immediately stops the program. 12. These two keys can be in a key-list under the stated conditions:

ESCAPE, if you have specified another key as the Accept key in the OPTIONS statement.

• Interrupt, if you have executed a DEFER INTERRUPT statement. (When
the user presses the Interrupt key under these conditions, INFORMIX-4GL executes the statements in the ON KEY clause and sets int_flag to nonzero, but does not terminate the INPUT statement.) Do not use the following keys in a key-list:

CTRL-A, CTRL-D, CTRL-H, CTRL-L, CTRL-R, or CTRL-X, since these keys are reserved for editing functions in the INPUT statement. CTRL-S for XOFF.

• Other keys that may have special meaning on your system, such as
13. Use of CTRL-I and CTRL-J in a key-list can conflict with normal data entry.
INFORMIX-4GL Statement Syntax 7-125

INPUT

14. In addition to the RETURN, ESCAPE, Interrupt, and Arrow keys, the user can employ the following keys for editing during an INPUT statement:
CTRL-A CTRL-D CTRL-H CTRL-L CTRL-R CTRL-X

toggles between insert and typeover mode. deletes characters from the current cursor position to the end of the field. moves the cursor nondestructively one space to the left inside a field. It is equivalent to pressing the [ ←] key. moves the cursor nondestructively one space to the right inside a field. It is equivalent to pressing the [→] key. redisplays the screen. deletes the character beneath the cursor.

15. Function infield(field) from the function library returns TRUE if the current field is field, and FALSE otherwise. Use it to make field-dependent responses when the user presses a key specified in the key-list of an ON KEY clause. If you call infield(field) outside the INPUT statement, it returns a value corresponding to the field that was current when INPUT was terminated. 16. Do not execute PROMPT, INPUT, or INPUT ARRAY statements within the BEFORE, AFTER, or ON KEY clauses of an INPUT statement. You can, however, call a function that executes one of these statements. 17. If you do not use the ATTRIBUTE clause, the display attributes of the input fields are governed by the INPUT ATTRIBUTE clause of the most recent OPTIONS statement. (The description of the OPTIONS statement lists the order of precedence among different sources of 4GL screen attribute specifications.) 18. In an INPUT statement, any screen attributes specified in attribute-list apply to all the fields in field-list or screen-record. 19. If you use the ATTRIBUTE clause, no default attributes in syscolatt or in the form specification file for fields in field-list or screen-record apply (including any default values from the DEFAULT attribute). The attribute-list temporarily overrides any attributes specified in an OPTIONS, DISPLAY FORM, or OPEN WINDOW statement for these fields.

7-126

INFORMIX-4GL Statement Syntax

INPUT

20. These keywords can appear in the ATTRIBUTE clause:
WHITE = NORMAL YELLOW = BOLD MAGENTA = BOLD RED = BOLD CYAN = DIM GREEN = DIM BLUE = DIM BLACK = INVISIBLE REVERSE BLINK UNDERLINE

You can specify zero or one of the keywords in the left-hand columns, and from zero to three from the right-hand column (but some terminals may not support some combinations). On color terminals, NORMAL is interpreted as WHITE, BOLD as RED, DIM as BLUE, and INVISIBLE as BLACK. Do not include the equal ( = ) sign, which in this table shows the effect on monochrome terminals of keywords that specify color. These keywords cannot produce the effects suggested by their names unless the termcap or terminfo files and the physical terminals support the attribute. (See Appendix I, “Modifying termcap and terminfo.”) Note: Some terminal entries in termcap or terminfo include the sg#1 or xmc#1 capabilities. On these terminals, the first character of variable-list is replaced by a blank if you use the INPUT statement with any display attribute. To be safe, make sure that fields in any line of a screen form begin after column 1, if you specify display attributes. 21. On UNIX systems that use terminfo files rather than termcap, INFORMIX-4GL does not support attributes that specify colors, and the only valid attribute-list keywords are REVERSE and UNDERLINE.

INFORMIX-4GL Statement Syntax

7-127

INPUT

Example
INPUT p_addr.* FROM sc_addr.* ATTRIBUTE (REVERSE RED) HELP 101 BEFORE FIELD fname MESSAGE "Enter first name of customer" BEFORE FIELD lname MESSAGE "Enter last name of customer" AFTER INPUT IF check_zip(p_addr.zipcode, p_addr.city) = FALSE THEN ERROR "Bad zip code for ", p_addr.city NEXT FIELD zipcode END IF ON KEY (F1) IF infield(city) THEN LET p_addr.city = "San Francisco" DISPLAY p_addr.city TO city LET p_addr.state = "CA" DISPLAY p_addr.state TO state NEXT FIELD zipcode END IF END INPUT

Related Statements
DISPLAY, DISPLAY FORM, EXIT, INPUT ARRAY, OPTIONS

7-128

INFORMIX-4GL Statement Syntax

INPUT ARRAY

INPUT ARRAY
Overview
Use the INPUT ARRAY statement to permit the user to enter data onto a screen array and to store the data in a program record array.

Syntax
INPUT ARRAY record-array [ WITHOUT DEFAULTS ] FROM screen-array.* [ HELP help-number ] [ ATTRIBUTE ( attribute-list ) ] [ { BEFORE { ROW | INSERT | DELETE | FIELD field-sublist } [ , . . . ] | AFTER { ROW | INSERT | DELETE | FIELD field-sublist | INPUT } [ , . . . ] | ON KEY ( key-list ) } statement ... [ NEXT FIELD field-name ] ... [ EXIT INPUT ] ... ... END INPUT ]

Explanation
INPUT ARRAY

are required keywords. is a program array name. Usually, record-array is an array of records. are optional keywords to display the current values of record-array. is a required keyword. is the name of a screen record that corresponds to the fields in a row of a screen array. is an optional keyword. is an integer that identifies the help message for this INPUT
ARRAY statement in the help file set in the OPTIONS

record-array WITHOUT DEFAULTS
FROM

screen-array
HELP

help-number

statement.
ATTRIBUTE

is a keyword to specify screen input attributes. is a list (in parentheses) of screen attributes.
INFORMIX-4GL Statement Syntax 7-129

(attribute-list)

INPUT ARRAY

BEFORE ROW INSERT DELETE FIELD

is an optional keyword. is an optional keyword. is an optional keyword. is an optional keyword. is an optional keyword. is a list of one or more fields taken from screen-array.*. is an optional keyword. is an optional keyword. are optional keywords. is usually a list of one or more function or CTRL key designations. The list can also include ESCAPE (if you have specified another key as the Accept key in the OPTIONS statement) or Interrupt (if you have executed a DEFER INTERRUPT statement). is any INFORMIX-4GL statement. is an optional statement that causes the cursor to move immediately to the next field. is a field name to which the cursor should move. is an optional statement directing INFORMIX-4GL to leave the INPUT ARRAY statement immediately. is a statement that terminates an INPUT ARRAY statement. It is required only when a BEFORE, an AFTER, or an ON KEY clause is used.

field-sublist
AFTER INPUT ON KEY

key-list

statement
NEXT FIELD

field-name
EXIT INPUT END INPUT

Notes
1. When you execute the INPUT ARRAY statement with the WITHOUT DEFAULTS clause, INFORMIX-4GL displays in screen-array the values in record-array. You must call set_count() with the number of rows in program-array before the INPUT ARRAY statement. (See a later note for the definition of set_count().) This is appropriate when you are requesting input prior to updating an existing row of a table. 2. When you execute the INPUT ARRAY statement omitting the WITHOUT DEFAULTS clause, INFORMIX-4GL initializes the first row of screen-array and record-array with the default values from the form specification (or from syscolval if no defaults were set in the form). INFORMIX-4GL assigns NULL values for all variables for which no default has been set. As the cursor moves into a blank line of screen-array, INFORMIX-4GL ini7-130 INFORMIX-4GL Statement Syntax

INPUT ARRAY

tializes that line and the corresponding row of record-array. This is appropriate when you are requesting input prior to inserting new rows in a table. 3. The user can insert rows into the middle of existing rows of record-array by pressing the Insert key (the default is the [ F1 ] function key. You can alter the default with the OPTIONS statement). The user can insert rows at the bottom of existing rows in record-array without pressing the Insert key. 4. If the user attempts to insert rows beyond the defined size of the recordarray, INFORMIX-4GL displays a message that the array is full. 5. The user can delete the current row and move the following rows up to fill the gap by pressing the [ F2 ] function key. You can alter this default with the OPTIONS statement. 6. The user can move the cursor and scroll the displayed rows using the Arrow keys and the function keys [ F3 ] and [ F4 ].
RIGHT ARROW

moves the cursor non-destructively (does not blank out the current contents) one space to the right inside a screen field. At the end of the screen field, it causes a jump to the first character position of the next screen field. moves the cursor non-destructively one space to the left inside a screen field. At the end of the screen field, it causes a jump to the first character position of the previous screen field. moves the cursor down one row on the screen. If the cursor was on the last row of the screen array before the user pressed [ ↓ ], the displayed data moves up one row. moves the cursor up one row on the screen. If the cursor was on the first row before the user pressed [ ↑ ], the displayed data moves down one row. If the first program array row is already on the first screen array row, [ ↑ ] does nothing. scrolls the display to the next full page of program array rows. You can reset this key using the OPTIONS statement. scrolls the display to the previous full page of program array rows. You can reset this key using the OPTIONS statement.

LEFT ARROW

DOWN ARROW

UP ARROW

F3

F4

INFORMIX-4GL Statement Syntax

7-131

INPUT ARRAY

7. The INPUT ARRAY statement is terminated when the user enters ESC or the key you specified as the Accept key in the OPTIONS statement. If there is an AFTER INPUT clause, the program control passes to the statements following that clause, rather than to the statements following the END INPUT clause. This feature allows the programmer to perform data validity checks before allowing the INPUT ARRAY statement to terminate. Unlike the INPUT statement, the RETURN does not terminate the statement. 8. The number of variables in a row of record-array must be the same as the number of fields in a row of screen-array and of the corresponding data type. 9. INFORMIX-4GL executes BEFORE, AFTER, and ON KEY clauses in the following order:
BEFORE ROW BEFORE INSERT, DELETE BEFORE FIELD ON KEY AFTER FIELD AFTER INSERT, DELETE AFTER ROW AFTER INPUT

10. INFORMIX-4GL passes control to the statements following a BEFORE ROW clause when

• • • •

The cursor moves into a new form row. An Insert fails due to lack of space. Insert is aborted with an Interrupt. The user performs a Delete ([ F2 ]).

11. INFORMIX-4GL passes control to the statements following a BEFORE INSERT clause when

• The user presses the Insert key ([ F1 ]). • A row is added automatically at the end of an array.
12. INFORMIX-4GL passes control to the statements following a BEFORE DELETE clause when the user presses the Delete key ([ F2 ]). 13. INFORMIX-4GL passes control to the statements following a BEFORE FIELD clause when the cursor enters a field. 14. INFORMIX-4GL passes control to the statements following an ON KEY clause when the user presses a key named in key-list. 15. INFORMIX-4GL passes control to the statements following an AFTER FIELD clause when the cursor leaves a field.
7-132 INFORMIX-4GL Statement Syntax

INPUT ARRAY

16. INFORMIX-4GL passes control to the statements following an AFTER INSERT clause when the user inserts a row and leaves it (without necessarily entering data into it). 17. INFORMIX-4GL passes control to the statements following an AFTER DELETE clause when the user presses the Delete key ([ F2 ]) and the row has been deleted. 18. INFORMIX-4GL passes control to the statements following an AFTER ROW clause when

• The cursor leaves the row by any means. • An INSERT is complete.
19. INFORMIX-4GL passes control to the statements following an AFTER INPUT clause when the user presses ESC or the key specified as the Accept key in the OPTIONS statement. 20. If there is no NEXT FIELD statement in the sequence of statements following a BEFORE or AFTER clause, the cursor moves to the next field in the direction that the user indicated (forward for [ → ] or RETURN and backward for [ ← ]). 21. If the user triggers an ON KEY clause while entering data into a field, INFORMIX-4GL suspends the input of the current field while it executes the statements in the ON KEY clause. It preserves the input buffer that contains the characters the user typed before triggering the ON KEY clause, restores them when the ON KEY clause returns, and resumes the input in the same field with the cursor at the end of the buffered list of characters. If you want to use the ON KEY clause to fill the field with another value, be sure to move to a new field with the NEXT FIELD statement to prevent the INPUT ARRAY statement from ignoring the new value. 22. The notation for function keys is F1 through F36. The notation for CTRL keys is CONTROL-key, where key is any letter except A, D, H, L, R, or X. The notation for ESCAPE is ESCAPE or ESC. The notation for the Interrupt key is INTERRUPT. Appendix I, “Modifying termcap and terminfo,” describes how to verify that the termcap and terminfo entries for your terminal allow INFORMIX-4GL to recognize function keys. 23. By default, both ESCAPE and Interrupt are exits from the INPUT ARRAY statement. If the DEFER INTERRUPT statement has been executed, an Interrupt causes INFORMIX-4GL to set int_flag to nonzero and terminate the INPUT ARRAY statement (unless the function of Interrupt has been redefined in an ON KEY clause). Otherwise, an Interrupt causes an immediate program stop.
INFORMIX-4GL Statement Syntax 7-133

INPUT ARRAY

24. You can include the following keys in a key-list under the stated conditions:

ESCAPE, if you have specified another key as the Accept key in the OPTIONS statement. OPTIONS statement.

• [ F1 ] if you have specified another key as the Insert key in the • [ F2 ] if you have specified another key as the Delete key in the
OPTIONS statement.

• [ F3 ] if you have specified another key as the Next key in the OPTIONS
statement.

• [ F4 ] if you have specified another key as the Previous key in the
OPTIONS statement.

• Interrupt if you have executed a DEFER INTERRUPT statement.
(When the user presses the Interrupt key under these conditions,
INFORMIX-4GL executes the statements in the ON KEY clause and sets int_flag to nonzero, but does not terminate the INPUT ARRAY

statement.) You cannot use the following keys in a key-list:

CTRL-A, CTRL-D, CTRL-H, CTRL-L, CTRL-R, or CTRL-X since these keys are reserved for editing functions in the INPUT ARRAY statement.

• Other keys that may have special meaning on your operating system.
25. Use of CTRL-I and CTRL-J in a key-list can conflict with normal data entry. 26. In addition to the RETURN, ESCAPE, Interrupt, function, and Arrow keys, the user can employ the following keys for editing during an INPUT ARRAY statement:
CTRL-A CTRL-D CTRL-H CTRL-L CTRL-R CTRL-X

toggles between insert and typeover mode. deletes characters from the current cursor position to the end of the field. moves the cursor non-destructively one space to the left inside a field. moves the cursor non-destructively one space to the right inside a field. redisplays the screen. deletes the character beneath the cursor.

27. The function infield(field) from the function library returns TRUE if the current field is field and FALSE otherwise. It can be used to make fielddependent responses when the user presses a key in the key-list of an
7-134 INFORMIX-4GL Statement Syntax

INPUT ARRAY

ON KEY clause. If you call infield(field) outside the INPUT ARRAY statement, it returns a value corresponding to the field that was current when INPUT ARRAY was terminated.

28. Do not execute PROMPT, INPUT, or INPUT ARRAY statements within the BEFORE, AFTER, or ON KEY clauses of an INPUT ARRAY statement. However, you can call a function that executes one of these statements. 29. Four functions are required to keep track of the relative state of the cursor, the program array, and the screen array. The functions are defined as follows: arr_curr( ) returns the current record-array row. This is the row where the cursor is at the beginning of the [ BEFORE | AFTER ] ROW block, not the row the cursor moves to after execution of the block. returns the total number of filled rows in record-array. returns the current row of screen-array. The current row is defined in the same way that the current row for arr_curr( ) is defined. takes an argument that is the total number of filled rows in record-array. You must call this function before executing the INPUT ARRAY WITHOUT DEFAULTS, so that the program knows the initial value of arr_count( ).

arr_count( ) scr_line( )

set_count( )

30. If you do not use the ATTRIBUTE clause, the display attributes of the input fields are governed by the INPUT ATTRIBUTE clause of the most recent OPTIONS statement. (The description of the OPTIONS statement lists the order of precedence among different sources of 4GL screen attribute specifications.) 31. In an INPUT ARRAY statement, any screen attributes specified in attribute-list apply to all the fields in field-list or screen-record. 32. If you use the ATTRIBUTE clause, none of the default attributes listed in syscolatt or in the form specification file for fields in field-list or screen-record apply (including any default values from the DEFAULT attribute). The attribute-list temporarily overrides any attributes specified in an OPTIONS, DISPLAY FORM, or OPEN WINDOW statement for these fields.

INFORMIX-4GL Statement Syntax

7-135

INPUT ARRAY

33. These keywords can appear in the ATTRIBUTE clause:
WHITE = NORMAL YELLOW = BOLD MAGENTA = BOLD RED = BOLD CYAN = DIM GREEN = DIM BLUE = DIM BLACK = INVISIBLE REVERSE BLINK UNDERLINE

You can specify zero or one of the keywords in the left-hand columns, and from zero to three from the right-hand column (but some terminals may not support some combinations). On color terminals, NORMAL is interpreted as WHITE, BOLD as RED, DIM as BLUE, and INVISIBLE as BLACK. Do not include the equal ( = ) sign, which in this table shows the effect on monochrome terminals of keywords that specify color. These keywords cannot produce the effects suggested by their names unless the termcap or terminfo files and the physical terminals support the attribute. (See Appendix I, “Modifying termcap and terminfo.”) Note: Some terminal entries in termcap or terminfo include the sg#1 or xmc#1 capabilities. On these terminals, the first character of variable-list is replaced by a blank if you use the INPUT statement with any display attribute. To be safe, make sure that fields in any line of the screen form begin after column 1, if you specify display attributes. 34. On UNIX systems that use terminfo files rather than termcap, INFORMIX-4GL does not support attributes that specify colors, and the only valid attribute-list keywords are REVERSE and UNDERLINE.

7-136

INFORMIX-4GL Statement Syntax

INPUT ARRAY

Example
The following program fragment assumes that one column of the screen array (sc_array) contains the row number (row_num) of the program array (pa_array) being displayed there. The next column of sc_array is called first_data. The program recalculates and displays the row number after the user inserts new rows or deletes old ones.
DEFINE pa_total INTEGER DEFINE pa_curr DEFINE sc_curr INTEGER INTEGER # # # # # # # # total number of rows in program array current program array row number current screen array row number total number of rows in screen array

DEFINE sc_total INTEGER

DEFINE k SMALLINT INPUT ARRAY pa_array FROM sc_array.* AFTER INSERT, DELETE LET pa_curr = arr_curr() LET pa_total = arr_count() LET sc_curr = scr_line() FOR k = pa_curr TO pa_total LET pa_array[k].row_num = k IF sc_curr <= sc_total THEN DISPLAY k TO sc_array[sc_curr].row_num LET sc_curr = sc_curr + 1 END IF END FOR END INPUT

Related Statements
DISPLAY ARRAY, EXIT, INPUT, OPTIONS

INFORMIX-4GL Statement Syntax

7-137

INSERT

INSERT
Overview
Use the INSERT statement to insert one or more new rows into an existing table.

Syntax
INSERT INTO table-name [ ( column-list ) ] { VALUES ( value-list ) | SELECT-statement }

Explanation
INSERT INTO

are required keywords. is the name of the table to which to add rows. is a list of the names of the columns into which to insert data. You can enter one column name or a series of column names, separated by commas. is a keyword. are the values to insert into the columns that you specified. You can enter one or more program variables or constants, separated by commas. is a valid SELECT statement.

table-name column-list

VALUES

value-list

SELECT-statement

Notes
1. INFORMIX-4GL inserts data into the columns in the specified table in the order in which you enter column names. It inserts the first value that you enter into the first listed column, the second value into the second listed column, and so on. 2. Entering column names is optional. If you omit them, 4GL assumes that the values are listed in the order in which the columns are listed in the syscolumns systems catalog. Unless you have subsequently used the ALTER TABLE statement to change the order, the order is the same as when the table was created. 3. If you have previously defined a RECORD type program variable LIKE table-name, you can use the program variable in place of a list of values in an INSERT statement.
7-138 INFORMIX-4GL Statement Syntax

INSERT

4. When you execute an INSERT statement, INFORMIX-4GL inserts a single row into the database (unless a SELECT statement appears after the VALUES clause). If you DECLARE a cursor for an INSERT statement and use the OPEN, PUT, FLUSH, and CLOSE statements, INFORMIX-4GL buffers the rows in memory and writes to disk only when the buffer is full. 5. 4GL inserts the rows of data that result from the SELECT statement into the table, just as though you had entered them with the VALUES keyword. 6. You cannot use table-name in the FROM clause of the SELECT statement. The data must be selected from other tables. 7. Do not include an INTO TEMP clause or an ORDER BY clause in the SELECT statement. 8. Although the values that you insert do not have to be of the same data type as the columns themselves, they must be compatible. You can insert only CHAR data into CHAR columns, and only numbers or character representation of number data into number columns. 9. Enter a zero (0) for a SERIAL column in the INSERT statement if you want 4GL to insert the next SERIAL value for the table. Enter a nonzero value for a SERIAL column that does not duplicate a value already in the table, if you want 4GL to use that value. An error occurs if you enter a nonzero value for a SERIAL column that duplicates a value already in the table, and if a UNIQUE index or constraint is defined on the column. In this case, the status is set to a negative value. 10. You can use program variables in the list of values. 11. Enclose string constants (including those that evaluate to DATE, DATETIME, or INTERVAL values) in quotation marks. (See Appendix J for examples of inserting DATETIME and INTERVAL values.) 12. When you create a database with transactions that is not MODE ANSI, each INSERT statement that you execute is treated as a single transaction, even if you do not use the BEGIN WORK and COMMIT WORK or ROLLBACK WORK statements. 13. Each row affected by the INSERT statement within a transaction is locked for the duration of the transaction; therefore, a single INSERT statement that affects a large number of rows locks those rows until the entire operation is completed. If the number of rows affected is very large, you might exceed the limits that your operating system places on the maximum number of simultaneous locks. If this occurs, you may want either to

INFORMIX-4GL Statement Syntax

7-139

INSERT

reduce the scope of the INSERT statement or lock the entire table before executing the statement. See the section “Locking” in Chapter 3 for a more detailed description of table-level and row-level locking in INFORMIX-4GL. Caution: 4GL makes every possible effort to perform data conversion, including converting the character string ‘‘123’’ into the integer 123. If the data cannot be converted, however, INSERT stops. Unless you have created the database with transactions, all changes made to that point remain, but subsequent rows from the SELECT statement will not be inserted. Data conversion also fails if the target data type cannot hold the value offered. For example, you cannot insert the integer 123456 into a SMALLINT.

Examples
DEFINE ps_customer RECORD LIKE customer.* ... INSERT INTO customer VALUES (ps_customer.*) INSERT INTO customer VALUES (0, f_name, l_name, comp, addr1, addr2, "Palo Alto", "CA", zip, phone)

Related Statements
DECLARE, DELETE, SELECT

7-140

INFORMIX-4GL Statement Syntax

LABEL

LABEL
Overview
Use the LABEL statement to indicate the position in a 4GL program to which the GOTO statement transfers control.

Syntax
LABEL label-id:

Explanation
LABEL

is a required keyword. is an INFORMIX-4GL identifier, followed by a colon ( : ).

label-id:

Note
The LABEL statement must be in the same program block (MAIN, FUNCTION, or REPORT) as the GOTO statement with the same label-id. You cannot use GOTO to transfer out of a routine.

Example
IF customer_num < 0 THEN GOTO abort END IF statement ... LABEL abort: statement

Related Statements
GOTO, WHENEVER

INFORMIX-4GL Statement Syntax

7-141

LET

LET
Overview
Use the LET statement to assign a value to a program variable.

Syntax
LET variable = expr

Explanation
LET

variable expr

is a required keyword. is the identifier of a simple program variable. is an expression.

Notes
1. The variable can be an element of an ARRAY if that element is a simple variable. 2. As an exception to the .* notation, you may make assignment to a record variable from another record variable using the statement
LET x.* = y.*

This statement is shorthand for a sequence of LET statements assigning values of elements of y to elements of x.

Examples
LET a = b + c LET d[index] = "This is a string" LET newstr = mystr[2,6]

Related Statement
INITIALIZE

7-142

INFORMIX-4GL Statement Syntax

LOAD

LOAD
Overview
Use the LOAD statement to fill an existing table with data taken from an ASCII file.

Syntax
LOAD FROM "pathname" [ DELIMITER "char" ] { INSERT INTO table-name [ ( column-name [ , . . . ] ) ] | INSERT-stmt }

Explanation
LOAD FROM

are required keywords. is a character variable or constant that evaluates to the pathname of a file that contains rows of data. is an optional keyword to indicate that the following char appears at the end of each data field in the file. is a CHAR variable or a quoted string containing exactly one character. are keywords to specify where to store the data. is the identifier of an existing table. is a column name (in parentheses) in table-name. is a character string or variable containing the text of an
INSERT statement in the form shown here, with no VALUES clause or SELECT clause.

pathname
DELIMITER

char
INSERT INTO

table-name column-name
INSERT-stmt

Notes
1. You must have INSERT permission to use the LOAD statement. 2. You can specify an optional list of one or more column names, enclosed within parentheses and separated by commas. 3. Fields in the input file must be separated by a delimiter character. If you do not specify a delimiter in the DELIMITER clause, INFORMIX-4GL

INFORMIX-4GL Statement Syntax

7-143

LOAD

checks the DBDELIMITER environment variable and uses this setting, if it exists. The default delimiter is the vertical bar ( | = ASCII 124). A character column in the input file can contain the delimiter character. Use a backslash to escape the delimiter character and prevent its interpretation as a field delimiter. 4. The LOAD statement can accept the format of data from a file written by the UNLOAD statement (described later in this chapter). 5. The number of data fields in the load file must equal the number of columns in the table (or in the optional list of column names). 6. The order and data type of the data fields in the file must match the order and data type of the columns specified in the database table. There must be exactly as many delimited fields in each line of the file as the number of columns that you imply or specify in the INTO clause. The length of each data field must be less than or equal to the length specified for each column of the database table. The value in each field must be convertible to the data type of the corresponding column. 7. See also “The dbload Utility,” described in Appendix E, which gives you more options for the format of the input file. 8. A NULL column should be represented in the input file by no characters between delimiters. 9. A blank CHAR column should be represented in the input file by one or more blank characters between delimiters. 10. It is permissible to have leading blanks in number, DATE, and MONEY fields. 11. DATE fields should have the format mm/dd/yyyy. Here mm is the month (1 or 01 for January, and so on), dd is the day, and yyyy is the year. If the format of the DATE field is mm/dd/yy, the yy is interpreted as 19yy. Any value in a DATE field must be a legal date (for example, February 30 is illegal). 12. MONEY fields can have leading currency symbols. 13. DATETIME and INTERVAL values must be in character form, showing only field digits and delimiters (with no type specification or qualifiers). The required pattern is the substring of yyyy-mm-dd hh:mi:ss.fff, which corresponds to the qualifier associated with the column. 14. If your database has transactions but is not MODE ANSI, you must issue a BEGIN WORK statement before using LOAD. 15. LOAD appends new rows to the table, rather than overwriting existing data.

7-144

INFORMIX-4GL Statement Syntax

LOAD

16. You cannot PREPARE a LOAD statement. 17. The embedded INSERT statement is restricted to the syntax shown here and cannot include a VALUES clause or a SELECT statement. 18. When you execute a LOAD statement, INFORMIX-4GL sets status to zero to indicate success, or to an error number to indicate failure. If an error occurs, the SQLCODE and SQLERRD[2] error codes are set, as described in Chapter 3. In any case, the value of SQLERRD[3] is set to the number of rows that LOAD inserted.

Example
LOAD FROM "/a/data/ord.loadfile" DELIMITER ";" INSERT INTO orders LOAD FROM "/tmp/prices" DELIMITER "," INSERT INTO walter.worktab(price,discount)

Related Statements
UNLOAD, INSERT

Note: INFORMIX-OnLine supports additional data types. Refer to the INFORMIX-OnLine Programmer’s Manual for more information.

INFORMIX-4GL Statement Syntax

7-145

LOCK TABLE

LOCK TABLE
Overview
Use the LOCK TABLE statement to control access to a table by other users.

Syntax
LOCK TABLE table-name IN { SHARE | EXCLUSIVE } MODE

Explanation
LOCK TABLE

are required keywords. is the name of the table you want to lock. is a required keyword. is a keyword to give other users read access to the table, but to prevent them from modifying any of the data that it contains. is a keyword to prevent other users from having any access to the table. is a required keyword.

table-name
IN SHARE

EXCLUSIVE MODE

Notes
1. Only one lock can apply to a table at any given time. That is, if a user locks a table (in either SHARE or EXCLUSIVE mode), no other user can lock that table in either mode until the first user unlocks it. 2. If your database has transactions and is not MODE ANSI, you must issue a BEGIN WORK statement before you can issue the LOCK TABLE statement. 3. You can use the LOCK TABLE statement immediately after beginning a transaction to override row-level locking during the transaction. Normally, each row of a table affected by a statement within a transaction is locked for the duration of the transaction. During transactions that affect a large number of rows, you can exceed the limit that your operating system places on the maximum number of locks. If you lock the entire table at the beginning of the transaction, however, INFORMIX-4GL does not lock each row in the table. You may want to use
7-146 INFORMIX-4GL Statement Syntax

LOCK TABLE

this strategy when executing a transaction that affects a large number of rows or every row in a table. See the section “Locking” in Chapter 3 for more information about tablelevel and row-level locking in INFORMIX-4GL. 4. You cannot lock system catalogs. (See Appendix B for a list of system catalogs.)

Example
LOCK TABLE orders IN EXCLUSIVE MODE

Related Statements
BEGIN WORK, COMMIT WORK, UNLOCK TABLE

INFORMIX-4GL Statement Syntax

7-147

MAIN

MAIN
Overview
Use the MAIN keyword to introduce the MAIN program block.

Syntax
MAIN statement ... END MAIN

Explanation
MAIN

is a required keyword. is any INFORMIX-4GL statement except MAIN. are required keywords that terminate the MAIN program block.

statement
END MAIN

Note
Every INFORMIX-4GL program must have a MAIN program block and can have one or more functions and reports.

Related Statements
FUNCTION, REPORT

7-148

INFORMIX-4GL Statement Syntax

MENU

MENU
Overview
Use the MENU statement to create a menu screen, to define user menu options, to designate help numbers, and to define what statements should be executed for each option.

Syntax
MENU "menu-name" COMMAND { KEY ( key-list ) | [ KEY ( key-list ) ] "menu-option" [ "helpline" ] [ HELP help-number ] } statement ... [ CONTINUE MENU ] ... [ EXIT MENU ] ... [ NEXT OPTION "menu-option" ] ... ... END MENU

Explanation
MENU

is a required keyword. is a character string giving the title of the menu. is a required keyword. is an optional keyword. is a list of one or more letters, function key identifiers, or CTRL key identifiers, separated by commas. You do not need to put quotation marks around single, printable characters. is a single-word label for a menu option. The menu-option must be enclosed in quotation marks ( " ). is a one-line character string describing the menu-option. The helpline must be enclosed in quotation marks ( " ). is an optional keyword.

menu-name
COMMAND KEY

key-list

menu-option helpline

HELP

INFORMIX-4GL Statement Syntax

7-149

MENU

help-number

is the number of the help message in the help file designated in the OPTIONS statement that corresponds to menu-option. is an INFORMIX-4GL statement that you want executed when the user selects the preceding option. Several statements can exist for each option. is an optional statement that returns program control to the current MENU statement. is an optional statement that causes program control to move to the first statement following the END MENU keywords. are optional keywords that precede the menu option that you want highlighted when you return to the menu. are required keywords that terminate the MENU statement.

statement

CONTINUE MENU EXIT MENU

NEXT OPTION

END MENU

Notes
1. You must define at least two options (COMMAND clauses) for each menu. 2. The menu screen displays in a ring menu each of the single-word menuoptions in the order of the COMMAND clauses. 3. When INFORMIX-4GL displays a menu, it adds a colon (:) and a space after the menu name, as well as a space before and after each menu option. If the width of the menu exceeds the number of characters that the screen or a window can display on a single line, INFORMIX-4GL displays the first ‘‘page’’ of options followed by an ellipsis ( . . . ) indicating that additional options exist. For example,
menu-name: menu-option1 optional Help line menu-option2 menu-option3 menu-option4 ...

If the user presses the SPACEBAR or [ → ] key to move past the rightmost option (menu-option4 in this case), INFORMIX-4GL displays the next
7-150 INFORMIX-4GL Statement Syntax

MENU

page of menu options. In the following example, the ellipses at each end indicate that more menu options exist in both directions.
menu-name: ... menu-option5 optional Help line menu-option6 menu-option7 menu-option8 ...

If the user moves the highlight to the right past menu-option8 in this example, INFORMIX-4GL displays a page of menu options like the following:
menu-name: ... menu-option9 optional Help line menu-option10 menu-option11

Since no ellipsis appears to the right of the menu, the user has come to the last page of the menu options. The user can display the previous page of menu options again by using the [ ← ] key to move the highlight past the leftmost option in the example. The user can display the first page of menu options by using the [ → ] key to move the highlight past the rightmost option in the example. The [ ↑ ] key moves the highlight to the first item on the previous page; the [ ↓ ] key moves the highlight to the first item on the subsequent page. 4. The help-number refers to the number of the help message in the help file set by the OPTIONS statement. 5. A run-time error occurs if you specify a help-number for an option, and that number does not occur in the help file, or if the help file does not exist. 6. You will incur a run-time error if the menu cannot fit on the screen or in the current window.
INFORMIX-4GL Statement Syntax 7-151

MENU

7. INFORMIX-4GL truncates any helpline that exceeds the width of the screen or current window. 8. The user chooses an option by typing one of the letters in key-list. If the KEY clause is not present, the user chooses an option by typing the first letter of menu-option. 9. After the user chooses an option, INFORMIX-4GL executes the statements immediately following the COMMAND clause. 10. After INFORMIX-4GL executes all the statements for an option, it redisplays the menu, and the user can choose another option. 11. You can execute a CONTINUE MENU statement anywhere within the statements following the COMMAND clause. Use of this statement causes the menu to reappear so that the user can choose another option. 12. The key-list notation to specify function keys is F1 through F36. The notation for CTRL keys is CONTROL-key, where key is any letter except A, D, H, L, R, or X (Some other keys, such as CTRL-S, CTRL-Q, or CTRL-Z might also not be allowed, depending on your implementation of the UNIX operating system.) The key-list notation for the key is ESC or ESCAPE. The notation for the Interrupt key (often DEL or CTRL-C) is INTERRUPT. 13. Unless you use the KEY clause, the initial letters of each menu-option should be different, regardless of case. The values within the key-list must be unambiguous. Each option must be uniquely defined. 14. INFORMIX-4GL produces a run-time error if a menu option exceeds the length of the screen or window. 15. You can add a ‘‘hidden’’ option to your menu by including a KEY key-list choice in the list of menu COMMANDs. This is demonstrated in the following example.

7-152

INFORMIX-4GL Statement Syntax

MENU

Example
MENU "TOP LEVEL" COMMAND "Add" "Add a row to the database" HELP 12 ... COMMAND "Find" "Find a row in the database" HELP 13 ... COMMAND "Change" "Update a row in the database" HELP 14 ... COMMAND "Delete" "Delete a row from the database" HELP 15 ... COMMAND key ("!") CALL bang() ... COMMAND "Exit" "Return to operating system" HELP 16 EXIT PROGRAM END MENU

These statements produce the following menu:
TOP LEVEL: Add Find Change Add a row to the database Delete Exit

Related Command
OPTIONS

INFORMIX-4GL Statement Syntax

7-153

MESSAGE

MESSAGE
Overview
Use the MESSAGE statement to display a character string on the Message line.

Syntax
MESSAGE display-list [ ATTRIBUTE ( attribute-list ) ]

Explanation
MESSAGE

is a required keyword. is a list of one or more program variables and/or string constants (enclosed in quotation marks), separated by commas. is an optional keyword. is a list of one or more screen attributes, separated by commas.

display-list
ATTRIBUTE

attribute-list

Notes
1. INFORMIX-4GL generates the message by replacing the variables in display-list with their values and concatenating the resulting strings. 2. The default Message line is the same line used to display the helpline in menus. See the OPTIONS statement for information about resetting this line to a different position. 3. The default attribute for the Message line is the NORMAL display. You can alter the default attribute with the ATTRIBUTE clause.

7-154

INFORMIX-4GL Statement Syntax

MESSAGE

4. The following list shows the screen attributes allowed in the ATTRIBUTE clause:
WHITE = NORMAL YELLOW = BOLD MAGENTA = BOLD RED = BOLD CYAN = DIM GREEN = DIM BLUE = DIM BLACK = INVISIBLE REVERSE BLINK UNDERLINE

On color terminals, NORMAL is interpreted as WHITE, BOLD as RED, DIM as BLUE, and INVISIBLE as BLACK. If you have a colornames file, you can use the color names listed there. (See Appendix I.)

Example
MESSAGE "Enter the order data."

Related Statements
OPTIONS, PROMPT

INFORMIX-4GL Statement Syntax

7-155

OPEN

OPEN
Overview
Use the OPEN statement to establish search criteria for a SELECT cursor and initialize the system for subsequent FETCHes, or to set up an INSERT buffer for an INSERT cursor that references program variables.

Syntax
OPEN cursor-name [ USING variable-list ]

Explanation
OPEN

is a required keyword. is the identifier of a previously declared cursor. is a keyword, needed only if the cursor expects user-supplied search values. is a list of program variables, separated by commas, corresponding to the ‘‘?’’ parameters in a query associated with a SELECT cursor.

cursor-name
USING

variable-list

Notes
1. If cursor-name is associated with a SELECT statement, the OPEN statement examines the content of the program variables and, using these values for the parameters in the SELECT statement, establishes the search criteria for determining the logical set of rows that satisfies the WHERE clause. This set of rows is called the active set. It leaves the cursor in an open state and pointing before the first row of the active set. 2. The active set is a dynamic collection of rows; it is not fixed at the time when the OPEN statement is executed. Rows meeting the WHERE criteria and qualified for FETCHing depend on the activity in the table. 3. Once the active set for a SELECT cursor is determined, the program variables are not reexamined until you reopen the cursor. 4. If a SELECT cursor is already open, an OPEN statement closes the cursor and reopens it, creating a new active set, based on the current values of the program variables.

7-156

INFORMIX-4GL Statement Syntax

OPEN

5. The FOREACH statement performs an implied OPEN statement. You cannot use the FOREACH statement if the OPEN statement for a SELECT cursor must have a USING clause to supply values for ‘‘?’’ parameters in a PREPAREd SELECT statement. 6. If cursor-name is associated with an INSERT statement (rather than a SELECT statement), the OPEN statement cannot include a USING clause. 7. If you reopen an INSERT cursor that is already open, INFORMIX-4GL flushes the INSERT buffer (that is, INFORMIX-4GL inserts any rows currently in the INSERT buffer into the database table). The global variable SQLCA. SQLERRD [3] is set to the number of rows successfully inserted into the database. 8. A cursor declared FOR UPDATE is called an UPDATE cursor. In a database that uses transactions, you cannot OPEN an UPDATE cursor outside a transaction unless it also was declared WITH HOLD. You can OPEN a nonUPDATE cursor, or one declared WITH HOLD, at any time. In a non-MODE ANSI database that has transactions, a transaction begins with a BEGIN WORK statement and ends with a COMMIT WORK or ROLLBACK WORK statement. In a MODE ANSI database, no BEGIN WORK is required; all actions take place inside transactions. 9. If you declare a cursor with a DECLARE statement that includes the SELECT or INSERT keywords, INFORMIX-4GL implicitly PREPAREs the statement when you OPEN that cursor. 10. The database engine allocates resources to explicitly or implicitly PREPAREd statements. If you release resources with FREE cursor-name, you cannot use that cursor unless you OPEN it again. If you specify FREE statement-id, you cannot OPEN a cursor that references statement-id unless you PREPARE that statement again.

Examples
DECLARE s_curs CURSOR FOR SELECT * FROM orders OPEN s_curs DECLARE q_cursor CURSOR FOR SELECT o.order_num, SUM(total_price) FROM orders o, items i WHERE o.order_date > "06/04/86" AND o.customer_num = 110 AND o.order_num = i.order_num GROUP BY o.order_num OPEN q_cursor

INFORMIX-4GL Statement Syntax

7-157

OPEN

Related Statements
CLOSE, DECLARE, FETCH, FLUSH, FOREACH, FREE, PREPARE, PUT

7-158

INFORMIX-4GL Statement Syntax

OPEN FORM

OPEN FORM
Overview
Use the OPEN FORM statement to associate an INFORMIX-4GL identifier with a pre-compiled screen form.

Syntax
OPEN FORM form-name FROM "form-file"

Explanation
OPEN FORM

are required keywords. is an INFORMIX-4GL identifier. is a required keyword. is the pathname of a compiled screen form (omitting the extension .frm). form-file must be enclosed in quotation marks.

form-name
FROM

form-file

Notes
1. You must open a form before you can display it. 2. When you execute the OPEN FORM statement, the compiled form is loaded into and kept in memory until you execute a CLOSE FORM statement for that form. If you have displayed another form and wish to regain the space used by the first form, you can execute CLOSE FORM on the old form. The CLOSE FORM statement is a memory-management feature only; it does not affect the logic of the program.

Example
OPEN FORM order_form FROM "orderform"

Related Statements
CLOSE FORM, DISPLAY FORM

INFORMIX-4GL Statement Syntax

7-159

OPEN WINDOW

OPEN WINDOW
Overview
Use the OPEN WINDOW statement to create and open a window at a specified origin on the screen. This can optionally display a form.

Syntax
OPEN WINDOW window-name AT row, column WITH { integer ROWS, integer COLUMNS | FORM "form-file" } [ ATTRIBUTE ( attribute-list ) ]

Explanation
OPEN WINDOW

are required keywords. is the name of the window that you want to create. is a required keyword. is an integer or integer variable between one and the maximum number of lines allowed by your terminal (usually 24), indicating the line on the screen where the top of the window will appear. is an integer or integer variable between one and the maximum number of columns allowed by your terminal (usually 80), indicating the column of the screen where the left margin of the window will appear. is a required keyword to specify the vertical and horizontal dimensions of the window, in characters. is an integer or integer variable. is a keyword to specify the height of the window. is a keyword to specify the width of the window. is an optional keyword. is the pathname of a compiled form specification file (excluding the .frm extension). is an optional keyword. is a list of one or more window display attributes.

window-name
AT

row

column

WITH

integer
ROWS COLUMNS FORM

form-file
ATTRIBUTE

(attribute-list)

7-160

INFORMIX-4GL Statement Syntax

OPEN WINDOW

Notes
1. When you open a window, INFORMIX-4GL saves any current window and makes the new window the current window. 2. The window-name is a 4GL identifier whose scope is global to the entire program. It must begin with a letter. Up to 17 additional characters can include letters, numbers, and underscores ( _ ). 3. You can use the WITH integer ROWS, integer COLUMNS clause to specify explicit dimensions for the window. Alternatively, you can include a WITH FORM clause, so that INFORMIX-4GL automatically opens a window sized to the screen layout of form-file and displays the form. INFORMIX-4GL determines the width of the window from the rightmost character of the screen form and calculates the length of the window as this sum:
( FORM LINE (relative to the first line of the window) -1 ) + form-length + 1 (for the COMMENT LINE )

Unless you specify FORM LINE in an ATTRIBUTE clause or in the OPTIONS statement, the default value of this sum is form-length + 1, where form-length is the number of lines in the screen layout of form-file. (Chapter 4 describes the screen layout.) 4. The WITH FORM clause is convenient when you want to open a window that displays a single form. You cannot use a CLOSE FORM statement to close a form that the WITH FORM clause displays, but CLOSE WINDOW closes the form automatically. If you want to display more than one form in a window or want a window larger than the one that INFORMIX-4GL creates when it executes the WITH FORM clause, you must specify explicit window dimensions with the WITH integer ROWS, integer COLUMNS clause. In that case, you must also open, display, and close the form(s) yourself. 5. When you OPEN a window, INFORMIX-4GL uses line-values specified in the most recently executed OPTIONS statement for the Prompt, Message, Form, and Comment lines. Values are relative to the first or last line of the newly opened window. To change the values for these reserved lines (without disabling the OPTIONS statement specifications for other windows), you can include an ATTRIBUTE clause. 6. An ATTRIBUTE clause in the OPEN WINDOW statement can include the following attributes:

INFORMIX-4GL Statement Syntax

7-161

OPEN WINDOW

Attribute BORDER color (see note 13) REVERSE PROMPT LINE line-value MESSAGE LINE line-value FORM LINE line-value COMMENT LINE line-value

Default Setting No border The default foreground color on your terminal No reverse video FIRST ( = 1 ) FIRST + 1 ( = 2 ) FIRST + 2 ( = 3 ) LAST - 1 (for the screen) LAST (for all other windows)

After the PROMPT, MESSAGE, and COMMENT keywords, line-value can be an integer, a program variable, FIRST plus an optional integer, or LAST minus an optional integer. For the Form line, line-value can be an integer, a program variable, or FIRST plus an optional integer. 7. If a window is not large enough to contain the specified value for one or more of these reserved lines, INFORMIX-4GL increases its line-value to FIRST or decreases it to LAST, as appropriate. 8. If the window is not wide enough to display part of the text that you specify with the PROMPT, MESSAGE, or DISPLAY statement (or with the COMMENTS attribute of a screen form), INFORMIX-4GL generates a runtime error. 9. INFORMIX-4GL displays system error messages and text associated with the ERROR statement in a borderless window on the Error line. INFORMIX-4GL opens the window as necessary and closes it at the next keystroke to erase the message. Since the position of the Error line is relative to the screen, rather than to the current window, the ATTRIBUTE clause of an OPEN WINDOW statement cannot change its location. 10. If a window and its border (if any) exceed the physical limits of the screen, INFORMIX-4GL generates a run-time error.

7-162

INFORMIX-4GL Statement Syntax

OPEN WINDOW

11. When you use the BORDER attribute, INFORMIX-4GL draws a border outside the window area that you specify. For example, if you open the following window
OPEN WINDOW w1 AT 10,10 WITH 5 ROWS, 30 COLUMNS ATTRIBUTE (BORDER) INFORMIX-4GL displays a border with coordinates like those in the fol-

lowing example:
(9,9) (9,40) +------------------------------+ | | | | | | | | | | +------------------------------+ (15,9) (15,40) INFORMIX-4GL draws the border with characters defined in the termcap

or terminfo files. You can specify alternative border characters in these files. Otherwise, INFORMIX-4GL uses the hyphen ( - ) for horizontal lines, the vertical bar ( | ) for vertical lines, and the plus ( + ) sign for corners, as illustrated in the preceding example. See Appendix I, “Modifying termcap and terminfo,” and the manual that comes with your terminal for information about making changes to your termcap or terminfo files. Note: Some terminals do not support the features described in Appendix I. 12. The termcap or terminfo entries for some terminals include, respectively, the sg#1 or xmc#1 capabilities. On these terminals, INFORMIX-4GL reserves an additional column to the left and to the right of the window. These two columns are reserved, whether you specify a border or not. INFORMIX-4GL uses a total of four extra columns for bordered windows on these terminals: two columns to the left of the window, and two columns to the right. 13. Use any of the following keywords for color in an ATTRIBUTE clause to specify the foreground of a window:
WHITE YELLOW MAGENTA RED CYAN GREEN BLUE BLACK DIM INVISIBLE BOLD NORMAL

14. If you specify a color in the ATTRIBUTE clause of an OPEN WINDOW statement, it becomes the default color for anything displayed in the window except a menu. You can override the default color for a particular display by specifying a different color in the ATTRIBUTE clause of a CONSTRUCT,
INFORMIX-4GL Statement Syntax 7-163

OPEN WINDOW

DISPLAY, DISPLAY ARRAY, DISPLAY FORM, INPUT, or INPUT ARRAY

statement. 15. Windows are stacked in the order that they are opened. See the CURRENT WINDOW and CLOSE WINDOW statements for information about how these statements affect the window stack.

Examples
OPEN WINDOW w1 AT 5, 5 WITH FORM "custform" OPEN WINDOW w2 AT 10, 12 WITH 5 ROWS, 40 COLUMNS ATTRIBUTE (BORDER, PROMPT LINE 3)

Related Statements
CLEAR WINDOW, CLOSE FORM, CLOSE WINDOW, CURRENT WINDOW, OPTIONS

7-164

INFORMIX-4GL Statement Syntax

OPTIONS

OPTIONS
Overview
The OPTIONS statement can modify the reserved line positions and input or display attributes for screen forms, and can change the keys for screen operations and program aids (like help messages).

Syntax
OPTIONS {MESSAGE LINE line-value | PROMPT LINE line-value | COMMENT LINE line-value | ERROR LINE line-value | FORM LINE line-value | INPUT { WRAP | NO WRAP } | INSERT KEY key-name | DELETE KEY key-name | NEXT KEY key-name | PREVIOUS KEY key-name | ACCEPT KEY key-name | HELP FILE "help-file" | HELP KEY key-name | INPUT ATTRIBUTE ( attribute-list ) | DISPLAY ATTRIBUTE ( attribute-list ) } [ , . . . ]

Explanation
OPTIONS

is a required keyword. is an integer expression, indicating the line of the current window or screen to display the reserved line specified by the preceding keywords. The line-value can include the keywords FIRST or LAST. are optional keywords to position the Message line. The default line-value is FIRST + 1 (that is, line 2 of the current window). are optional keywords to position the Prompt line. The default line-value is the FIRST window line. are optional keywords to position the Comment line. The default line-value is LAST - 1 for the screen, and LAST for all other windows. are optional keywords to position the Error line. The default line-value is the LAST line of the screen.
INFORMIX-4GL Statement Syntax 7-165

line-value

MESSAGE LINE PROMPT LINE COMMENT LINE
ERROR LINE

OPTIONS

FORM LINE

are optional keywords to position the first line of a form. The default line-value is FIRST + 2 (that is, the form will begin on line 3 of the current window). are optional keywords indicating that the cursor wraps around the list of input fields during the execution of an INPUT or CONSTRUCT statement until the Accept key is pressed. The default is INPUT NO WRAP. are optional keywords indicating that the INPUT or CONSTRUCT statement terminates upon a RETURN after the last field. This option is the default. designates or a function or CTRL key whose action is specified by preceding keywords. are optional keywords to specify the key that opens up a line for data insertion in INPUT ARRAY statements. If you do not specify an Insert key, the default is [ F1 ]. are optional keywords to specify the key that deletes a line in INPUT ARRAY statements. The default is [ F2 ]. are optional keywords to specify the key that scrolls to the next page in the INPUT ARRAY or DISPLAY ARRAY statement. The default is [ F3 ].

INPUT WRAP

INPUT NO WRAP

key-name
INSERT KEY

DELETE KEY NEXT KEY

PREVIOUS KEY are optional keywords to specify the key that scrolls to the previous page in the INPUT ARRAY or DISPLAY ARRAY statement. The default is [ F4 ]. ACCEPT KEY

are optional keywords specifying the key to terminate the INPUT, INPUT ARRAY, DISPLAY ARRAY, and CONSTRUCT statements. If you do not specify an Accept key, the default is the ESCAPE key. are optional keywords to specify the file that contains programmer-defined help messages. (Appendix E describes mkmessage, the help message utility.) is the pathname, enclosed in quotation ( " ) marks, of the file containing help messages. are optional keywords to specify the key that displays help messages. The default is CTRL-W. are optional keywords to specify field attributes that are in effect when data values are entered. is a list of one or more screen display attributes, or the keywords FORM or WINDOW.

HELP FILE

help-file
HELP KEY

INPUT ATTRIBUTE attribute-list

7-166

INFORMIX-4GL Statement Syntax

OPTIONS

DISPLAY ATTRIBUTE

are optional keywords to specify screen attributes that are in effect when data values are displayed.

Notes
1. You can use the OPTIONS statement to change the defaults listed earlier. (If you list more than one item in an OPTIONS statement, make sure to separate the items with commas.) 2. You can issue the OPTIONS statement more than once. The values set in the last OPTIONS statement encountered at run time prevail. 3. The line-value to position the Form line can be either integer or FIRST [ + integer]. The line-value of the other reserved lines can have any of the following formats:
integer FIRST LAST [ + integer ] [ - integer ]

Here FIRST is the first line of the current window (line 1), and LAST is the last line of the current window. 4. The line-value for the Error line is relative to the screen, rather than to the current window. The line-value of any other reserved line is relative to the first line of the current window (or to the screen, if that is the current window). 5. The key-name notation to specify function keys is F1 through F36. The key-name notation for CTRL keys is CTRL-key, where key is any letter except A, D, H, L, Q, R, S, or X. The key-name notation for is ESC or ESCAPE. 6. INFORMIX-4GL uses the CTRL keys CTRL-A, CTRL-D, CTRL-H, CTRL-L, CTRL-R, and CTRL-X for screen-editing functions. You cannot use these for the Insert key, Delete key, Next key, Previous key, Accept key, or Help key. In addition, you might not be able to use some other keys, such as CTRL-C, CTRL-S, CTRL-Q, or CTRL-Z, depending on your implementation of the UNIX operating system. 7. During a CONSTRUCT, DISPLAY, DISPLAY ARRAY, DISPLAY FORM, INPUT, or INPUT ARRAY statement, INFORMIX-4GL checks for attributes and reserved line positions in the following order of precedence (from highest to lowest): 1. Any ATTRIBUTE clause in the current statement. 2. Any attributes from field descriptions in the current form file. (See the “Attributes Syntax” section of Chapter 4.)
INFORMIX-4GL Statement Syntax 7-167

OPTIONS

3. Any default attributes in the syscolatt table of fields linked to database columns. (See the description of the “The upscol Utility” in Appendix E.) 4. Any attributes and reserved line positions specified in the most recent OPTIONS statement. 5. Any ATTRIBUTE clause for the current form in the most recent DISPLAY FORM statement. 6. Any ATTRIBUTE clause of the current window in the most recent OPEN WINDOW statement. 7. The default reserved line positions and the default foreground color on your terminal. 8. The attribute-list supports the same keyword options as in the ATTRIBUTE clause of the DISPLAY statement, plus two additional options, FORM and WINDOW:
WHITE YELLOW MAGENTA RED CYAN GREEN BLUE BLACK DIM INVISIBLE BOLD NORMAL REVERSE BLINK UNDERLINE FORM WINDOW

9. The INPUT ATTRIBUTE clause specifies the screen attributes to be used during a CONSTRUCT, INPUT, or INPUT ARRAY statement when no attribute-list is specified in those statements or in the specification file of the current form. 10. Similarly, the DISPLAY ATTRIBUTE clause specifies the screen attributes to be used during a DISPLAY or DISPLAY ARRAY statement when no attribute-list is specified in those statements or in the specification file of the current form. 11. Include the FORM keyword with a DISPLAY ATTRIBUTE or INPUT ATTRIBUTE statement to instruct INFORMIX-4GL to use the display attributes of the current form. Use the WINDOW keyword of the same statements to instruct INFORMIX-4GL to use the display attributes of the current window.

7-168

INFORMIX-4GL Statement Syntax

OPTIONS

Examples
The following statement sets three reserved line positions and specifies the Next and Previous keys:
OPTIONS MESSAGE LINE 23, PROMPT LINE LAST-2, FORM LINE FIRST, NEXT KEY CONTROL-N, PREVIOUS KEY CONTROL-P

The following statement causes screen fields to appear as green where values are input, regardless of the foreground form color or window color:
OPTIONS INPUT ATTRIBUTE (green)

Related Statements
CONSTRUCT, DISPLAY, DISPLAY ARRAY, DISPLAY FORM, ERROR, INPUT, INPUT ARRAY, MENU, MESSAGE, OPEN FORM, OPEN WINDOW, PROMPT

INFORMIX-4GL Statement Syntax

7-169

OUTPUT TO REPORT

OUTPUT TO REPORT
Overview
Use the OUTPUT TO REPORT statement to pass a single row of data to a report.

Syntax
OUTPUT TO REPORT report-name (expr-list)

Explanation
OUTPUT TO REPORT report-name expr-list are required keywords. is the identifier of a report. is a list of one or more expressions, separated by commas.

Notes
1. Ordinarily, you will use the OUTPUT TO REPORT statement within a loop that passes data to a report. 2. The number of expressions in expr-list should agree with the number and type of arguments in the REPORT routine.

Example
OUTPUT TO REPORT rept1 (v_pers.*)

Related Statements
FINISH REPORT, REPORT, START REPORT

7-170

INFORMIX-4GL Statement Syntax

PREPARE

PREPARE
Overview
Use the PREPARE statement to preprocess an SQL statement for later execution. The SQL statements are listed in Chapter 3.

Syntax
PREPARE statement-id FROM string-spec

Explanation:
PREPARE

is a required keyword. is an SQL identifier for a statement. is a required keyword. is either a string constant enclosed in quotation marks or a CHAR type program variable. The string-spec must contain an SQL statement.

statement-id
FROM

string-spec

Notes
1. The statement(s) described in string-spec cannot contain program variables. Use a question mark ( ? ) as a placeholder for an input value that will be supplied in an EXECUTE, OPEN, or PUT statement. Do not use a question mark as a placeholder for an SQL identifier such as a database name, table name, column name, or user name. 2. If you PREPARE a SELECT statement for use with the DECLARE statement, string-spec can include a SELECT statement followed by a FOR UPDATE clause. 3. The string-spec cannot include any of the following statements: CLOSE, DECLARE, EXECUTE, FETCH, LOAD, OPEN, PREPARE, UNLOAD, and WHENEVER. 4. Do not PREPARE a SELECT statement with an INTO clause. 5. The scope of statement-id is the module in which you PREPARE it. You can refer to it by name in functions contained in the same module. It is not, however, a global identifier that you can reference in another source file.

INFORMIX-4GL Statement Syntax

7-171

PREPARE

6. INFORMIX-4GL can execute several SQL statements as one action if you preprocess them all in the same PREPARE statement. To PREPARE multiple SQL statements, the string-spec must use the comma ( , ) concatenation operator between consecutive strings that contain each SQL statement. You must also terminate each string (except the last) with a semicolon ( ; ) symbol before the right-hand quotation ( " ) mark. For an example, see the section “Preparing Multiple SQL Statements” in Chapter 3. (The statements cannot include SELECT, DATABASE, CLOSE DATABASE, CREATE DATABASE, or DROP DATABASE.) 7. Within a module, statement-id can apply to only one SQL statement or sequence of statements. Do not specify the same statement-name in another PREPARE statement in the same module. 8. You can use a subsequent FREE statement to release the database engine resources that have been allocated to statement-id.

Example
LET select_2 = "select * from orders ", "where customer_num = ? and ", "order_date > ?" PREPARE query_2 FROM select_2

Related Statements
DECLARE, EXECUTE, FOREACH, FREE, OPEN

7-172

INFORMIX-4GL Statement Syntax

PROMPT

PROMPT
Overview
Use the PROMPT statement to prompt the user for keyboard input, and to accept a value entered by the user.

Syntax
PROMPT display-list [ ATTRIBUTE ( attribute-list) ] FOR [ CHAR ] variable [ HELP help-number ] [ ATTRIBUTE ( attribute-list) ] [ ON KEY ( key-list) statement ... ... END PROMPT ]

Explanation
PROMPT

is a required keyword. is a list of one or more program variables or string constants, separated by commas. is a keyword to specify screen display attributes. is a list (in parentheses) of one or more screen display attributes, separated by commas. is a required keyword. is an optional keyword. is the program variable that will contain the value typed in by the user. is an optional keyword. is an integer that identifies the help message for this PROMPT statement in the help file designated in the OPTIONS statement. are optional keywords. is a list of one or more function or CTRL key designations. It can also include ESCAPE (if you have specified another key as the Accept key in the OPTIONS statement) or INTERRUPT (if you have executed a DEFER INTERRUPT statement).
INFORMIX-4GL Statement Syntax 7-173

display-list
ATTRIBUTE

(attribute-list)
FOR CHAR

variable
HELP

help-number

ON KEY

key-list

PROMPT

statement END PROMPT

is an INFORMIX-4GL statement. are keywords to terminate a PROMPT statement (required only if an ON KEY clause is used).

Notes
1. INFORMIX-4GL displays the string generated by replacing the variables in display-list with their current values on the Prompt line if an open form is displayed. The prompt occurs at the current cursor position if no form is displayed and

• It is preceded by a DISPLAY statement with no AT clause. • It is the first printing statement in the program. • The screen is cleared.
2. The PROMPT statement returns the value entered by the user in variable. For a string variable, the value returned can include spaces. 3. The use of the CHAR option causes PROMPT to accept a single character input without requiring a carriage return. 4. If INFORMIX-4GL cannot convert the value entered by the user to the data type of variable, it returns a negative error code in the global variable status and the value of variable is undetermined. 5. You can use these keys in a key-list under the stated conditions:

• Function keys. • CTRL keys (except as noted later). • ESCAPE (if you have specified another key as the Accept key in the
OPTIONS statement).

• Interrupt, if you have executed a DEFER INTERRUPT statement. (When
the user presses the Interrupt key under these conditions, INFORMIX-4GL executes the statements in the ON KEY clause and sets int_flag to nonzero.) You cannot use the following keys in a key-list:

CTRL-A, CTRL-D, CTRL-H, CTRL-L, CTRL-R, or CTRL-X since these CTRL keys are reserved for editing functions in the CONSTRUCT, INPUT, and INPUT ARRAY statements.

• Other keys like CTRL-S that may have special meaning on your implementation of UNIX. 6. INFORMIX-4GL terminates PROMPT and passes control to the statements following an ON KEY clause when the user presses a key specified in key7-174 INFORMIX-4GL Statement Syntax

PROMPT

list. In this case, the value in variable is undetermined. After completing the ON KEY clause, INFORMIX-4GL passes control to the statements following END PROMPT. 7. The notation for function keys is F1 through F36. The notation for CONTROL keys is CTRL-key, where key is any letter except A, D, H, L, R, or X. The notation for ESCAPE is ESC or ESCAPE. The notation for the Interrupt key (often CTRL-C or DEL) is INTERRUPT. 8. Do not execute PROMPT, INPUT, or INPUT ARRAY statements within the ON KEY clause of a PROMPT statement. However, you can call a function that executes one of these statements. If you include an ON KEY clause, any HELP or ATTRIBUTE specifications must appear before the ON KEY clause, not after it. 9. The first ATTRIBUTE clause applies to the display-list, while the second is in effect during input. 10. The HELP clause and the second ATTRIBUTE clause can appear in any order. 11. Neither ATTRIBUTE clause can be in effect when the terminal is in line mode. The terminal is in line mode until the first time that a screen-I/O statement is executed. It returns to line mode when you issue any DISPLAY statement that has no BY NAME, TO, or AT clause. 12. The attribute-list temporarily overrides any attributes specified in an OPTIONS or OPEN WINDOW statement. 13. These keywords can appear in the ATTRIBUTE clause:
WHITE = NORMAL YELLOW = BOLD MAGENTA = BOLD RED = BOLD CYAN = DIM GREEN = DIM BLUE = DIM BLACK = INVISIBLE REVERSE BLINK UNDERLINE

You can specify zero or one of the keywords in the left-hand columns, and from zero to three from the right-hand column (but some terminals may not support some combinations). On color terminals, NORMAL is interpreted as WHITE, BOLD as RED, DIM as BLUE, and INVISIBLE as BLACK. Do not include the equal ( = ) sign, which in this table shows the effect on monochrome terminals of keywords that specify color. These keywords cannot produce the effects suggested by their names unless the termcap or terminfo files and the physical terminals support the attribute. (See Appendix I, “Modifying termcap and terminfo.”)

INFORMIX-4GL Statement Syntax

7-175

PROMPT

Note: Some terminal entries in termcap or terminfo include the sg#1 or xmc#1 capabilities. On these terminals, the first character of display-list is replaced by a blank if you use the PROMPT statement with any display attribute. To be safe, make sure that the first character of the display-list is a blank if you specify any display attributes. 14. On UNIX systems that use terminfo files rather than termcap, INFORMIX-4GL does not support attributes that specify colors, and the only valid attribute-list keywords are REVERSE and UNDERLINE.

Example
PROMPT "Enter the Customer Number: " FOR v.cust_no ON KEY (CONTROL-E) GOTO stop_now: END PROMPT

Related Statements
DISPLAY, DISPLAY ARRAY, INPUT, INPUT ARRAY, OPTIONS

7-176

INFORMIX-4GL Statement Syntax

PUT

PUT
Overview
Use the PUT statement to store a row in the INSERT buffer for later insertion into the database table.

Syntax
PUT cursor-name [ FROM variable-list ]

Explanation
PUT

is a required keyword. is the name of a cursor that has been DECLAREd for an INSERT statement. is an optional keyword. is a list of program variables, separated by commas, corresponding to the ‘‘?’’ parameters in the PREPAREd INSERT statement associated with cursor-name.

cursor-name
FROM

variable-list

Notes
1. You can execute the PUT statement only if cursor-name has been DECLAREd for an INSERT statement and is in an open state. Such a cursor is referred to as an INSERT cursor. 2. The PUT statement puts a row in the buffer created when cursor-name was OPENed. When you flush the buffer (by executing a series of PUT statements, a CLOSE statement, or a FLUSH statement), INFORMIX-4GL inserts the buffered rows into the database table as a block. 3. INFORMIX-4GL does not create an INSERT buffer for a cursor associated with an INSERT statement that contains only constants in the VALUES clause. If you execute a PUT statement for such a cursor, INFORMIX-4GL increments a counter that keeps track of the number of rows to be inserted into the database. The database is updated only when you issue a FLUSH or CLOSE statement. 4. You close a cursor by issuing a CLOSE statement. Exiting a program without closing an insert cursor leaves the buffer unflushed. Rows inserted

INFORMIX-4GL Statement Syntax

7-177

PUT

into the buffer since the last flush are lost. You cannot rely on the end of program to close the cursor and flush the buffer. 5. The global variables status (whose value is received from SQLCA.SQLCODE) and SQLCA.SQLERRD[3] indicate the result of each PUT statement. If INFORMIX-4GL simply puts a row in the INSERT buffer, it sets status and SQLCA.SQLERRD[3] to zero. If, as the result of a PUT statement, INFORMIX-4GL successfully inserts a block of rows into the database, it sets status to zero and sets SQLCA.SQLERRD[3] to the number of rows inserted. If, as the result of a PUT statement, INFORMIX-4GL is unsuccessful in its attempt to insert an entire block of rows into the database, it sets status to a negative number (specifically, the number of the error message) and sets SQLCA.SQLERRD[3] to the number of rows successfully inserted into the database. 6. Whenever the buffer is flushed, SQLCA.SQLERRD[3] is set to the number of rows successfully inserted into the database. If an error occurs during the flushing of a buffer, the buffered rows that follow the last successfully inserted row are discarded. 7. If your database has transactions, you must issue the PUT statement within a transaction. 8. If cursor-name has been DECLAREd for a PREPAREd INSERT statement that includes ‘‘?’’ parameters, you must use the PUT statement with a FROM clause. After the FROM keyword, you can list the variable(s) containing the value(s) that INFORMIX-4GL substitutes for the ‘‘?’’ parameters in the PREPAREd INSERT statement.

Examples
DECLARE icurs CURSOR FOR INSERT INTO manufact VALUES (m_code, m_name) OPEN icurs PUT icurs PREPARE ins_stmt FROM "INSERT INTO manufact VALUES (?, ?)" DECLARE ins_curs CURSOR FOR ins_stmt OPEN ins_curs PUT ins_curs FROM m_code, m_name

Related Statements
CLOSE, DECLARE, FLUSH, OPEN, PREPARE

7-178

INFORMIX-4GL Statement Syntax

RECOVER TABLE

RECOVER TABLE
Overview
In the event of a system failure, use the RECOVER TABLE statement to restore a database table from a backup copy and an audit trail file.

Syntax
RECOVER TABLE table-name

Explanation
RECOVER TABLE

are required keywords. is the name of the table you want to recover.

table-name

Notes
1. Once you have recovered the table, use the DROP AUDIT statement to remove the contents of the audit trail file. Run the CREATE AUDIT statement to start a new audit trail file, then back up the table. See the section “Audit Trails” in Chapter 3 for more information. 2. RECOVER TABLE checks that the audit trail and table-name have consistent record numbers for rows where changes have taken place. If RECOVER TABLE finds inconsistencies, it stops restoring the table. 3. You must own table-name or have DBA status to use the RECOVER TABLE statement.

Example
The following SQL statements give a template for the recovery of a table. They assume that your audit trail began from the last backup.
{restore table from last backup} RECOVER TABLE customer DROP AUDIT FOR customer CREATE AUDIT FOR customer IN "/dev/safe" {make a backup of the recovered table} INFORMIX-4GL Statement Syntax 7-179

RECOVER TABLE

Related Statements
CREATE AUDIT, DROP AUDIT

7-180

INFORMIX-4GL Statement Syntax

RENAME COLUMN

RENAME COLUMN
Overview
Use the RENAME COLUMN statement to change the name of a column.

Syntax
RENAME COLUMN table.oldcolumn TO newcolumn

Explanation
RENAME COLUMN are required keywords.

table oldcolumn
TO

is the required name of the table containing the column whose name is to be changed. is the name of the column to be renamed. is a required keyword. is the new name to be assigned to the column. The newcolumn must satisfy the requirements for an SQL identifier, and cannot duplicate another column name in the table.

newcolumn

Notes
1. You can RENAME a column of a table only when you own the table, have DBA privilege, or have been granted ALTER permission. 2. The RENAME COLUMN statement cannot be rolled back.

Example
RENAME COLUMN customer.customer_num TO c_num

Related Statements
ALTER TABLE, CREATE TABLE, INSERT, DROP TABLE, RENAME TABLE

INFORMIX-4GL Statement Syntax

7-181

RENAME TABLE

RENAME TABLE
Overview
Use the RENAME TABLE statement to change the name of a table in the system catalogs.

Syntax
RENAME TABLE oldname TO newname

Explanation
RENAME TABLE

are required keywords. is the current name of the table to be renamed. is a required keyword. is the new name that you want to assign to the table.

oldname
TO

newname

Notes
1. In a non-MODE ANSI database, the newname identifier must be unique among tables and synonyms. In a MODE ANSI database, it must be unique among tables and synonyms that you own. 2. You can RENAME a table only when you own the table, have DBA privilege, or have been granted ALTER permission on the table. 3. You can specify owner.oldname in a RENAME TABLE statement, but a compile-time error results if you specify owner.newname. 4. The RENAME TABLE statement cannot be rolled back.

7-182

INFORMIX-4GL Statement Syntax

RENAME TABLE

Example
This example moves the quantity column to the third place:
CREATE TABLE newtab (item_num order_num quantity stock_num manu_code total_price ) SMALLINT, INTEGER, SMALLINT, SMALLINT, CHAR(4), MONEY(8)

INSERT INTO newtab SELECT item_num, order_num, quantity, stock_num, manu_code, total_price FROM items DROP TABLE items RENAME TABLE newtab TO items

Related Statements
ALTER TABLE, CREATE TABLE, INSERT, DROP TABLE, RENAME COLUMN

INFORMIX-4GL Statement Syntax

7-183

REPORT

REPORT
Overview
Use the REPORT routine to provide the format specifications for a report.

Syntax
REPORT report-name ( variable-list ) [ DEFINE-statement ] ... [ OUTPUT output-statement ...] [ ORDER [ EXTERNAL ] BY sort-list ] FORMAT format-statement ... 4gl-statement ... END REPORT

Explanation
REPORT

is a required keyword.

report-name is an INFORMIX-4GL identifier. variable-list is a list of zero or more variables, separated by commas. DEFINE-statement is a DEFINE statement giving the data type for the variables in variable-list. OUTPUT is an optional keyword. output-statement is an output statement described in Chapter 5. ORDER BY are optional keywords. EXTERNAL is an optional keyword. sort-list is a list of one or more variables from those in variable-list. FORMAT is a required keyword. format-statement is a FORMAT statement described in Chapter 5. 4gl-statement is an arbitrary INFORMIX-4GL statement. END REPORT are required keywords that terminate the REPORT statement.

7-184

INFORMIX-4GL Statement Syntax

REPORT

Notes
1. If variable-list contains the name of a record, you must DEFINE the record in DEFINE-statement. Do not append the .* to the name of the record in variable-list. 2. See Chapter 5 for a discussion of the OUTPUT, ORDER BY, and FORMAT sections of the REPORT routine. 3. If INFORMIX-4GL statements occur in the control blocks of the FORMAT section, they are executed during the report-printing phase. If the data is sorted outside the report, report printing takes place with each OUTPUT TO REPORT statement. This is called a one-pass report. If the data is sorted inside the report, report printing takes place with the FINISH REPORT statement. This is called a two-pass report. If 4GL statements occur in the OUTPUT TO REPORT loop as well as in the report, INFORMIX-4GL alternately executes the 4GL statements in the OUTPUT TO REPORT loop and the 4GL statements in the report during a one-pass report. In contrast, INFORMIX-4GL repeatedly executes all the 4GL statements in the OUTPUT TO REPORT loop before executing the 4GL statements in the report during a two-pass report.

Example
The simplest report displays the output of a query:
DECLARE simp_curs CURSOR FOR SELECT * FROM CUSTOMER START REPORT simple FOREACH simp_curs INTO cust.* OUTPUT TO REPORT simple(cust.*) END FOREACH FINISH REPORT simple ... REPORT simple (x) DEFINE x RECORD LIKE customer.* FORMAT EVERY ROW END REPORT

Related Statements
FINISH REPORT, OUTPUT TO REPORT, START REPORT

INFORMIX-4GL Statement Syntax

7-185

RETURN

RETURN
Overview
Use the RETURN statement to leave a FUNCTION routine and to return values to the calling routine.

Syntax
RETURN [expr-list]

Explanation
RETURN

is a required keyword. is an optional list of one or more expressions, separated by commas.

expr-list

Notes
1. The RETURN statement can occur only within a FUNCTION routine and directs INFORMIX-4GL to exit the function and to return to the calling routine (MAIN, FUNCTION, or REPORT). 2. The expressions in expr-list must match in number and type the argument list in the RETURNING clause of the CALL statement.

Related Statement
FUNCTION

7-186

INFORMIX-4GL Statement Syntax

REVOKE

REVOKE
Overview
Use the REVOKE statement to remove another user’s access privileges for a database or table.

Syntax
REVOKE { tab-privilege ON table-name | db-privilege } FROM { PUBLIC | user-list}

Explanation
REVOKE

is a required keyword. is one or more of the following table-level access privileges, separated by commas: ALTER Adds or deletes columns or modifies data types of columns DELETE Deletes rows INDEX Creates indexes INSERT Inserts rows SELECT Retrieves data UPDATE Changes column values ALL [PRIVILEGES] All of the above is a required keyword. is the name of the table for which you are revoking access privileges. is one of the following database-level access types: CONNECT allows access to database tables without permission to create permanent tables and indexes. RESOURCE allows access to database tables with permission to create permanent tables and indexes. DBA allows full database administrator privileges. is a required keyword.
INFORMIX-4GL Statement Syntax 7-187

tab-privilege

ON

table-name db-privilege

FROM

REVOKE

PUBLIC

is the keyword to revoke access privilege from all users. is a list of login names for the users whose access privilege you are revoking. You can enter one login name or a series of login names, separated by commas.

user-list

Notes
1. You cannot roll back the REVOKE statement. 2. You can revoke database-level access privileges only if you have DBA status. 3. You can revoke only those table-level access privileges that you have granted to another user. 4. You cannot revoke privileges from yourself. 5. Although you can grant UPDATE and SELECT privileges for specific columns, you cannot revoke these privileges column by column. If you revoke UPDATE or SELECT privileges from a user, INFORMIX-4GL automatically revokes all UPDATE and SELECT privileges that you have ever granted to that user for table-name. You can then re-grant privileges for specific columns. 6. Only a DBA recipient can revoke the DBA privilege from another recipient. If the database creator grants DBA privileges to another user, that person can revoke the DBA privilege from the database creator. 7. If you revoke the DBA or RESOURCE privilege from one or more users, they are left with the CONNECT privilege. To revoke all database privileges from users with DBA or RESOURCE status, you must revoke CONNECT as well as DBA or RESOURCE.

Examples
REVOKE ALL ON orders FROM PUBLIC REVOKE DELETE, UPDATE ON customer FROM jeff, judy REVOKE CONNECT FROM enid, felix

Related Statement
GRANT

7-188

INFORMIX-4GL Statement Syntax

ROLLBACK WORK

ROLLBACK WORK
Overview
Use the ROLLBACK WORK statement to undo all modifications made to the database during the current transaction.

Syntax
ROLLBACK WORK

Explanation
ROLLBACK WORK

are required keywords.

Note
1. If you use the ROLLBACK WORK statement in a routine that is called by a WHENEVER statement, be sure to specify WHENEVER ERROR CONTINUE and WHENEVER WARNING CONTINUE before the ROLLBACK WORK statement. This will prevent the program from looping if the ROLLBACK WORK statement fails with an error or warning. 2. See the “Transactions” section in Chapter 3 for more information about transactions and the ROLLBACK WORK statement. 3. The ROLLBACK WORK statement releases all row and table locks. 4. The ROLLBACK WORK statement closes all open cursors except those DECLAREd WITH HOLD, although using it for this purpose is not recommended.

Related Statements
BEGIN WORK, COMMIT WORK

INFORMIX-4GL Statement Syntax

7-189

ROLLFORWARD DATABASE

ROLLFORWARD DATABASE
Overview
Use the ROLLFORWARD DATABASE statement to cause INFORMIX-4GL to apply the transactions registered in the transaction log file to a backup copy of your database, recovering all completed transactions.

Syntax
ROLLFORWARD DATABASE database-name

Explanation
ROLLFORWARD are required keywords. DATABASE database-name is the name of a database.

Notes
1. Immediately after you roll forward a database, it is in EXCLUSIVE mode, with no transactions. After the database is closed and reopened, it becomes accessible to other users, and transactions can resume. 2. See the section “Transactions” in Chapter 3 for more information.

Related Statements
BEGIN WORK, COMMIT WORK, START DATABASE, ROLLBACK WORK

7-190

INFORMIX-4GL Statement Syntax

RUN

RUN
Overview
Use the RUN statement to execute a system program.

Syntax
RUN command-line [ RETURNING integer-variable | WITHOUT WAITING ]

Explanation
is a required keyword. command-line is an expression that evaluates to a command line for your operating system. In particular, it may be a character string enclosed in quotation marks. RETURNING is an optional keyword. integer-variable is an INTEGER-type program variable that will receive the value returned by the program executed by the RUN statement. WITHOUT WAITING are optional keywords.
RUN

Note
RUN spawns a child process described by command-line. The WITHOUT WAITING option instructs INFORMIX-4GL to continue immediately to the next 4GL statement, while the RETURNING option instructs INFORMIX-4GL to await the return value before continuing to the next 4GL statement. If neither optional clause is present, INFORMIX-4GL waits until the child process is completed (and ignores the return code) before continuing to the next 4GL

statement.

Examples
RUN "date_script" RETURNING error_val RUN "isql -qr myscript" RUN charval[i]

INFORMIX-4GL Statement Syntax

7-191

SCROLL

SCROLL
Overview
Use the SCROLL statement to move rows of a screen record through a screen array.

Syntax
SCROLL { field-list | screen-record. * } [ , . . . ] { UP | DOWN } [ BY integer ]

Explanation
SCROLL

is a required keyword. is a list of one or more screen field names, separated by commas. is the name of a screen record. is an optional keyword indicating that the data on the screen should move upwards. is an optional keyword indicating that the data on the screen should move downwards. is an optional keyword. is an INTEGER constant or variable.

field-list screen-record
UP DOWN BY

integer

Notes
1. The BY clause determines the number of lines upward or downward that the data will move. The default is 1. 2. It is the responsibility of the programmer to keep track of what data is left on the screen.

Example
SCROLL sc_item UP BY 2

Related Statements
DISPLAY ARRAY, INPUT ARRAY

7-192

INFORMIX-4GL Statement Syntax

SELECT

SELECT
Overview
Use the SELECT statement to query the current database. The SELECT statement can include up to eight clauses. Only the SELECT clause and the FROM clause are required.

Syntax
SELECT clause [ INTO clause ] FROM clause [ WHERE clause ] [ GROUP BY clause ] [ HAVING clause ] [ ORDER BY clause ] [ INTO TEMP clause ]

See “The SELECT Statement” section later in this chapter for detailed descriptions of these clauses.

INFORMIX-4GL Statement Syntax

7-193

SET EXPLAIN

SET EXPLAIN
Overview
Use the SET EXPLAIN statement to record how the query processor is accessing the database when executing a query.

Syntax
SET EXPLAIN { ON | OFF }

Explanation
SET EXPLAIN ON OFF

are required keywords. is a keyword to enable the EXPLAIN facility. is a keyword to disable the EXPLAIN facility. OFF is the default.

Notes
1. When you issue SET EXPLAIN ON, the access procedures of all subsequent queries are stored in the file sqexplain.out in your current directory. If sqexplain.out already exists, subsequent output is appended to it. SET EXPLAIN ON remains in effect until you issue SET EXPLAIN OFF, or the program ends. 2. SET EXPLAIN estimates the cost in CPU resources (a weighted sum of disk accesses and total rows processed), indicates the order of table access, and estimates the number of rows returned. For each table, SET EXPLAIN identifies the type of access and the column(s) that serves as a filter, including whether the filtering is through an index. The following table-access types are available:
SEQUENTIAL SCAN INDEX PATH AUTOINDEX PATH

reads rows in sequence. scans one or more indexes. creates a temporary index.

3. The name of the owner precedes each table name in the output file.

7-194

INFORMIX-4GL Statement Syntax

SET EXPLAIN

Examples
The following example shows an sqexplain.out output file for a simple query and for a complex query from one table.
QUERY: -----select fname, lname, company from customer; Estimated Cost: 4 Estimated # of Rows Returned: 18 1) joe.customer: SEQUENTIAL SCAN

QUERY: -----select fname, lname, company from customer where company matches "Sport*" and customer_num between 110 and 115 order by lname; Estimated Cost: 3 Estimated # of Rows Returned: 1 Temporary Files Required For: Order By 1) joe.customer: INDEX PATH Filters: joe.customer.company MATCHES "Sport*" (1) Index Keys: customer_num Lower Index Filter: joe.customer.customer_num >= 110 Upper Index Filter: joe.customer.customer_num <= 115

INFORMIX-4GL Statement Syntax

7-195

SET EXPLAIN

The next example is from an sqexplain.out output file for a multiple-table query.
QUERY: -----select * from customer, orders, items where customer.customer_num = orders.customer_num and orders.order_num = items.order_num; Estimated Cost: 110 Estimated # of Rows Returned: 41 1) joe.orders: SEQUENTIAL SCAN 2) joe.customer: INDEX PATH (1) Index Keys: customer_num Lower Index Filter: joe.customer.customer_num = joe.orders.customer_num 3) joe.items: INDEX PATH (1) Index Keys: order_num Lower Index Filter: joe.items.order_num = joe.orders.order_num

Related Statements
ALTER INDEX, CREATE INDEX, SELECT, UPDATE STATISTICS

Note: Additional statistics are available for query processing when you use INFORMIX-OnLine as the database engine. As a result, estimates for the cost and the number of rows returned may be more precise under INFORMIX-OnLine.

7-196

INFORMIX-4GL Statement Syntax

SET LOCK MODE ( O )

SET LOCK MODE ( O )
Overview
Use the SET LOCK MODE statement to determine whether subsequent INFORMIX-4GL calls wait for a locked row to become unlocked.

Syntax
SET LOCK MODE TO [ NOT ] WAIT

Explanation
SET LOCK MODE TO NOT WAIT

are required keywords. is a required keyword. is an optional keyword. is a required keyword.

Notes
1. The TO NOT WAIT option causes INFORMIX-4GL to return an error if a statement attempts to alter or delete a row (or to SELECT a row FOR UPDATE) that another process has locked. This is the default situation; that is, if you have not issued a SET LOCK MODE statement previously. The NOT option is relevant, therefore, only when you have previously executed SET LOCK MODE TO WAIT and want to return to the default state. 2. The TO WAIT option causes INFORMIX-4GL to wait on an attempt to alter or delete a row (or to SELECT a row FOR UPDATE) that another process has locked until the locked row becomes unlocked. 3. Use the SET LOCK MODE TO WAIT statement with extreme caution. If the locking process fails and does not remove the lock, your statement could wait indefinitely. 4. This feature is available only on systems that have record-level locking and applies only to row-level locking. Any attempt by another user to access a row in a table locked IN EXCLUSIVE MODE produces an error. 5. You can use the SET LOCK MODE statement only on systems that support kernel locking. An error is generated if you use the SET LOCK MODE statement with a system that does not support kernel locking.
INFORMIX-4GL Statement Syntax 7-197

SET LOCK MODE ( O )

Related Statement
LOCK TABLE

7-198

INFORMIX-4GL Statement Syntax

SLEEP

SLEEP
Overview
Use the SLEEP statement to cause the program to suspend operation for a period of time.

Syntax
SLEEP integer-expr

Explanation
SLEEP

is a required keyword. is an expression that evaluates to INTEGER type.

integer-expr

Note
The SLEEP statement causes the program to suspend operation for integerexpr seconds.

Example
SLEEP 4

INFORMIX-4GL Statement Syntax

7-199

START DATABASE

START DATABASE
Overview
Use the START DATABASE statement to start a new transaction log file.

Syntax
START DATABASE database-name WITH LOG IN "pathname" [ MODE ANSI ]

Explanation
START DATABASE are required keywords. database-name
WITH LOG IN

is the name of a database. are required keywords. is the full pathname, enclosed in quotation ( " ) marks, of the transaction log file. are optional keywords to convert the database to MODE ANSI.

pathname
MODE ANSI

Notes
1. The START DATABASE statement can perform these tasks:

• Change the name of your transaction log file. • Start recording transactions in a database that was created without
transactions.

• Start a database that supports ANSI standards.
2. The START DATABASE statement opens the database in EXCLUSIVE mode. No users can access the database until you issue a CLOSE DATABASE statement. 3. After a database is started as MODE ANSI, you receive an error if you do not use the owner.object naming convention to refer to an object owned by another user. You must modify existing queries that reference a table, view, or synonym owned by another user to include the owner prefix. See the section “Owner Naming” in Chapter 3 of this manual. 4. Do not use the BEGIN WORK statement in programs that access a MODE ANSI database. Since transactions are implicit in MODE ANSI, the BEGIN WORK statement is not needed.
7-200 INFORMIX-4GL Statement Syntax

START DATABASE

5. Singleton transactions do not exist in MODE ANSI. For a singleton statement, you must issue a COMMIT WORK statement to commit a transaction, or a ROLLBACK WORK statement to roll the database back to the last COMMIT WORK or ROLLBACK WORK statement. 6. See the section “Transactions” in Chapter 3 for more information on START DATABASE. See also the discussion of CREATE DATABASE earlier in this chapter for more information on MODE ANSI databases. 7. You can determine the type of database that a user selects by checking the return code from a DATABASE statement in the SQLCA.SQLAWARN character string. See the section “SQLCA Record” in Chapter 3 for more information. 8. You cannot remove MODE ANSI from a database. Once started as such, a database remains MODE ANSI.

Example
START DATABASE stores WITH LOG IN "/u/myname/stores.log" MODE ANSI

Related Statements
BEGIN WORK, COMMIT WORK, CREATE DATABASE, ROLLBACK WORK, ROLLFORWARD DATABASE

INFORMIX-4GL Statement Syntax

7-201

START REPORT

START REPORT
Overview
Use the START REPORT statement to begin processing a report.

Syntax
START REPORT report-name [ TO { filename | PRINTER | PIPE program } ]

Explanation
START REPORT are required keywords.

report-name
TO

is the identifier of a report. is an optional keyword. is either a CHAR type variable or a quoted string constant containing the name of a system file. is an optional keyword. is an optional keyword. is either a CHAR variable or a string constant containing the command line for a system program.

filename
PRINTER PIPE

program

Notes
1. Usually, you will execute the START REPORT statement just before a loop in which you process the report data using the OUTPUT TO REPORT statement. 2. If you use the TO clause, INFORMIX-4GL ignores any REPORT TO statement in the OUTPUT section of report-name. 3. If you indicate filename, INFORMIX-4GL puts the report output there. 4. If you use the TO PRINTER option, INFORMIX-4GL sends the report output to your printer. The default printer command is lp or lpr; be sure to check with your system administrator. You can change the default by setting the DBPRINT environment variable. (See Appendix C.) 5. Use the TO PIPE option to pipe report output to program.

Related Statements
FINISH REPORT, OUTPUT TO REPORT, REPORT

7-202

INFORMIX-4GL Statement Syntax

UNLOAD

UNLOAD
Overview
Use the UNLOAD statement to write the data from a table to an ASCII file.

Syntax
UNLOAD TO "pathname" [ DELIMITER "char" ] SELECT-statement

Explanation
UNLOAD TO

are required keywords. is a quoted string or a character variable that evaluates to the pathname of the file in which to store the database table. is an optional keyword to indicate that the following char separates data fields in the file. is a single character that serves as the delimiter between fields. The char must appear in quotation marks. is a SELECT statement that retrieves the data to be written to a file.

pathname

DELIMITER

char
SELECT-statement

Notes
1. The data from each column in each row are separated from the data in the next column by the delimiter. INFORMIX-4GL uses as a delimiter the character included in the DELIMITER clause, if one is provided. If no DELIMITER clause appears in the statement, INFORMIX-4GL checks the setting in the DBDELIMITER environment variable, if it exists. The default delimiter is the vertical bar ( | = ASCII 124). If character data contains a delimiter character, INFORMIX-4GL automatically escapes it with a backslash to prevent interpretation as a special character. (Backslashes are automatically stripped when the field is LOADed.) 2. As in a DECLARE statement for a SELECT cursor, the SELECT-statement can be either an unquoted SELECT statement, or the name of a string variable that contains a SELECT statement. 3. NULL columns have no characters between delimiters.
INFORMIX-4GL Statement Syntax 7-203

UNLOAD

4. Trailing blanks in CHARACTER data are clipped. Number data types have no leading blanks. 5. An INTEGER or SMALLINT zero is represented as 0 ; FLOAT, SMALLFLOAT, DECIMAL, and MONEY zeros are represented as 0.00. 6. MONEY values have no leading currency symbol. 7. DATE values are represented as mm/dd/yyyy, where mm is the month (January = 1, and so on), dd is the day, and yyyy is the year. 8. DATETIME and INTERVAL items are written in character form, showing only their field digits and delimiters. No type specification or qualifiers are output. INFORMIX-4GL uses the following pattern: yyyy-mm-dd hh:mi:ss.fff, omitting fields that are not part of the data. 9. You must have SELECT permission on all columns in the select-list of the SELECT statement to use the UNLOAD statement. 10. You cannot PREPARE an UNLOAD statement. 11. When you execute an UNLOAD statement, INFORMIX-4GL sets status to zero to indicate success, or to an error number to indicate failure. If an error occurs, the SQLCODE and SQLERRD[2] error codes are set, as described in Chapter 3. In any case, the value of SQLERRD[3] is set to the number of rows that UNLOAD copied to the file.

Example
UNLOAD TO "cust.out" DELIMITER ";" SELECT fname, lname, company, city FROM customer

Related Statements
LOAD, SELECT

Note: INFORMIX-OnLine supports additional data types. Refer to the INFORMIX-OnLine Programmer’s Manual for more information.

7-204

INFORMIX-4GL Statement Syntax

UNLOCK TABLE

UNLOCK TABLE
Overview
Use the UNLOCK TABLE statement to unlock a table that you previously locked with the LOCK TABLE statement.

Syntax
UNLOCK TABLE table-name

Explanation
UNLOCK TABLE

are required keywords. is the name of the table you want to unlock.

table-name

Note
If the database has transactions, the UNLOCK TABLE statement can not be used and generates an error. All locks placed on the table are released when the COMMIT WORK or ROLLBACK WORK statement is processed.

Related Statement
LOCK TABLE

INFORMIX-4GL Statement Syntax

7-205

UPDATE

UPDATE
Overview
Use the UPDATE statement to change the values in one or more columns of one or more rows in a table.

Syntax
UPDATE table-name SET { column-name = expr [ , . . . ] | { ( column-list ) | [ table-name. ] * } = { ( expr-list) | record-name.* } } [ WHERE { condition | CURRENT OF cursor-name } ]

Explanation
UPDATE

is a required keyword. is the name of the table that contains the row(s) that you want to update. is a required keyword. is the name of a column you want to update. is any combination of column names, constants, program variables, arithmetic operators, or an SQL subquery that returns a single row of one value. is a list of the names of columns to be updated. refers to all columns in table-name. (You can substitute table-name.* if you prefer.) is a list of expressions that represent values corresponding to the columns in column-list or the columns represented by the asterisk notation. In expr-list, you can specify multiple values using a record name with the asterisk ( * ) or THRU notation. The list can also include an SQL subquery that returns a single row of multiple values. is the name of a program variable of type RECORD. is an optional keyword. is a condition for a standard WHERE clause made up of a search condition that compares the values in one column to the values in another column, to a program variable, or to a constant. (For further information, refer to the explanation of

table-name
SET

column-name expr

column-list * expr-list

record-name
WHERE

condition

7-206

INFORMIX-4GL Statement Syntax

UPDATE

WHERE clauses in the section “The SELECT Statement” at the end of this chapter.) CURRENT OF

are keywords. is the SQL identifier of a previously DECLAREd cursor.

cursor-name

Notes
1. The expr can be a SELECT statement in parentheses that adheres to standard rules for subqueries. The SELECT statement can return no more than one value except when included in an expr-list. 2. You cannot use a SELECT statement that retrieves data from table-name. 3. The number of column names included in the column-list must equal the number of values produced in the expr-list. 4. Although the value returned by expr does not have to be of the same data type as column-name, it must be compatible. You can put only CHAR data into CHAR columns, and only numeric or character representations of numeric data into number columns. 5. If you use the CURRENT OF option in the WHERE clause, INFORMIX-4GL updates the current row of the active set and leaves the cursor on the same row. 6. If you do not specify any columns in the FOR UPDATE clause of a DECLARE statement, you can update any column in a subsequent UPDATE WHERE CURRENT OF statement. If you do specify one or more columns in the FOR UPDATE clause, you can update only those columns in a subsequent UPDATE WHERE CURRENT OF statement. When you specify the column names in the FOR UPDATE clause, INFORMIX-4GL can usually perform the updates more quickly. 7. SERIAL columns cannot be updated. If you want to use the [table-name].* notation and table-name contains a SERIAL column, you can only execute the following form of the UPDATE statement:
UPDATE table-name SET [table-name.]* = record-name.*

When INFORMIX-4GL executes this form of the UPDATE statement, it automatically skips any SERIAL column and the corresponding value in the expression list produced by record-name.*. 8. When you create a database with transactions that is not MODE ANSI, each UPDATE statement that you execute is treated as a single transaction, even if you do not use the BEGIN WORK and COMMIT WORK or ROLLBACK WORK statements.
INFORMIX-4GL Statement Syntax 7-207

UPDATE

9. Each row affected by an UPDATE statement within a transaction is locked for the duration of the transaction; therefore, a single UPDATE statement that affects a large number of rows locks those rows until the entire operation is completed. If the number of rows affected is very large, you can approach the limit that your operating system places on the maximum number of simultaneous locks. If this occurs, you may want to reduce the scope of the UPDATE statement, or lock the entire table before executing the statement. See the section “Locking” in Chapter 3 for a more detailed description of table-level and row-level locking in INFORMIX-4GL. 10. You cannot perform an UPDATE through a DECLAREd cursor that includes aggregate functions. The cursor can only specify simple column names. 11. The UNIQUE keyword cannot appear in a subquery within an UPDATE statement. Caution: If INFORMIX-4GL encounters an error while performing an UPDATE, the operation stops. Unless you have created the database with transactions, all database changes made up to the point where the error is encountered remain, but subsequent rows are not updated. A data conversion error is an example of an error that stops an UPDATE operation. Common data conversion errors include attempting to insert numeric data into a CHAR column, or attempting to insert numeric values that exceed the limits of the data type of the column. For example, you cannot insert the integer 123456 into a SMALLINT column. If you omit the WHERE clause, INFORMIX-4GL assumes that you want to update every row in the table.

7-208

INFORMIX-4GL Statement Syntax

UPDATE

Examples
UPDATE stock SET unit_price = unit_price * 1.04 WHERE manu_code = "HRO"

UPDATE customer SET * = p_customer.* WHERE customer_num = p_customer.customer_num

UPDATE customer SET (fname, company, address2) = ("Marie", "Marie’s Sports", "P. O. Box 3621") WHERE customer_num = 103

UPDATE table1 SET (col1, col2, col3) = ((select min (ship_charge), max (ship_charge) from orders), "07/01/1986") WHERE col4 = 1001

Related Statements
SELECT, DELETE, INSERT

INFORMIX-4GL Statement Syntax

7-209

UPDATE STATISTICS

UPDATE STATISTICS
Overview
Use the UPDATE STATISTICS statement to cause the number of rows in a table to be recorded in the systables catalog.

Syntax
UPDATE STATISTICS [ FOR TABLE table-name ]

Explanation
UPDATE STATISTICS are required keywords. FOR TABLE

are optional keywords you use when you want to update the statistics for a single table. is the name of the table for which you want the statistics updated.

table-name

Notes
1. UPDATE STATISTICS is effective only when there is a current database. 2. INFORMIX-4GL uses the data generated by UPDATE STATISTICS to optimize searching strategy. When you have modified a table extensively, use UPDATE STATISTICS to improve the efficiency of queries. 3. INFORMIX-4GL does not update the statistics unless you execute the UPDATE STATISTICS statement. 4. If you omit the FOR TABLE clause, UPDATE STATISTICS updates all the tables in the current database.

Related Statement
SET EXPLAIN INFORMIX-OnLine supports additional functionality. Refer to the INFORMIXOnLine Programmer’s Manual for more information.

7-210

INFORMIX-4GL Statement Syntax

VALIDATE

VALIDATE
Overview
Use the VALIDATE statement to determine whether values in a list of variables conform to the allowed ranges of values in syscolval for a corresponding list of columns.

Syntax
VALIDATE variable-list LIKE column-list

Explanation
VALIDATE

is a required keyword. is a list of one or more variables, separated by commas. is a required keyword. is a list of column names, preceded by table names and separated by commas.

variable-list
LIKE

column-list

Notes
1. There must be as many entries in column-list as there are variables in variable-list. 2. You must use a table-name prefix to designate the column names. 3. In a MODE ANSI database, the name of a table is qualified by the owner of the table (owner. table-name). You must specify owner when you refer to a table owned by another user. The use of the prefix owner is optional in a non-MODE ANSI database. INFORMIX-4GL does check the accuracy of owner, however, if you include it in a statement. See the section “Owner Naming” in Chapter 3 for more information. 4. You can use the upscol utility to create and update the values in syscolval. (See the discussion of “The upscol Utility” in Appendix E.) 5. If the current database is not MODE ANSI, the upscol utility creates a single syscolval table that specifies acceptable values or ranges of values for any or all columns in the database. The VALIDATE statement compares variable-list with the limitations specified in this table.

INFORMIX-4GL Statement Syntax

7-211

VALIDATE

6. In a MODE ANSI database, each user of upscol creates an individual owner. syscolval table. When it executes the VALIDATE statement, INFORMIX-4GL compares each component of variable-list to the syscolval table that belongs to the owner of the corresponding table-name.column-name in column-list. (You can omit the owner prefix from table-name if the user who compiled the current 4GL program is the owner of table-name.) If the owner. syscolval table does not exist, the VALIDATE statement takes no action. 7. If the values of the components of variable-list do not conform entirely with the INCLUDE values of syscolval, INFORMIX-4GL sets the status variable to a negative value. You must test the variables individually to detect the non-conforming component. 8. The column-list cannot include DATETIME or INTERVAL columns. 9. You can use the * notation in variable-list and column-list.

Examples
VALIDATE var1, var2, var3 LIKE tab1.col1, tab1.col2, tab1.col3 VALIDATE p_customer.* LIKE customer.*

Related Statement
INITIALIZE

7-212

INFORMIX-4GL Statement Syntax

WHENEVER

WHENEVER
Overview
Use the WHENEVER statement to trap errors and other exceptional conditions that result during the execution of other 4GL statements.

Syntax
WHENEVER { ERROR | WARNING | NOT FOUND } {GOTO [ : ] label | CALL function-name | CONTINUE | STOP }

Explanation
WHENEVER ERROR

is a required keyword. is a keyword to test for an error (status < 0) after each 4GL statement. Its synonym SQLERROR conforms to the ANSI standard for SQL syntax. is a keyword to test for a warning (SQLAWARN[1] is set to W) after each 4GL statement. Its synonym is SQLWARNING. are keywords to test whether a FETCH is attempted beyond the first or last row in the active set, or if no more rows satisfy the current SELECT statement (status=100). is an optional keyword. Its synonym GO TO conforms to the ANSI standard for SQL syntax. is an optional prefix to label, and conforms to the ANSI standard for SQL syntax. is a statement label to which program control transfers when the specified exceptional condition occurs. is an optional keyword. is the name of a function to which program control transfers when the exceptional condition occurs. is an optional keyword, instructing INFORMIX-4GL to take no action. You can use this option to turn off a previously specified option. is an optional keyword, instructing INFORMIX-4GL to exit from the program immediately.

WARNING NOT FOUND

GOTO

: label
CALL

function-name
CONTINUE

STOP

INFORMIX-4GL Statement Syntax

7-213

WHENEVER

Notes
1. The WHENEVER statement is shorthand for putting an IF statement after every SQL statement and form-related INFORMIX-4GL statement, and testing for an error, warning, or NOT FOUND condition. 2. In the default situation, INFORMIX-4GL tests for errors (not warnings) after every INFORMIX-4GL statement. The 4GL compiler sets the declared database (that is, the database specified in the DATABASE statement that precedes the MAIN program block or the first FUNCTION or REPORT routine of the module) as the current database and determines whether it is MODE ANSI. If (at compile time) the database is MODE ANSI, the default for WHENEVER ERROR is CONTINUE. Otherwise, the default is STOP. No DATABASE or START DATABASE statement in a function has any effect on the WHENEVER ERROR default. 3. A program can include several WHENEVER statements. If they refer to the same exception condition (ERROR, WARNING, or NOT FOUND), the last one encountered takes precedence. 4. The scope of a WHENEVER statement is the file in which it occurs, and from its position in the file to the next WHENEVER statement for the same exception condition in the same file. The scope extends to the end of the file, if you do not specify more WHENEVER statements for the same exception condition. 5. INFORMIX-4GL provides useful information (like source-file line numbers where an error has occurred) when it terminates a program because of an error. You may want to allow errors to occur during program development and insert trapping at a later stage. 6. If the NOT FOUND condition (status=100) is returned, the open cursor is automatically closed. 7. The label or :label specified after the GOTO or GO TO keywords must be in the same routine (that is, the same FUNCTION, REPORT, or MAIN program block) as the WHENEVER statement. 8. Some errors cannot be trapped by the WHENEVER ERROR statement. Certain errors always terminate the program, and others result in action by INFORMIX-4GL prior to the action specified by WHENEVER. (If you also have the INFORMIX-4GL Interactive Debugger, however, you can examine the current execution stack and the values of program variables after any error that is not followed by a system crash.) 9. While both NOT FOUND and NOTFOUND indicate the same condition, they cannot be used interchangeably. Use NOTFOUND (a single word)
7-214 INFORMIX-4GL Statement Syntax

WHENEVER

with status, and use NOT FOUND (two words) with the WHENEVER statement.

Examples
The following statement executes a function called error_recovery if an error condition is detected:
WHENEVER ERROR CALL error_recovery

The next statement terminates program execution if a warning is issued:
WHENEVER WARNING STOP

In the following program fragment, the WHENEVER statement transfers control, after a NOT FOUND condition, to the statement whose label is ‘‘missing:’’ in the same routine. (The use of keywords and colons here conforms to the ANSI standard for SQL syntax.)
MAIN WHENEVER NOT FOUND GO TO :missing . . . LABEL missing: DISPLAY "No row was retrieved from the database." AT 12,1 . . . END MAIN

Related Statements
CALL, DEFER, FOREACH, GOTO, IF, LABEL

INFORMIX-4GL Statement Syntax

7-215

WHILE

WHILE
Overview
Use the WHILE statement to execute a group of statements while a condition is TRUE.

Syntax
WHILE Boolean-expr statement ... [ EXIT WHILE ] ... [ CONTINUE WHILE ] ... END WHILE

Explanation
WHILE

is a required keyword. is an expression that can be either true or false. is an INFORMIX-4GL statement (including another WHILE statement). is an optional statement. is an optional statement. are required keywords that terminate a WHILE statement.

Boolean-expr statement
EXIT WHILE CONTINUE WHILE END WHILE

Notes
1. The CONTINUE WHILE statement interrupts the sequence and causes the program control to return to the top of the sequence and to test the Boolean-expr. 2. The EXIT WHILE statement interrupts the sequence and causes the program control to jump to the first statement following the END WHILE keywords. 3. If Boolean-expr is FALSE on entry to the WHILE statement, program control passes directly to the statement following END WHILE.

7-216

INFORMIX-4GL Statement Syntax

WHILE

Related Statements
CONTINUE, EXIT, FOR

INFORMIX-4GL Statement Syntax

7-217

The SELECT Statement

The SELECT Statement
Overview
Use the SELECT statement to query the current database. The SELECT statement can include the following eight clauses. Of these, only the SELECT clause and the FROM clause are required. If the INTO clause is present, it must precede the FROM clause.

Syntax
SELECT clause [ INTO clause ] FROM clause [ WHERE clause ] [ GROUP BY clause ] [ HAVING clause ] [ ORDER BY clause ] [ INTO TEMP clause ]

These clauses have the following syntax:
SELECT [ ALL | DISTINCT | UNIQUE ] select-list INTO variable-list FROM { table-name [ table-alias ] | OUTER table-name [ table-alias ] | OUTER ( table-expr ) } [ , . . . ] WHERE condition

A condition is a collection of one or more search conditions connected by the logical operators AND, OR, or NOT. A search condition can be any of the following three types: 1. Comparison condition a. expr rel-op expr b. expr [ NOT ] BETWEEN expr AND expr c. expr [ NOT ] IN ( value-list ) d. column-name [ NOT ] LIKE "string" [ ESCAPE "esc-char" ] e. column-name [ NOT ] MATCHES "string" [ ESCAPE "esc-char" ] f. column-name IS [ NOT ] NULL 2. Join condition (a comparison condition among columns of the joined tables)

7-218

INFORMIX-4GL Statement Syntax

The SELECT Statement

3. Condition with subquery a. expr rel-op { ALL | ANY | SOME } ( SELECT-statement ) b. expr [ NOT ] IN ( SELECT-statement ) c. [ NOT ] EXISTS ( SELECT-statement )
GROUP BY column-list HAVING condition ORDER BY column-name [ ASC | DESC ] [ , . . . ] INTO TEMP table-name

Explanation
The following pages explain each of the syntax elements. A few basic concepts are defined here. 1. An expression consists of a column name, a program variable, a constant, or any combination of these connected by the following arithmetic operators:
Operator + * / Operation addition subtraction multiplication division

Note: Unlike INFORMIX-4GL statements, SQL statements cannot contain expressions that use the exponentiation (**) or modulus ( mod ) operators. The result of the operation must make sense. For example, you cannot divide 16 by Jones. Column names in expressions must have an ‘‘at sign’’ ( @ ) in front of them if there is danger of confusion with program variables that have the same identifier.
SQL has three functions that you can use wherever a constant can be used. TODAY always returns the system date. CURRENT returns the system date and the time of day. USER returns a string containing the login name of

the current user. The CURRENT function is described later in this chapter. The TODAY and USER functions are described in Chapter 3. An expression can also be one of the aggregate, date, datetime, or length functions. You cannot include both an aggregate function and a column

INFORMIX-4GL Statement Syntax

7-219

The SELECT Statement

in an expression. The functions that you can use in SQL statements are defined at the end of this chapter. A CHAR column can have subscripts so that only a portion of the column value is involved in the expression. The notation for subscripting a column is column-name[m, n], where you want the mth through the nth characters in the column, for m less than or equal to n. Here the brackets are literal characters, not conventional symbols to indicate an option. 2. A relational operator is one of the following:
Operator = != or < > > >= < <= Operation equal to not equal to greater than greater than or equal to less than less than or equal to

For CHAR expressions, greater than means ‘‘after’’ in the ASCII collating order, where lowercase letters are after uppercase letters, and both are after numerals. See Appendix H for the ASCII codes of all the characters. For DATE and DATETIME expressions, greater than means ‘‘later in time.’’

Notes
1. The clauses of the SELECT statement are explained in detail on the following pages. Briefly, SELECT names a list of columns or expressions to be retrieved, INTO names the program variables to receive the data, FROM names a list of tables, WHERE sets conditions on the rows, GROUP BY groups rows together, HAVING sets conditions on the groups, ORDER BY sequences the selected rows, and INTO TEMP puts the results into a temporary table. 2. If the SELECT statement returns no rows, INFORMIX-4GL returns a ‘‘no rows found’’ code (status = NOTFOUND = 100). See Chapter 3 for a full explanation. 3. If a SELECT statement returns more than one row or if it is dynamically defined, you must use a cursor to FETCH one row at a time (see Chapter 3). 4. It is sometimes helpful to think of the SELECT statement in the following way: When you list more than one table in the FROM clause, INFORMIX-4GL behaves as though it were creating a composite table that is the Cartesian product of all the tables in the FROM clause. That is, the rows of the new table are constructed by taking all the possible combinations of rows from
7-220 INFORMIX-4GL Statement Syntax

The SELECT Statement

all the tables listed in the FROM clause. If there is a WHERE clause, INFORMIX-4GL eliminates from this new table all rows that do not meet the conditions of the WHERE clause. This modified table is returned to the SELECT clause, where all columns not listed are eliminated. The resulting table is what the SELECT statement returns. 5. The SELECT statement cannot appear in a multi-statement PREPARE.

INFORMIX-4GL Statement Syntax

7-221

SELECT Clause

SELECT Clause
Overview
Use the SELECT clause to specify the data that you want to retrieve from one or more tables in a database.

Syntax
SELECT [ ALL | DISTINCT | UNIQUE ] select-list

Explanation
SELECT ALL

is a required keyword. is a keyword that causes INFORMIX-4GL to select all rows that satisfy the WHERE clause, without eliminating duplicates. This keyword is the default. is a keyword that causes INFORMIX-4GL to eliminate duplicate rows from the query results. is a keyword that is synonymous with DISTINCT. is a list of column names and/or expressions separated by commas. A column name must be unambiguous; use its table name as a prefix if there can be confusion.

DISTINCT UNIQUE

select-list

Notes
1. If the SELECT statement does not include a WHERE clause, every row will be returned. 2. The DISTINCT or UNIQUE keyword can appear once in each level of a query or subquery. 3. You can use the asterisk (*) in the select-list to select all columns from all the tables and views in the FROM clause. You could produce the same result by listing every column name in the select-list. 4. To select all the columns from a single table or view, you can use the notation tablename.*. 5. You can supply a display label for the column name or an expression in the select-list by following the column name or expression with a legal identifier. If you create a temporary table with the INTO TEMP clause, the
7-222 INFORMIX-4GL Statement Syntax

SELECT Clause

column names of the temporary table are the display labels, if they have been defined. 6. If you specify an aggregate function and a column in the select-list, the column must be used in the GROUP BY list (see “GROUP BY Clause” for further explanation).

Examples
The following examples use INTO, FROM, and WHERE clauses, whose syntax will be defined later. This example selects columns customer_num, lname, and city; the FROM clause indicates that these columns are taken from the customer table. The values returned are placed in the program variables cnum, lname, and town, respectively. Since lname is both a program variable name and a column name, the column identifier is prefixed with the at ( @ ) sign.
SELECT customer_num, @lname, city INTO cnum, lname, town FROM customer

The next statement counts the number of rows in orders in which the customer_num column contains the value 101. In other words, it counts the number of orders made by the customer whose identifying number is 101. The number is placed in the variable num.
SELECT COUNT(*) INTO num FROM orders WHERE customer_num = 101

The next statement computes the average of the total_price values in those rows of items that contain an order_num column equal to 1021.
SELECT AVG(total_price) FROM items WHERE order_num = 1021

The next example illustrates the use of display labels. It selects the sum of columns a and b from tablez and gives the sum the label abtotal. Similarly, the product of columns c and d is labeled cdprod.
SELECT a+b abtotal, c*d cdprod FROM tablez INTO TEMP x

INFORMIX-4GL Statement Syntax

7-223

INTO Clause

INTO Clause
Overview
Use the INTO clause to specify the program variables to receive the data retrieved by the SELECT statement.

Syntax
INTO variable-list

Explanation
INTO

is a required keyword. is a list of program variables that should agree in order and type with the corresponding columns or expressions in the select-list.

variable-list

Notes
1. If the SELECT statement stands alone (not in a DECLARE statement), it must be a singleton SELECT (returning exactly one row) and must have an INTO clause. 2. If the SELECT statement returns more than one row, you must use a cursor to FETCH the rows one at a time. (See Chapter 3.) You can put the INTO clause in the FETCH statement, rather than in the SELECT statement, but not in both. You can use the FOREACH statement in place of the FETCH statement. 3. If you use DECLARE to associate a SELECT statement with a cursor, the SELECT statement can specify individual elements as a constant but not as a variable of a program array. (FETCH or FOREACH statements can specify program array elements as constants or variables in their INTO clause.) 4. If the number of variables in variable-list differs from the number of items in the select-list, INFORMIX-4GL returns a warning by setting SQLCA. SQLAWARN [4] to W. The actual number of variables transferred is the lesser of the two numbers. 5. If possible, INFORMIX-4GL converts the data type of each selected item to match that of the receiving variable. If the conversion is not possible, an error occurs and a negative value is returned in status. In this case, the
7-224 INFORMIX-4GL Statement Syntax

INTO Clause

value in the program variable is unpredictable. See Chapter 2 for a discussion of data conversion. 6. You cannot PREPARE a query that has an INTO clause. (Instead, you can DECLARE a cursor to perform the query.)

Examples
The following are equivalent program fragments:
DECLARE q_curs CURSOR FOR SELECT @lname, @company INTO lname, company FROM customer OPEN q_curs FETCH q_curs DECLARE q_curs CURSOR FOR SELECT @lname, @company FROM customer OPEN q_curs FETCH q_curs INTO lname, company DECLARE q_curs CURSOR FOR SELECT @lname, @company FROM customer FOREACH q_curs INTO lname, company . . .

INFORMIX-4GL Statement Syntax

7-225

FROM Clause

FROM Clause
Overview
Use the FROM clause to specify the table(s) or views from which you want to select data.

Syntax
FROM { table-name [ table-alias ] | OUTER table-name [ table-alias ] | OUTER ( table-expr ) } [ , . . . ]

Explanation
FROM OUTER

is a required keyword. is an optional keyword. is the name or synonym of a table or view in which to search for data. is an optional alias for table-name. is one or more of the options in the preceding syntax, enclosed in parentheses (for example tab1, outer tab2).

table-name table-alias (table-expr)

Notes
1. Use the optional keyword OUTER to form outer joins. See the “Outer Joins” section in Chapter 3 and Appendix G, “Outer Joins,” for a discussion of this syntax. 2. In a database created as MODE ANSI, the name of a table or view is qualified by the username of the owner (owner.table-name). You must specify owner when you refer to a table or view owned by another user. The use of the prefix owner is optional in a database that is not MODE ANSI. INFORMIX-4GL checks the accuracy of owner, however, if you include it in a statement. See the section “Owner Naming” in Chapter 3 of this manual. 3. You can specify an alias for a table name by following the table name with a space and an SQL identifier. This feature is especially useful when performing self-joins. (See the “WHERE Clause” section of this chapter.)

7-226

INFORMIX-4GL Statement Syntax

FROM Clause

4. The table-alias that you can specify in a FROM clause is distinct from the alias for a table that is sometimes required in the TABLES section of a form specification file. An alias that you define in a form can appear in 4GL screen interaction statements that reference screen fields but cannot appear in a SELECT statement. (See Chapter 4.)

Examples
The following example selects customers who have placed orders.
SELECT fname, lname, order_num FROM customer, orders WHERE customer.customer_num = orders.customer_num

The following example selects all customers whether or not they have placed orders.
SELECT fname, lname, order_num FROM customer, OUTER orders WHERE customer.customer_num = orders.customer_num

INFORMIX-4GL Statement Syntax

7-227

WHERE Clause

WHERE Clause
Overview
Use the WHERE clause to specify search criteria and join conditions on the data to be selected.

Syntax
WHERE condition

Explanation
WHERE

is a required keyword. is a collection of one or more search conditions, optionally connected by the logical operators AND, OR, or NOT. A search condition can be any of the following:

condition

• Comparison condition • Join condition • Condition with subquery
Comparison Condition
A comparison condition can have one of the following forms: a. expr rel-op expr b. expr [ NOT ] BETWEEN expr AND expr c. expr [ NOT ] IN ( value-list ) d. column-name [ NOT ] LIKE "string" [ ESCAPE "esc-char" ] e. column-name [ NOT ] MATCHES "string" [ ESCAPE "esc-char" ] f. column-name IS [ NOT ] NULL These forms are explained in the following pages. Any one of these conditions can be preceded by the keyword NOT, in which case the row is selected only if the condition that NOT qualifies is FALSE.

Syntax
expr rel-op expr

7-228

INFORMIX-4GL Statement Syntax

WHERE Clause

Explanation
expr rel-op is an expression. is a relational operator.

Examples
SELECT fname, lname, company FROM customer WHERE city[1,3] = "San" SELECT order_num, company FROM orders o, customer c WHERE o.order_date > "6/12/86" AND o.customer_num = c.customer_num

If a column value is NULL in a given row, the WHERE clause will not locate that row if you use relational operators. For example, if paid_date has a NULL value, you cannot use either statement (a) or (b) to retrieve that row:
--(a) SELECT customer_num, order_date FROM orders WHERE paid_date = "" --(b) SELECT customer_num, order_date FROM orders WHERE NOT paid_date != ""

You must use the syntax that follows:
SELECT customer_num, order_date FROM orders WHERE paid_date IS NULL

Syntax
expr [ NOT ] BETWEEN expr AND expr

Explanation
expr
NOT BETWEEN

is an expression. is a keyword that indicates that the expression to the left lies outside the range. is a keyword that indicates that the value of the expression to its left lies in the inclusive range of the values of the two expressions to its right.
INFORMIX-4GL Statement Syntax 7-229

WHERE Clause

AND

is a required keyword.

Examples
SELECT stock_num, manu_code FROM stock WHERE unit_price BETWEEN loprice AND hiprice SELECT UNIQUE customer_num, stock_num, manu_code FROM orders, items WHERE order_date BETWEEN "6/1/86" AND "9/7/89" AND orders.order_num = items.order_num SELECT fname, lname FROM customer WHERE zipcode NOT BETWEEN "94100" AND "94199"

Syntax
expr [ NOT ] IN ( value-list )

Explanation
expr
NOT IN

is an expression. is an optional keyword. is a required keyword. is a list of values (enclosed in parentheses).

(value-list)

Notes
1. The search condition is satisfied when the expression to the left is included in the list of items. The NOT option produces a search condition that is satisfied when expr is not in the list of items. 2. The value-list can contain program variables, constants, or the special keyword constants TODAY, CURRENT, and USER. 3. TODAY is evaluated at execution time. CURRENT is evaluated when a cursor is opened, or when the query is executed if it is a singleton select.

7-230

INFORMIX-4GL Statement Syntax

WHERE Clause

Examples
SELECT lname, fname, company FROM customer WHERE state IN ("CA", "WA", "OR") SELECT item_num, total_price INTO inum, tprice FROM items WHERE manu_code IN ("HRO", "HSK")

Syntax
column-name [ NOT ] LIKE "string" [ ESCAPE "escape-character" ]

Explanation
column-name
NOT LIKE

is the name of a column. is an optional keyword. is a required keyword. is a pattern of characters enclosed in quotation marks. is an optional keyword.

string
ESCAPE

escape-character is a single character enclosed in quotation marks.

Notes
1. The search condition is successful when the value of the column on the left matches the pattern specified by string. You can use wildcard characters in place of other characters in the string: % _ A percent sign matches zero or more characters. An underscore matches any single character.

2. The NOT option makes the search condition successful when the column on the left does not match the pattern specified by string. 3. The purpose of the ESCAPE clause is to permit the specification of an underscore ( _ ) or the percent sign ( % ) in string, and to avoid their interpretation as wildcards. If z is the escape-character, then the characters z_ in a string stand for the character _ (not the wildcard). Similarly, z% in the string stands for the character % (not the wildcard). Finally, the characters zz in the string stand for the single character z.

INFORMIX-4GL Statement Syntax

7-231

WHERE Clause

4. You can only use the double quote ( " ) within string to match a literal quote; you cannot use the ESCAPE keyword. Similarly, you cannot use the quote character as the ESCAPE character in matching any other pattern.

Examples
SELECT fname, lname FROM customer WHERE lname LIKE "%son"

finds every customer representative whose last name ends in son.
SELECT stock_num, manu_code, unit_price FROM stock WHERE description LIKE "%ball%"

obtains stock number, manufacturer’s code, and unit price for all stock items with ball anywhere in their description.
SELECT * FROM customer WHERE company LIKE "%z_%" ESCAPE "z"

retrieves rows from the customer table where the company column value includes the underscore character.

Syntax
column-name [ NOT ] MATCHES "string" [ ESCAPE "escape-character" ]

Explanation
column-name
NOT MATCHES

is the name of a column. is an optional keyword. is a required keyword. is a pattern of characters enclosed in quotation marks. is an optional keyword.

string
ESCAPE

escape-character is a single character enclosed in quotation marks.

Notes
1. The search condition is successful when the value of the column on the left matches the pattern specified by string. You can use the following wildcard characters in place of other characters in the string: * ?
7-232

matches zero or more characters matches any single character

INFORMIX-4GL Statement Syntax

WHERE Clause

[...]

matches any of the enclosed characters, including character ranges as in [a-z]. A caret ( ^ ) as the first character within the brackets matches any character that is not listed. Here [^abc] matches any character that is not a, b, or c. escapes special significance of the next character (used to match * or ? by writing \* or \?)

\

2. The NOT option makes the search condition successful when the column on the left does not match the pattern specified by string. 3. The MATCHES comparison is an Informix Software extension to retain compatibility with earlier versions of Informix products. 4. Values used in a MATCHES search must be character strings. 5. The purpose of the ESCAPE clause is to permit the specification of a question mark ( ? ), an asterisk ( * ), the backslash ( \ ), and left or right bracket ( [ ] ), in string and to avoid their interpretation as wildcards. If z is the escape character, then the characters z? in a string stand for the character ? (not the wildcard). Similarly, z* in the string stands for the character * (not the wildcard). Finally, the characters zz in the string stand for the single character z (same as \z). 6. You can only use the double quote ( " ) within string to match a literal quote; you cannot use the ESCAPE keyword. Similarly, you cannot use the quote character as the ESCAPE character in matching any other pattern.

Examples
SELECT fname, lname FROM customer WHERE lname MATCHES "Richard*"

selects rows in which the first seven letters of the last name are Richard (thus matching Richard, Richards, Richardson, and any others).
SELECT customer_num, company FROM customer WHERE city MATCHES "[A-J]*"

provides the customer number and company name for all customers in cities that start with the letters A through J.
SELECT * FROM customer WHERE company MATCHES "*z?*" ESCAPE "z"

retrieves rows from the customer table, where the value in the company column includes the question mark.

INFORMIX-4GL Statement Syntax

7-233

WHERE Clause

Syntax
column-name IS [ NOT ] NULL

Explanation
column-name
IS NULL NOT

is the name of a column. are required keywords. is an optional keyword.

Examples
SELECT order_num, customer_num FROM orders WHERE paid_date IS NULL

lists those order numbers and customer numbers where the order has not been paid. You can link any number of the above-described conditions together using the logical operators AND or OR. For example:
SELECT order_num, total_price FROM items WHERE total_price > loprice AND manu_code LIKE "H%" SELECT lname, customer_num FROM customer WHERE zipcode BETWEEN "93500" AND "95700" OR state NOT IN ("CA", "WA", "OR")

Join Conditions Overview
You join two tables when you create a relationship in the WHERE clause between at least one column from one table and at least one column from another table. The effect of the join is to create a temporary composite table in which each pair of rows (one from each table) satisfying the join condition is linked together to form a single row.

7-234

INFORMIX-4GL Statement Syntax

WHERE Clause

Syntax
The critical elements of a SELECT statement with a join between two tables or views table1 and table2 follow:
SELECT clause FROM table1, table2 WHERE condition

Explanation
SELECT clause is any valid SELECT clause involving columns from table1 or

table2.
FROM

is a required keyword. is the name or synonym of one of the tables or views in the join. is the name or synonym of the other table or view in the join. is a required keyword. is any of the comparison conditions that involves columns from both table1 and table2.

table1 table2
WHERE

condition

Notes
1. When columns from different tables have the same name, you must distinguish them by prefixing the table identifier and a period, in the format table.column. 2. In a database created as MODE ANSI, the name of a table is qualified by the owner of the table (owner. table-name). You must specify owner when you refer to a table owned by another user. The use of the prefix owner is optional in a non-MODE ANSI database. INFORMIX-4GL checks the accuracy of owner, however, if you include it in a statement. See the section “Owner Naming” in Chapter 3 of this manual. 3. A multiple join is a join of more than two tables. Its structure is similar to that shown previously, except that you have a join condition for more than one pair of tables in the FROM clause. 4. You can also join a table to itself in a self-join. To do so, you must list the table name twice in the FROM clause, assigning it two different aliases. Use the aliases to refer to each of the ‘‘two’’ tables in the WHERE clause. 5. An outer join occurs when every row from table1 is taken, whether or not the join condition is met. If the join condition is not met, the columns from table2 in the select-list are set to NULL values. You indicate an outer join by inserting the keyword OUTER before table2.
INFORMIX-4GL Statement Syntax 7-235

WHERE Clause

Examples
This example specifies a two-table join:
SELECT order_num, lname, fname FROM customer, orders WHERE customer.customer_num = orders.customer_num

The query results list the order number and first and last names of the customer’s representative for each order. This example specifies a multiple-table join:
SELECT UNIQUE company, stock_num, manu_code FROM customer c, orders o, items i WHERE c.customer_num = o.customer_num and o.order_num = i.order_num

This query yields the company name of the customer who ordered an item identified with the stock number and manufacturer code. This example specifies a self-join:
SELECT x.stock_num, x.manu_code, y.stock_num, y.manu_code FROM stock x, stock y WHERE x.unit_price > 2.5 * y.unit_price

This query finds pairs of stock items whose unit prices differ by a factor greater than two and one-half. Here x and y are each aliases for the stock table. This example specifies an outer join:
SELECT company, order_num FROM customer c, OUTER orders o WHERE c.customer_num = o.customer_num

This query lists all the customers’ company names and order numbers, if the customer has placed an order. If not, the company name will still be listed. See the “Outer Joins” section in Chapter 3 and Appendix G for information about outer joins.

7-236

INFORMIX-4GL Statement Syntax

WHERE Clause

Subquery Overview
The search condition in a SELECT statement can also perform these tasks:

• Compare an expression to the result of another SELECT statement • Determine whether an expression is included in the results of another
SELECT statement

• Ask whether any rows are selected by another SELECT statement
SELECT statements within a WHERE clause are called subqueries. A subquery can return a single value, no values, or a set of values. If a subquery returns a value, it must return only a single row or column. If the subquery does not return a value (for example, with the EXISTS keyword), any number of rows and columns can be returned. A subquery cannot contain an ORDER BY clause.

The subquery can depend on whether the current row is being evaluated by the outer SELECT statement (correlated subqueries).

Syntax
WHERE expr rel-op { ALL | [ ANY | SOME ] } ( SELECT-statement ) WHERE expr [ NOT ] IN ( SELECT-statement ) WHERE [ NOT ] EXISTS ( SELECT-statement )

Explanation
WHERE

is a required keyword. is an expression. is a relational operator. is a keyword to specify that the subquery can return zero, one, or more values, and that the search condition is TRUE if the comparison is TRUE for each of the values returned. If the subquery returns no value, the search condition is TRUE. is a keyword to specify that the subquery can return zero, one, or more values and that the search condition is TRUE if the comparison is TRUE for at least one of the values returned. If the subquery returns no value, the search condition is FALSE. is a synonym for ANY.
INFORMIX-4GL Statement Syntax 7-237

expr rel-op
ALL

ANY

SOME

WHERE Clause

IN EXISTS

is a keyword that asks whether expr is among the values returned by the following SELECT-statement. is a keyword that asks whether any rows are returned by the following SELECT-statement. The search condition is TRUE if the subquery returns one or more rows. is an optional keyword that reverses the truth value of the search condition. Rows are selected if the WHERE condition is FALSE.

NOT

Notes
1. You can omit the keywords ANY and ALL in a comparison if you know that the subquery will return exactly one value. In this case, the search condition is TRUE if the comparison is TRUE for the expression and the value returned by the subquery. The status will be set to a negative number if the subquery returns other than a single value. 2. The specification expr IN ( SELECT-statement ) is equivalent to expr = ANY ( SELECT-statement ). 3. The specification expr NOT IN ( SELECT-statement ) is equivalent to expr ! = ALL ( SELECT-statement ).

Examples
SELECT order_num FROM items WHERE stock_num = 9 AND quantity = (SELECT MAX(quantity) FROM items WHERE stock_num = 9)

This subquery returns a single value (the maximum number of volleyball nets ordered) to the outer-level query. The entire SELECT statement lists the order numbers for orders that include the maximum number of volleyball nets.
SELECT UNIQUE order_num FROM items WHERE total_price > ALL (SELECT total_price FROM items WHERE order_num = 1011)

7-238

INFORMIX-4GL Statement Syntax

WHERE Clause

This query lists the order numbers of all orders containing an item whose total price is greater than the total price on all the items in order number 1011.
SELECT UNIQUE customer_num FROM orders WHERE order_num NOT IN (SELECT order_num FROM items WHERE stock_num = 1)

This query lists all customer numbers of customers who have placed orders that do not include baseball gloves (stock_num = 1).
SELECT order_num, stock_num, manu_code, total_price FROM items x WHERE total_price > (SELECT 2 * MIN(total_price) FROM items WHERE order_num = x.order_num)

This query (using a correlated subquery) lists all items whose total price is at least twice the minimum total price for all items on the same order.

INFORMIX-4GL Statement Syntax

7-239

GROUP BY Clause

GROUP BY Clause
Overview
Use the GROUP BY clause to produce a single row of results for each group. A group is a set of rows having the same values for each column listed.

Syntax
GROUP BY group-list

Explanation
GROUP BY

are required keywords. is a column name or a list of column names, separated by commas, that determines the group. The query result contains a single row for each set of rows that satisfies the WHERE clause and contains a unique value or set of values in the column or columns indicated by group-list.

group-list

Notes
1. Using a GROUP BY clause restricts what you can enter in the SELECT clause. The select-list can include aggregate functions for any column and/or the name of any column that you also list in the GROUP BY clause. You cannot, however, list any column in the select-list that you do not also list in group-list. 2. The SELECT list can contain expressions involving GROUP BY columns. 3. In the place of column names in group-list, you can enter one or more integers that refer to the position of items in the select-list. 4. NULL values are considered identical when evaluated within a GROUP BY clause. 5. You can GROUP BY up to eight columns.

Examples
SELECT order_num, COUNT(*), SUM(total_price) FROM items GROUP BY order_num

7-240

INFORMIX-4GL Statement Syntax

GROUP BY Clause

obtains the number of items and total price of all items for each order.
SELECT order_num, COUNT(*), SUM(total_price) FROM items GROUP BY 1

returns the same information as the previous example.

INFORMIX-4GL Statement Syntax

7-241

HAVING Clause

HAVING Clause
Overview
Use the HAVING clause to apply one or more qualifying conditions to groups.

Syntax
HAVING condition

Explanation
HAVING

is a required keyword. is a condition, as if defined for a WHERE clause.

condition

Notes
1. Each condition compares one column or aggregate property of the group either with another aggregate property of the group or with a constant. 2. The HAVING clause generally complements a GROUP BY clause. If you use HAVING without GROUP BY, the HAVING clause applies to all rows that satisfy the WHERE clause. Without a GROUP BY clause, all rows that satisfy the WHERE clause make up a single group. 3. You can use the HAVING clause to place conditions on the GROUP BY column values, as well as on aggregate values.

Example
SELECT order_num, AVG(total_price) FROM items GROUP BY order_num HAVING COUNT(*) > 2

This query returns the average total price per item on all orders that have more than two items.

7-242

INFORMIX-4GL Statement Syntax

ORDER BY Clause

ORDER BY Clause
Overview
Use the ORDER BY clause to sort query results by the values contained in one or more columns. You can sort only by a column that you specify in the SELECT clause.

Syntax
ORDER BY column-name [ ASC | DESC ] [ , . . . ]

Explanation
ORDER BY

are required keywords. is the name of a column by which you want to sort the query results. is a keyword that specifies that the results should be in ascending order (smallest value first, largest last). ASC is the default. is a keyword that specifies that the results should be in descending order (largest value first).

column-name
ASC

DESC

Notes
1. You can only ORDER BY columns that are named explicitly or implicitly in the select-list. 2. You can ORDER BY up to eight columns. 3. The total length of the data in the columns included in the ORDER BY clause cannot be greater than 120 bytes. 4. In the place of column names, you can enter one or more integers that refer to the position of items in the select-list. In this way, you can ORDER BY an expression. 5. You cannot use a DECLARE statement with a FOR UPDATE clause to associate a cursor with a SELECT statement that has an ORDER BY clause.

INFORMIX-4GL Statement Syntax

7-243

ORDER BY Clause

Examples
CORRECT: SELECT order_date, ship_date FROM orders ORDER BY order_date SELECT * FROM orders ORDER BY order_date SELECT order_date, ship_date FROM orders ORDER BY customer_num

CORRECT:

INCORRECT:

In the first two examples, order_date is either explicitly or implicitly listed in the select-list. In the third example, even though the column customer_num is in the orders table, it was not contained in the select-list. The query in the next example
SELECT customer_num, fname, lname, company FROM customer ORDER BY 3, 2

performs a nested sort. The first level of sorting is based on the lname column, and the second level is based on the fname column.

7-244

INFORMIX-4GL Statement Syntax

INTO TEMP Clause

INTO TEMP Clause
Overview
Use the INTO TEMP clause to create a temporary table that contains the query results. The temporary table disappears when your program ends.

Syntax
INTO TEMP table-name [ WITH NO LOG ]

Explanation
INTO TEMP

are required keywords. is the SQL identifier that you assign to the temporary table. tables.

table-name

WITH NO LOG are optional keywords to prevent logging of temporary

Notes
1. You will save time if you use a temporary table when the same query results are required several times. 2. An INTO TEMP clause in a SELECT statement often gives you clearer and more easily understood statements. 3. The column names of the temporary table are those named in the selectlist. If you list a display label for a column or expression, the column name in the temporary table is the display label. 4. No indexes are associated with table-name. 5. Do not use an INTO clause with the INTO TEMP clause. If you do, no results will be returned to the program variables, and status will be set to a negative value. 6. The temporary table persists until you exit from your 4GL program or issue the DROP TABLE table-name statement. 7. The keywords WITH NO LOG prevent INFORMIX-4GL from including in the transaction log operations on temporary tables. You can use this option to reduce the overhead of transaction logging.

INFORMIX-4GL Statement Syntax

7-245

UNION Operator

UNION Operator
Overview
The UNION operator is a keyword placed between two SELECT statements, to let you combine the queries into a single query.

Syntax
SELECT-statement UNION [ ALL ] SELECT-statement [ UNION [ ALL ] SELECT-statement . . . ]

Explanation
UNION ALL

is a keyword that selects all rows from both queries, removes duplicates, and returns what is left. is an optional keyword that leaves the duplicates.

Notes
1. You can place the UNION operator between each member of a sequence of more than two queries. 2. It is possible to write single queries that are equivalent to the compound queries constructed using the UNION operator. The advantage of the UNION operator is that it makes the process easier. 3. There are restrictions on the queries that you can connect with UNION operators.

• The number of the items in the select-list of each query must be the
same, and corresponding items in each select-list must have identical data types.

• Corresponding items need not have the same identifier.

7-246

INFORMIX-4GL Statement Syntax

UNION Operator

• You cannot use an INTO statement in a query unless you are sure that
the compound query will return exactly one row and you are not using a cursor. In this rare case, the INTO clause must be in the first SELECT statement.

• If you use an ORDER BY clause, it must follow the last SELECT statement, and you must refer by integer, not by identifier, to the item to be ordered. Ordering takes place after the set operation is complete. 4. UNION operators cannot occur inside a subquery and cannot be used in the definition of a view. 5. The column names (or display labels) of the resulting table are the same as those from the first SELECT statement. 6. You can put the results of a UNION into a temporary table by putting an INTO TEMP clause in the final SELECT statement.

Example
The following example selects those items (identified by a stock number and a manufacturing code) that have a unit price of less than $100.00 or that have been ordered in quantities greater than three.
SELECT DISTINCT stock_num, manu_code FROM stock WHERE unit_price < 100.00 UNION SELECT stock_num, manu_code, FROM items WHERE quantity > 3 ORDER BY 1

INFORMIX-4GL Statement Syntax

7-247

Functions in SQL Statements

Functions in SQL Statements
You can use the aggregate, length, date, and datetime functions anywhere in an SQL expression that a constant can appear. The following functions are available:
Aggregate Functions COUNT(*) SUM( ) AVG( ) MAX( ) MIN( ) Length Functions LENGTH( ) Date Functions DATE( ) DAY( ) MDY( ) MONTH( ) WEEKDAY( ) YEAR( ) Datetime Functions CURRENT EXTEND( )

These functions are defined on the pages that follow. You can also use the TODAY and USER functions that are described in Chapter 2 and Chapter 3 of this manual. Except for CURRENT, DATE( ), and MDY( ), all the date and datetime functions can accept both DATE and DATETIME values as arguments.

7-248

INFORMIX-4GL Statement Syntax

Aggregate Functions

Aggregate Functions
Overview
The aggregate functions take on values that depend on the set of rows returned by the WHERE clause of a SELECT statement. In the absence of a WHERE clause, the aggregate functions take on values that depend on all the rows formed by the FROM clause.
Syntax COUNT (*) COUNT ( DISTINCT x) Function

returns the number of rows that satisfy the WHERE clause. returns the number of different values in column x from rows that satisfy the WHERE clause. returns the sum of all values in column x from rows that satisfy the WHERE clause. You can apply SUM only to number columns. The default is ALL. If you use the keyword DISTINCT, the sum is only over distinct values in column x. returns the average of all values in column x from rows that satisfy the WHERE clause. You can apply AVG only to number columns. The default is ALL. If you use the keyword DISTINCT, the average (mean) is only over the distinct values in column x. returns the largest value in column x from a row that satisfies the WHERE clause. Default is ALL. returns the lowest value in column x from a row that satisfies the WHERE clause. Default is ALL.

SUM ( [ ALL | DISTINCT ] x)

AVG ( [ ALL | DISTINCT ] x)

MAX ( [ ALL | DISTINCT ] x)

MIN ( [ ALL | DISTINCT ] x)

Notes
1. In the functions SUM(x), AVG(x), MAX(x), and MIN(x), x can be an expression instead of a column name. If x is an expression, the function is evaluated over the values of the expression as computed for each row that

INFORMIX-4GL Statement Syntax

7-249

Aggregate Functions

satisfies the WHERE clause. The expression can not contain another aggregate function. 2. Both the COUNT(x) function and the keyword DISTINCT can only be used with column names, not with expressions. 3. You can use the keyword DISTINCT only once in each level of a query or subquery. Use DISTINCT to disregard duplicate query results or to eliminate duplicates from the argument of an aggregate function. 4. Specifying DISTINCT in a MIN or MAX function has no effect on the value returned by the function. 5. You can use the keyword UNIQUE as a synonym for DISTINCT. 6. Aggregate functions handle NULL values in these ways:

COUNT(DISTINCT x), AVG (x), SUM (x), MAX (x), and MIN (x) ignore rows with NULL values for x and return the appropriate values based on the rest of the rows.

• If x contains only NULL values, however, then the function COUNT
(DISTINCT x ) returns zero, and the other aggregate functions return NULL for that column.

COUNT(*) counts all rows, even if the value of every column in the row is NULL.

Examples
If a query selects seven rows in which the set of values in column x is
{ 2, 2, 2, 3, 3, 4, NULL }

then COUNT (*) returns 7, and COUNT ( DISTINCT x ) returns 3. For these values, MAX (x) returns 4, and MIN (x) returns 2.

7-250

INFORMIX-4GL Statement Syntax

LENGTH( )

LENGTH( )
Overview
The LENGTH function returns the clipped length of a character column or variable.

Syntax
LENGTH ( string )

Explanation
string is a character variable, string constant, or the name of a column that contains character data.

Note
LENGTH allows only one argument. You can, however, combine LENGTH val-

ues through an expression. (See the example.)

Example
SELECT customer_num, LENGTH(fname) + LENGTH(lname), LENGTH("How many bytes is this?") FROM customer WHERE LENGTH(company) > 10

Note: INFORMIX-OnLine supports additional data types. Refer to the INFORMIX-OnLine Programmer’s Manual for more information.

INFORMIX-4GL Statement Syntax

7-251

DATE( )

DATE( )
Overview
The DATE( ) function returns a type DATE value, corresponding to the expression with which you call it.

Syntax
DATE ( expr )

Explanation
DATE

is a required keyword. is a required expression that can be converted to a type DATE value.

expr

Note
The expr is usually of type CHAR, DATETIME, or INTEGER.

Example
The following example uses DATE( ) to convert a string to a date.
WHERE end_date > DATE("12/13/1989")

7-252

INFORMIX-4GL Statement Syntax

DAY( )

DAY( )
Overview
The DAY( ) function returns an integer that represents the day of the month, when you call it with a type DATE or DATETIME argument.

Syntax
DAY ( time-expr )

Explanation
DAY

is a required keyword.

time-expr is a required expression whose value is of type DATE or DATETIME.

Example
This example uses the DAY ( ) function with the CURRENT function to compare column values to the current day of the month.
WHERE DAY(ord_date) > DAY(CURRENT)

INFORMIX-4GL Statement Syntax

7-253

MDY( )

MDY( )
Overview
The MDY( ) function returns a type DATE value when you call it with three expressions that evaluate to integers representing the month, day of the month, and year.

Syntax
MDY ( expr1, expr2, expr3 )

Explanation
MDY

is a required keyword. is an expression that evaluates to an integer representing the number of the month (1-12). is an expression that evaluates to an integer representing the number of the day of the month (1-28, 29, 30, or 31, depending on the month). is an expression that evaluates to a four-digit integer representing the year.

expr1 expr2

expr3

Notes
The value of expr3 cannot be the abbreviation for the year. For example, 89 is a year in the first century.

7-254

INFORMIX-4GL Statement Syntax

MONTH( )

MONTH( )
Overview
The MONTH( ) function returns an integer corresponding to the month portion of its type DATE or DATETIME argument.

Syntax
MONTH ( time-expr )

Explanation
MONTH

is a required keyword.

time-expr is a required expression of type DATE or DATETIME.

Notes
1. This function extracts the month from a DATE value, returning an integer m in the range 1 ≤ m ≤ 12. 2. The time-expr cannot be an INTERVAL argument.

Example
SELECT order_num, MONTH (order_date) FROM orders

INFORMIX-4GL Statement Syntax

7-255

WEEKDAY( )

WEEKDAY( )
Overview
The WEEKDAY( ) function returns an integer that represents the day of the week, when you call it with a type DATE or DATETIME expression.

Syntax
WEEKDAY ( time-expr )

Explanation
WEEKDAY

is a required keyword. is a required expression of type DATE or DATETIME.

time-expr

Notes
1. WEEKDAY returns an integer in the range 0-6. Zero represents Sunday, 1 represents Monday, and so on. 2. The time-expr cannot be a type INTERVAL argument.

Examples
SELECT order_num, WEEKDAY (order_date) FROM orders SELECT * FROM orders WHERE WEEKDAY (paid_date) = WEEKDAY (CURRENT - 31 UNITS DAY)

7-256

INFORMIX-4GL Statement Syntax

YEAR( )

YEAR( )
Overview
The YEAR( ) function returns an integer that represents the year when you call it with a type DATE or DATETIME expression.

Syntax
YEAR ( time-expr )

Explanation
YEAR

is a required keyword.

time-expr is a required expression of type DATE or DATETIME.

Notes
The time-expr cannot be an INTERVAL argument.

Examples
SELECT order_num, YEAR (order_date) FROM orders SELECT order_num, customer_num FROM orders WHERE YEAR(ship_date) < YEAR(TODAY)

The second example specifies rows in which the ship_date is earlier than the beginning of the current year.

INFORMIX-4GL Statement Syntax

7-257

CURRENT

CURRENT
Overview
The CURRENT function returns a DATETIME value with the date and time of day of the current instant.

Syntax
CURRENT [ first TO last ]

Explanation
CURRENT

is a required keyword. is a qualifier that specifies the first field to be returned. is a required keyword if you specify first and last. is a qualifier that specifies the last field to be returned.

first
TO

last

Notes
1. The value returned is the date and time (from the system clock) when the CURRENT function executes. 2. You can use the CURRENT function in any context in which you can use a DATETIME literal. 3. The first qualifier must specify a field that is more significant than or equal to the last qualifier. 4. If the function is executed more than once in a statement, identical values may be returned at each point of the call. You cannot rely on CURRENT to provide distinct values each time that it executes. 5. INFORMIX-4GL may not execute the CURRENT function in the physical order in which it appears in a statement. You should not use the function to mark the start, the end, or any specific point in the execution of the 4GL statement. 6. If no first TO last qualifiers are specified, the default qualifiers are YEAR TO FRACTION(3).

7-258

INFORMIX-4GL Statement Syntax

CURRENT

7. The following qualifiers are valid:
Identifier YEAR MONTH DAY HOUR MINUTE SECOND FRACTION (n) Qualified Data A number of years. A number of months. A number of days. A number of hours. A number of minutes. A number of seconds. A decimal fraction of a second with n (up to five) digits of precision. The default precision is three digits (thousandths of a second).

Example
SELECT prog_title FROM tv_programs WHERE air_date > CURRENT YEAR TO DAY

See also Appendix J, “Working with DATETIME and INTERVAL Data.”

INFORMIX-4GL Statement Syntax

7-259

EXTEND( )

EXTEND( )
Overview
The EXTEND function adjusts the precision of a DATETIME or DATE value.

Syntax
EXTEND ( value [ , first TO last ] )

Explanation
EXTEND

is a required keyword. is a DATETIME or DATE type column name, variable, or expression. is an optional qualifier that specifies the first field in the result. (See Note 5.) is a required keyword if you include first and last qualifiers. is an optional qualifier that specifies the last field in the result. (See Note 6.)

value first
TO

last

Notes
1. The value can also be a DATETIME literal, or a character string in a valid DATETIME format. (It cannot be the string representation of a DATE value.) 2. If no first TO last qualifiers are specified, the default qualifiers are YEAR TO FRACTION(3). 3. The first qualifier must specify a field that is more significant than or equal to the last qualifier. 4. If the value contains fields not specified by the qualifiers, the unwanted fields are discarded. 5. If the first qualifier specifies a field to the left of (that is, more significant than) what exists in value, the new fields are filled with values returned by the CURRENT function.

7-260

INFORMIX-4GL Statement Syntax

EXTEND( )

6. If the last qualifier specifies a field to the right of (that is, less significant than) what exists in value, the new fields are filled in with constant values. A missing MONTH or DAY is filled in with 1, and the missing fields HOUR to FRACTION are filled in with 0. 7. The following qualifiers are valid:
Identifier YEAR MONTH DAY HOUR MINUTE SECOND FRACTION (n) Qualified Data A number of years. A number of months. A number of days. A number of hours. A number of minutes. A number of seconds. A decimal fraction of a second with n (up to five) digits of precision. The default precision is three digits (thousandths of a second).

8. If an INTERVAL value includes a field that is not present in a DATETIME value, you cannot combine the two values with the addition ( + ) or subtraction ( - ) operators. Similarly, you cannot add or subtract a DATE value and an INTERVAL whose last qualifier is smaller than DAY. In these cases, you must use the EXTEND function to return an adjusted DATETIME value on which to perform the arithmetic operation. See also Appendix J, “Working with DATETIME and INTERVAL Data.”

Examples
In the following example, the EXTEND function returns the MONTH and DAY fields from a column that contains YEAR, MONTH, and DAY data. In this instance the YEAR field is not returned.
SELECT EXTEND(air_date, MONTH TO DAY) FROM tv_programs

In the next example, assume that air_date is a DATE column, or else a DATETIME column whose last qualifier is larger than MINUTE. Then the EXTEND function is required in the following statement, because the INTERVAL operand includes a field (MINUTE) that is not part of the precision of air_date.
SELECT sponsor, prog_title, air_date FROM tv_programs WHERE air_date >= TODAY AND CURRENT > EXTEND(air_date) - 2880 UNITS MINUTE

INFORMIX-4GL Statement Syntax

7-261

EXTEND( )

Since no qualifiers are specified as arguments, the EXTEND function returns a DATETIME value with the default precision YEAR to FRACTION(3). The WHERE clause in this example specifies the rows in which air_date has a value in a range from the beginning of the current day (TODAY) up to 48 hours (= 2,880 minutes) after the current instant. See also Appendix J, “Working with DATETIME and INTERVAL Data.” for more information about arithmetic operations on date and time data types.

7-262

INFORMIX-4GL Statement Syntax

Appendix

A
Demonstration Database and Application
The stores Database
The stores database contains a set of tables that describe an imaginary business. You can access the data in stores by the demonstration programs that appear in this book, as well as by application programs that are listed in the documentation of other Informix products. The stores database is not MODE ANSI. This appendix contains five sections:

• The first section describes the structure of the tables in
the stores database. For each table, the name and the data type of each column are listed. Any indexes on individual columns or on multiple columns are identified and classified as unique or as allowing duplicate values.

• The second section presents a graphic map of the tables
in the stores database, showing potential join columns.

• The third section discusses the join columns that link
some of the tables in the stores database, and illustrates how you can use these relationships to obtain information from multiple tables.

• The fourth section shows the data contained in each
table of the stores database.

Structure of the Tables

• The final section contains the form specifications, INFORMIX-4GL source
code modules, and help message source code for the demonstration application. If you have modified or deleted some or all of the data in these tables, you can restore the stores database to its original form by entering i4gldemo (if you have the C Compiler Version), or

r4gldemo (if you have the Rapid Development System). Running this script creates a subdirectory called stores.dbs in your current directory, and places the stores database files there. It also copies all the demonstration programs, forms, and help files into the current directory.

Structure of the Tables
The stores database contains information about a fictitious sporting goods distributor that services stores in the Western United States. This database includes the following tables:

• • • • • •

customer orders items stock manufact state

The customer Table
The customer table describes the retail stores that order from the distributor. Information includes each store’s name, address, and telephone number, and the name of its representative. The customer table has the following columns: customer_num fname lname company address1 address2 city state zipcode phone serial(101) char(15) char(15) char(20) char(20) char(20) char(15) char(2) char(5) char(18)

The customer_num column is indexed as unique.
A-2 Demonstration Database and Application

Structure of the Tables

The zipcode column is indexed to allow duplicate values.

The orders Table
The orders table contains data about orders placed by customers of the distributor. This information includes the order number, the date when the order was made, the customer number, shipping instructions, the customer’s purchase order number, the date when the order was shipped, the weight of the order, the shipment charge, and the date when the customer paid for the order. It also tells whether a backlog exists. The columns of the orders table are listed here: order_num order_date customer_num ship_instruct backlog po_num ship_date ship_weight ship_charge paid_date serial(1001) date integer char(40) char(1) char(10) date decimal(8,2) money(6) date

The order_num column is indexed, and must contain unique values. The customer_num column is indexed, but allows duplicates.

The items Table
An order can include one or more items. The items table describes the items in each order. Information in the items table includes the item number, codes for the order, stock, and manufacturer, the quantity, and the total price for the item. The items table has these columns: item_num order_num stock_num manu_code quantity total_price smallint integer smallint char(3) smallint money(8)

The order_num column has an index that allows duplicate values. A multiple-column index for the stock_num and manu_code columns also permits duplicate values.

Demonstration Database and Application

A-3

Structure of the Tables

The stock Table
The distributor carries fifteen different types of sporting goods. For example, the distributor offers baseball gloves from three manufacturers, and offers basketballs from one manufacturer. The stock table is a catalog of the items sold by the distributor. For each item in stock, the stock table lists a stock number identifying the type of item, a code identifying the manufacturer, a description of the item, its unit price, the unit by which the item must be ordered, and a description of the unit (for example, a case containing 10 baseballs). These are the names and data types of the columns in the stock table: stock_num manu_code description unit_price unit unit_descr smallint char(3) char(15) money(6) char(4) char(15)

A multiple-column index for both the stock_num and manu_code columns allows only unique values.

The manufact Table
Information about the five manufacturers whose sporting goods are handled by the distributor is kept in the manufact table. Each row contains a manufacturer’s identifying code and name. The columns in the manufact table are as follows: manu_code manu_name char(3) char(15)

The manu_code column has an index that requires unique values.

The state Table
The state table contains the names and postal abbreviations of the fifty states of the United States. It includes two columns: code sname char(2) char(15)

The code column is indexed as unique.

A-4

Demonstration Database and Application

Map of the stores Database

Map of the stores Database
Figure A-1 displays the column names of the tables in the stores database, and indicates which columns in different tables contain the same information.
items orders order_num customer customer_num fname lname company address1 address2 state code sname Figure A-1 city state zipcode phone Tables in the stores Database order_date customer_num ship_instruct backlog po_num ship_date ship_weight ship_charge paid_date item_num order_num stock_num manu_code quantity total_price stock stock_num manu_code description unit_price unit unit_descr manufact manu_code manu_name

Join Columns That Link the Database
The tables of the stores database are linked together by join columns, which are identified in this section. You can use them to retrieve and display information from several tables at once, as if it had been stored in a single table. Figures A-2 through A-6 show the relationships among tables, and how information stored in one table supplements information in others.

Join Columns in the customer and orders Tables
The customer_num column joins the customer table and the orders table, as shown in Figure A-2.

Demonstration Database and Application

A-5

Join Columns That Link the Database

customer_num 101 102 103 104 order_num 1001 1002 1003 1004 Figure A-2

fname Ludwig Carole Philip Anthony order_date 01/20/1989 06/01/1989 10/12/1989 04/12/1989

lname Pauli Sadler Currie Higgins customer_num 104 101 104 106

customer table (detail)

orders table (detail)

Tables Joined by the customer_num Column

The customer table contains a customer_num column that holds a number identifying a customer, along with columns for the customer’s name, company, address, and telephone number. For example, the row with information about Anthony Higgins contains the number 104 in the customer_num column. The orders table also contains a customer_num column that stores the number of the customer who placed a particular order. According to Figure A-2, customer 104 (Anthony Higgins) has placed two orders, since his customer number appears in two rows of the orders table. The join relationship lets you select information from both tables. This means that you can retrieve Anthony Higgins’s name and address and information about his orders at the same time.

Join Columns in the orders and items Tables
The orders and items tables are linked by an order_num column that contains an identification number for each order. If an order includes several items, the same order number appears in several rows of the items table. Figure A-3 shows this relationship.

A-6

Demonstration Database and Application

Join Columns That Link the Database

order_num 1001 1002 1003 1004 item_num 1 1 2 1 2 3 Figure A-3

order_date 01/20/1989 06/01/1989 10/12/1989 04/12/1989 order_num 1001 1002 1002 1003 1003 1003

customer_num 104 101 104 106 manu_code HRO HSK HSK ANZ ANZ ANZ

orders table (detail)

stock_num 1 4 3 9 8 5

items table (detail)

Tables Joined by the order_num Column

Join Columns in the items and stock Tables
The items table and the stock table are joined by two columns: the stock_num column stores a stock number for an item, and the manu_code column stores a code to identify the manufacturer. You need both the stock number and the manufacturer code to uniquely identify an item. For example, the item with the stock number 1 and the manufacturer code HRO is a Hero baseball glove, while the item with the stock number 1 and and the manufacturer code HSK is a Husky baseball glove.

Demonstration Database and Application

A-7

Join Columns That Link the Database

item_num 1 1 2 1 2 3 1 stock_num 1 1 1 Figure A-4

order_num 1001 1002 1002 1003 1003 1003 1004 manu_code HRO HSK SMT

stock_num 1 4 3 9 8 5 1 description baseball glove baseball glove baseball glove

manu_code HRO HSK HSK ANZ ANZ ANZ HRO

items table (detail)

stock table (detail)

Tables Joined by Two Columns

The same stock number and manufacturer code can appear in more than one row of the items table, if the same item belongs to separate orders. This is illustrated above in Figure A-4.

Join Columns in the stock and manufact Tables
The stock table and the manufact table are joined by the manu_code column. The same manufacturer code can appear in more than one row of the stock table if the manufacturer produces more than one piece of equipment. This relationship is illustrated in Figure A-5.
stock_num 1 1 1 2 manu_code NRG HSK HRO Figure A-5 manu_code HRO HSK SMT HRO manu_name Norge Husky Hero description baseball glove baseball glove baseball glove baseball stock table (detail)

manufact table (detail)

Tables Joined by the manu_code Column

A-8

Demonstration Database and Application

Data in the stores Database

Join Columns in the state and customer Tables
The state table and the customer table are joined by a column that contains the state code. This column is called code in the state table and state in the customer table. If several customers live in the same state, the same state code will appear in several rows of the customer table, as shown in Figure A6.
customer_num 101 102 103 code AK AL AR AZ CA Figure A-6 fname Ludwig Carole Philip sname Alaska Alabama Arkansas Arizona California lname Pauli Sadler Currie ... ... ... ... state CA CA CA customer table (detail)

state table (detail)

Tables Joined by the State-Code Column

Joining lets you rearrange your view of a database whenever you want. It provides flexibility that lets you create new relationships between tables without redesigning the database. You can easily expand the scope of a database by adding new tables that join the existing tables. As you read through this manual, you will see programs that set up the join relationships across tables of the stores database. Refer to these figures whenever you need to review these relationships.

Data in the stores Database
The tables that follow display the data in the stores database.

Demonstration Database and Application

A-9

A-10

customer Table
fname
Ludwig Carole Philip Anthony Raymond George Charles Donald Jane Roy Frances Margaret Lana Frank Alfred Jean Arnold Dick Baxter Blue Ribbon Sports Sipes Kids Korner Parmelee Olympic City Grant Gold Medal Sports Albertson Sporting Place Beatty Sportstown 654 Oak Grove 947 Waverly Place 776 Gary Avenue 1104 Spinosa Drive 850 Lytton Court 5427 College Lawson Runners & Others 234 Wyandotte Way Keyes Sports Center 3199 Sterling Court Jaeger AA Athletics 520 Topaz Way Miller Sport Stuff Mayfair Mart Quinn Quinn’s Sports 587 Alvarado Ream Athletic Supplies 41 Jordan Avenue Watson Watson & Son 1143 Carver Place Vector Los Altos Sports 1899 La Loma Drive Higgins Play Ball! East Shopping Cntr. 422 Bay Road Los Altos Mountain View Palo Alto Redwood City 7345 Ross Blvd. Sunnyvale Redwood City Sunnyvale Los Altos Menlo Park Redwood City Menlo Park Mountain View Redwood City Oakland Currie Phil’s Sports 654 Poplar P. O. Box 3498 Palo Alto Redwood City Sadler Sports Spot 785 Geary St San Francisco Pauli All Sports Supplies 213 Erstwild Court Sunnyvale CA CA CA CA CA CA CA CA CA CA CA CA CA CA CA CA CA CA

customer_num

lname

company

address1

address2

city

state

zip code
94086 94117 94303 94026 94022 94063 94304 94063 94086 94062 94085 94022 94025 94062 94025 94040 94063 94609

phone
408-789-8075 415-822-1289 415-328-4543 415-368-1100 415-776-3249 415-389-8789 415-356-9876 415-544-8729 408-723-8789 415-743-3611 408-277-7245 415-887-7235 415-356-9982 415-886-6677 415-356-1123 415-534-8822 415-245-4578 415-655-0011

101

102

Demonstration Database and Application

103

104

105

Data in the stores Database

106

107

108

109

110

111

112

113

114

115

116

117

118

Data in the stores Database

items Table
item_num 1 1 2 1 2 3 1 2 3 4 1 2 3 4 1 2 3 4 5 1 2 3 4 5 1 2 1 1 2 1 1 2 1 2 3 4 1 2 1 order_num 1001 1002 1002 1003 1003 1003 1004 1004 1004 1004 1005 1005 1005 1005 1006 1006 1006 1006 1006 1007 1007 1007 1007 1007 1008 1008 1009 1010 1010 1011 1012 1012 1013 1013 1013 1013 1014 1014 1015 stock_num 1 4 3 9 8 5 1 2 3 1 5 5 6 6 5 5 5 6 6 1 2 3 4 7 8 9 1 6 6 5 8 9 5 6 6 9 4 4 1 manu_code HRO HSK HSK ANZ ANZ ANZ HRO HRO HSK HSK NRG ANZ SMT ANZ SMT NRG ANZ SMT ANZ HRO HRO HSK HRO HRO ANZ ANZ SMT SMT ANZ ANZ ANZ ANZ ANZ SMT ANZ ANZ HSK HRO SMT quantity 1 1 1 1 1 5 1 1 1 1 10 10 1 1 5 5 5 1 1 1 1 1 1 1 1 5 1 1 1 5 1 10 1 1 1 2 1 1 1 total_price 250.0 960.0 240.0 20.0 840.0 99.0 960.0 126.0 240.0 800.0 280.0 198.0 36.0 48.0 125.0 190.0 99.0 36.0 48.0 250.0 126.0 240.0 480.0 600.0 840.0 100.0 450.0 36.0 48.0 99.0 840.0 200.0 19.8 36.0 48.0 40.0 960.0 480.0 450.0

Demonstration Database and Application

A-11

A-12

orders Table
ship_instruct
ups po on box; deliver back door only via ups ring bell twice call before delivering after 10 am n closed Monday door next to supersaver deliver 776 Gary if no answer ups n via ups closed Mon n n ring bell, kick door loudly n n n n 4745 429Q B77897 278701 B77930 8052 MA003 y LZ230 278693 y Q13557 04/23/89 12/06/89 03/04/89 06/08/89 04/13/89 06/09/89 09/18/89 05/10/89 08/01/89 n 2865 y 8006 04/30/89 12/19/89 n B77890 10/13/89 n 9270 06/06/89 n B77836 02/01/89 20.40 50.60 35.60 95.80 80.80 70.80 125.90 45.60 20.40 40.60 10.40 70.80 60.80 40.60 20.60

order_num order_date customer_num
01/20/89 06/01/89 10/12/89 04/12/89 12/04/89 09/19/89 03/25/89 11/17/89 02/14/89 05/29/89 03/23/89 06/05/89 09/01/89 05/01/89 07/10/89 110 106 104 117 104 115 111 110 117 112 116 106 104 101 104

backlog

po_num

ship_date

ship_weight

ship_charge
10.00 15.30 10.80 19.20 16.20 14.20 25.20 13.80 10.00 12.30 5.00 14.20 12.20 12.30 6.30

paid_ date
03/22/89 07/03/89 11/04/89 12/30/89

1001

1002

1003

Demonstration Database and Application

1004

1005

Data in the stores Database

1006

1007

1008

12/21/89 04/21/89 07/22/89 06/01/89 10/10/89 07/18/89 08/31/89

1009

1010

1011

1012

1013

1014

1015

Data in the stores Database

stock Table
stock_num 1 1 1 2 3 4 4 5 5 5 6 6 7 8 9 manu_code HRO HSK SMT HRO HSK HSK HRO NRG SMT ANZ SMT ANZ HRO ANZ ANZ description baseball gloves baseball gloves baseball gloves baseball baseball bat football football tennis racquet tennis racquet tennis racquet tennis ball tennis ball basketball volleyball volleyball net unit_price 250.00 800.00 450.00 126.00 240.00 960.00 480.00 28.00 25.00 19.80 36.00 48.00 600.00 840.00 20.00 unit case case case case case case case each each each case case case case each unit_descr 10 gloves/case 10 gloves/case 10 gloves/case 24/case 12/case 24/case 24/case each each each 24 cans/case 24 cans/case 24/case 24/case each

manufact Table
manu_code ANZ HSK HRO NRG SMT manu_name Anza Husky Hero Norge Smith

Demonstration Database and Application

A-13

Data in the stores Database

state Table
code AK AL AR AZ CA CO CT DE FL GA HI IA ID IL IN KS KY LA MA MD ME MI MN MO MS sname Alaska Alabama Arkansas Arizona California Colorado Connecticut Delaware Florida Georgia Hawaii Iowa Idaho Illinois Indiana Kansas Kentucky Louisiana Massachusetts Maryland Maine Michigan Minnesota Missouri Mississippi code MT NB NC ND NH NJ NM NV NY OH OK OR PA RI SC SD TN TX UT VA VT WA WI WV WY sname Montana Nebraska North Carolina North Dakota New Hampshire New Jersey New Mexico Nevada New York Ohio Oklahoma Oregon Pennsylvania Rhode Island South Carolina South Dakota Tennessee Texas Utah Virginia Vermont Washington Wisconsin West Virginia Wyoming

A-14

Demonstration Database and Application

The Demonstration Application

The Demonstration Application
The following pages contain the form specifications, INFORMIX-4GL source code modules, and help message source file for the demo4.4ge demonstration application. The application is not complete, and some of the functions called by the menus are merely ‘‘dead ends.’’
File Name custform.per orderform.per state_list.per stock_sel.per d4_globals.4gl d4_main.4gl d4_cust.4gl d4_orders.4gl d4_stock.4gl d4_report.4gl d4_demo.4gl helpdemo.src Description Form for displaying customer information Form for entering an order Form for displaying a list of states Form for displaying a list of stock items Module containing global definitions Module containing MAIN routine Module handling the Customer option Module handling the Orders option Module handling the Stock option Module handling the Report option Module handling hidden sample source code option Source file for help messages

custform.per
DATABASE stores SCREEN {

Customer Form Number Owner Name Company Address City Telephone } TABLES customer ATTRIBUTES f000 = customer.customer_num, NOENTRY; f001 = customer.fname; f002 = customer.lname; f003 = customer.company; f004 = customer.address1; f005 = customer.address2; f006 = customer.city; a0 = customer.state, UPSHIFT; f007 = customer.zipcode; f008 = customer.phone, PICTURE = "###-###-#### XXXXX"; :[f000 :[f001 :[f003 :[f004 [f005 :[f006 :[f008 ] ][f002 ] ] ] ] ] State:[a0] Zipcode:[f007 ] ]

Demonstration Database and Application

A-15

The Demonstration Application

orderform.per
DATABASE stores SCREEN { -----------------------------------------------------------------------------ORDER FORM -----------------------------------------------------------------------------Customer Number:[f000 ] Contact Name:[f001 ][f002 ] Company Name:[f003 ] Address:[f004 ][f005 ] City:[f006 ] State:[a0] Zip Code:[f007 ] Telephone:[f008 ] -----------------------------------------------------------------------------Order No:[f009 ] Order Date:[f010 ] PO Number:[f011 ] Shipping Instructions:[f012 ] -----------------------------------------------------------------------------Item No. Stock No. Code Description Quantity Price Total [f013 ] [f014 ] [a1 ] [f015 ] [f016 ] [f017 ] [f018 ] [f013 ] [f014 ] [a1 ] [f015 ] [f016 ] [f017 ] [f018 ] [f013 ] [f014 ] [a1 ] [f015 ] [f016 ] [f017 ] [f018 ] [f013 ] [f014 ] [a1 ] [f015 ] [f016 ] [f017 ] [f018 ] Running Total including Tax and Shipping Charges:[f019 ] ============================================================================== } TABLES customer orders items stock ATTRIBUTES f000 = customer.customer_num; f001 = customer.fname; f002 = customer.lname; f003 = customer.company; f004 = customer.address1; f005 = customer.address2; f006 = customer.city; a0 = customer.state, UPSHIFT; f007 = customer.zipcode; f008 = customer.phone, PICTURE = "###-###-#### XXXXX"; f009 f010 f011 f012 f013 f014 a1 = f015 f016 f017 f018 f019 = = = = orders.order_num; orders.order_date, DEFAULT = TODAY; orders.po_num; orders.ship_instruct;

= items.item_num, NOENTRY; = items.stock_num; items.manu_code, UPSHIFT; = stock.description, NOENTRY; = items.quantity; = stock.unit_price, NOENTRY; = items.total_price, NOENTRY; = formonly.t_price TYPE MONEY;

INSTRUCTIONS SCREEN RECORD s_items[4](items.item_num, items.stock_num, items.manu_code, stock.description, items.quantity, stock.unit_price, items.total_price)

A-16

Demonstration Database and Application

The Demonstration Application

state_list.per
DATABASE stores SCREEN { State Selection [a0] [a0] [a0] [a0] [a0] [a0] [a0] } [f000 [f000 [f000 [f000 [f000 [f000 [f000 ] ] ] ] ] ] ]

TABLES state ATTRIBUTES a0 = state.code; f000 = state.sname; INSTRUCTIONS DELIMITERS " " SCREEN RECORD s_state[7](state.*)

stock_sel.per
DATABASE stores SCREEN { [f018][f019][f020 [f018][f019][f020 [f018][f019][f020 } TABLES stock ATTRIBUTES f018 = FORMONLY.stock_num; f019 = FORMONLY.manu_code; f020 = FORMONLY.manu_name; f021 = FORMONLY.description; f022 = FORMONLY.unit_price; f023 = FORMONLY.unit_descr; INSTRUCTIONS DELIMITERS " " SCREEN RECORD s_stock[3] (FORMONLY.stock_num THRU FORMONLY.unit_descr)

][f021 ][f021 ][f021

][f022 ][f022 ][f022

][f023 ][f023 ][f023

] ] ]

Demonstration Database and Application

A-17

The Demonstration Application

d4_globals.4gl
DATABASE stores GLOBALS DEFINE p_customer RECORD LIKE customer.*, p_orders RECORD order_num LIKE orders.order_num, order_date LIKE orders.order_date, po_num LIKE orders.po_num, ship_instruct LIKE orders.ship_instruct END RECORD, p_items ARRAY[10] OF RECORD item_num LIKE items.item_num, stock_num LIKE items.stock_num, manu_code LIKE items.manu_code, description LIKE stock.description, quantity LIKE items.quantity, unit_price LIKE stock.unit_price, total_price LIKE items.total_price END RECORD, p_stock ARRAY[30] OF RECORD stock_num LIKE stock.stock_num, manu_code LIKE manufact.manu_code, manu_name LIKE manufact.manu_name, description LIKE stock.description, unit_price LIKE stock.unit_price, unit_descr LIKE stock.unit_descr END RECORD, p_state ARRAY[50] OF RECORD LIKE state.*, state_cnt, stock_cnt INTEGER, print_option CHAR(1) END GLOBALS

A-18

Demonstration Database and Application

The Demonstration Application

d4_main.4gl
GLOBALS "d4_globals.4gl"

MAIN DEFER INTERRUPT OPTIONS HELP FILE "helpdemo" LET print_option = "s" CALL get_states() CALL get_stocks() CALL ring_menu() MENU "MAIN" COMMAND "Customer" "Enter and maintain customer data" HELP 101 CALL customer() CALL ring_menu() COMMAND "Orders" "Enter and maintain orders" HELP 102 CALL orders() CALL ring_menu() COMMAND "Stock" "Enter and maintain stock list" HELP 103 CALL stock() CALL ring_menu() COMMAND "Reports" "Print reports and mailing labels" HELP 104 CALL reports() CALL ring_menu() COMMAND key("!") CALL bang() CALL ring_menu() NEXT OPTION "Customer" COMMAND key("X") CALL demo() CALL ring_menu() NEXT OPTION "Customer" COMMAND "Exit" "Exit program and return to operating system" HELP 105 CLEAR SCREEN EXIT PROGRAM END MENU END MAIN

FUNCTION bang() DEFINE cmd CHAR(80), x CHAR(1) CALL clear_menu() LET x = "!" WHILE x = "!" PROMPT "!" FOR cmd RUN cmd PROMPT "Type RETURN to continue." FOR CHAR x END WHILE END FUNCTION

FUNCTION mess(str, mrow) DEFINE str CHAR(80),

Demonstration Database and Application

A-19

The Demonstration Application

mrow SMALLINT DISPLAY " ", str CLIPPED AT mrow,1 SLEEP 3 DISPLAY "" AT mrow,1 END FUNCTION

FUNCTION ring_menu() DISPLAY "----------------------------------------- ", "Type Control-W for MENU HELP -------" AT 4,2 ATTRIBUTE(MAGENTA) END FUNCTION

FUNCTION clear_menu() DISPLAY "" AT 1,1 DISPLAY "" AT 2,1 END FUNCTION

FUNCTION get_states() DECLARE c_state CURSOR FOR SELECT * FROM state ORDER BY sname LET state_cnt = 1 FOREACH c_state INTO p_state[state_cnt].* LET state_cnt = state_cnt + 1 IF state_cnt > 50 THEN EXIT FOREACH END IF END FOREACH LET state_cnt = state_cnt - 1 END FUNCTION

FUNCTION get_stocks() DECLARE stock_list CURSOR FOR SELECT stock_num, manufact.manu_code, manu_name, description, unit_price, unit_descr FROM stock, manufact WHERE stock.manu_code = manufact.manu_code ORDER BY stock_num LET stock_cnt = 1 FOREACH stock_list INTO p_stock[stock_cnt].* LET stock_cnt = stock_cnt + 1 IF stock_cnt > 30 THEN EXIT FOREACH END IF END FOREACH LET stock_cnt = stock_cnt - 1 END FUNCTION

A-20

Demonstration Database and Application

The Demonstration Application

d4_cust.4gl
GLOBALS "d4_globals.4gl" FUNCTION customer() OPTIONS FORM LINE 7 OPEN FORM customer FROM "custform" DISPLAY FORM customer ATTRIBUTE(MAGENTA) CALL ring_menu() CALL fgl_drawbox(3,30,3,43) CALL fgl_drawbox(3,61,8,7) CALL fgl_drawbox(11,61,8,7) LET p_customer.customer_num = NULL MENU "CUSTOMER" COMMAND "One-add" "Add a new customer to the database" HELP 201 CALL add_customer(FALSE) COMMAND "Many-add" "Add several new customer to database" HELP 202 CALL add_customer(TRUE) COMMAND "Find-cust" "Look up specific customer" HELP 203 CALL query_customer(23) IF p_customer.customer_num IS NOT NULL THEN NEXT OPTION "Update-cust" END IF COMMAND "Update-cust" "Modify current customer information" HELP 204 CALL update_customer() NEXT OPTION "Find-cust" COMMAND "Delete-cust" "Remove a customer from database" HELP 205 CALL delete_customer() NEXT OPTION "Find-cust" COMMAND "Exit" "Return to MAIN Menu" HELP 206 CLEAR SCREEN EXIT MENU END MENU OPTIONS FORM LINE 3 END FUNCTION

FUNCTION add_customer(repeat) DEFINE repeat INTEGER CALL clear_menu() MESSAGE "Press F1 or CTRL-F for field help; ", "F2 or CTRL-Z to return to menu" IF repeat THEN WHILE input_cust() ERROR "Customer data entered" ATTRIBUTE (GREEN) END WHILE CALL mess("Multiple insert completed - current screen values ignored", 23) ELSE IF input_cust() THEN ERROR "Customer data entered" ATTRIBUTE (GREEN) ELSE CLEAR FORM LET p_customer.customer_num = NULL ERROR "Customer addition aborted" ATTRIBUTE (RED, REVERSE) END IF END IF END FUNCTION FUNCTION input_cust()

Demonstration Database and Application

A-21

The Demonstration Application

DISPLAY "Press ESC to enter new customer data" AT 1,1 INPUT BY NAME p_customer.* AFTER FIELD state CALL statehelp() DISPLAY "Press ESC to enter new customer data", "" AT 1,1 ON KEY (F1, CONTROL-F) CALL customer_help() ON KEY (F2, CONTROL-Z) LET int_flag = TRUE EXIT INPUT END INPUT IF int_flag THEN LET int_flag = FALSE RETURN(FALSE) END IF LET p_customer.customer_num = 0 INSERT INTO customer VALUES (p_customer.*) LET p_customer.customer_num = SQLCA.SQLERRD[2] DISPLAY BY NAME p_customer.customer_num ATTRIBUTE(MAGENTA) RETURN(TRUE) END FUNCTION

FUNCTION query_customer(mrow) DEFINE where_part CHAR(200), query_text CHAR(250), answer CHAR(1), mrow, chosen, exist SMALLINT CLEAR FORM CALL clear_menu() MESSAGE "Enter criteria for selection" CONSTRUCT where_part ON customer.* FROM customer.* MESSAGE "" IF int_flag THEN LET int_flag = FALSE CLEAR FORM ERROR "Customer query aborted" ATTRIBUTE(RED, REVERSE) LET p_customer.customer_num = NULL RETURN (p_customer.customer_num) END IF LET query_text = "select * from customer where ", where_part CLIPPED, " order by lname" PREPARE statement_1 FROM query_text DECLARE customer_set SCROLL CURSOR FOR statement_1

A-22

Demonstration Database and Application

The Demonstration Application

OPEN customer_set FETCH FIRST customer_set INTO p_customer.* IF status = NOTFOUND THEN LET exist = FALSE ELSE LET exist = TRUE DISPLAY BY NAME p_customer.* MENU "BROWSE" COMMAND "Next" "View the next customer in the list" FETCH NEXT customer_set INTO p_customer.* IF status = NOTFOUND THEN ERROR "No more customers in this direction" ATTRIBUTE(RED, REVERSE) FETCH LAST customer_set INTO p_customer.* END IF DISPLAY BY NAME p_customer.* ATTRIBUTE(CYAN) COMMAND "Previous" "View the previous customer in the list" FETCH PREVIOUS customer_set INTO p_customer.* IF status = NOTFOUND THEN ERROR "No more customers in this direction" ATTRIBUTE(RED, REVERSE) FETCH FIRST customer_set INTO p_customer.* END IF DISPLAY BY NAME p_customer.* ATTRIBUTE(CYAN) COMMAND "First" "View the first customer in the list" FETCH FIRST customer_set INTO p_customer.* DISPLAY BY NAME p_customer.* ATTRIBUTE(CYAN) COMMAND "Last" "View the last customer in the list" FETCH LAST customer_set INTO p_customer.* DISPLAY BY NAME p_customer.* ATTRIBUTE(CYAN) COMMAND "Select" "Exit BROWSE selecting the current customer" LET chosen = TRUE EXIT MENU COMMAND "Quit" "Quit BROWSE without selecting a customer" LET chosen = FALSE EXIT MENU END MENU END IF CLOSE customer_set IF NOT exist THEN CLEAR FORM CALL mess("No customer satisfies query", mrow) LET p_customer.customer_num = NULL RETURN (FALSE) END IF IF NOT chosen THEN CLEAR FORM LET p_customer.customer_num = NULL CALL mess("No selection made", mrow) RETURN (FALSE) END IF RETURN (TRUE) END FUNCTION

Demonstration Database and Application

A-23

The Demonstration Application

FUNCTION update_customer() CALL clear_menu() IF p_customer.customer_num IS NULL THEN CALL mess("No customer has been selected; use the Find-cust option",23) RETURN END IF MESSAGE "Press F1 or CTRL-F for field-level help" DISPLAY "Press ESC to update customer data; DEL to abort" AT 1,1 INPUT BY NAME p_customer.* WITHOUT DEFAULTS AFTER FIELD state CALL statehelp() DISPLAY "Press ESC to update customer data; DEL to abort", "" AT 1,1 ON KEY (F1, CONTROL-F) CALL customer_help() END INPUT IF NOT int_flag THEN UPDATE customer SET customer.* = p_customer.* WHERE customer_num = p_customer.customer_num CALL mess("Customer data modified", 23) ELSE LET int_flag = FALSE SELECT * INTO p_customer.* FROM customer WHERE customer_num = p_customer.customer_num DISPLAY BY NAME p_customer.* ERROR "Customer update aborted" ATTRIBUTE (RED, REVERSE) END IF END FUNCTION

FUNCTION delete_customer() DEFINE answer CHAR(1), num_orders INTEGER CALL clear_menu() IF p_customer.customer_num IS NULL THEN ERROR "No customer has been selected; use the Find-customer option" ATTRIBUTE (RED, REVERSE) RETURN END IF SELECT COUNT(*) INTO num_orders FROM orders WHERE customer_num = p_customer.customer_num IF num_orders THEN ERROR "This customer has active orders and can not be removed" ATTRIBUTE (RED, REVERSE) RETURN END IF PROMPT " Are you sure you want to delete this customer row? " FOR CHAR answer IF answer MATCHES "[yY]" THEN DELETE FROM customer WHERE customer_num = p_customer.customer_num CLEAR FORM CALL mess("Customer entry deleted", 23) LET p_customer.customer_num = NULL ELSE ERROR "Deletion aborted" ATTRIBUTE (RED, REVERSE) END IF END FUNCTION

A-24

Demonstration Database and Application

The Demonstration Application

FUNCTION customer_help() CASE WHEN infield(customer_num) CALL showhelp(1001) WHEN infield(fname) CALL showhelp(1002) WHEN infield(lname) CALL showhelp(1003) WHEN infield(company) CALL showhelp(1004) WHEN infield(address1) CALL showhelp(1005) WHEN infield(address2) CALL showhelp(1006) WHEN infield(city) CALL showhelp(1007) WHEN infield(state) CALL showhelp(1008) WHEN infield(zipcode) CALL showhelp(1009) WHEN infield(phone) CALL showhelp(1010) END CASE END FUNCTION

FUNCTION statehelp() DEFINE idx INTEGER SELECT COUNT(*) INTO idx FROM state WHERE code = p_customer.state IF idx = 1 THEN RETURN END IF DISPLAY "Move cursor using F3, F4, and arrow keys; press ESC to select state" AT 1,1 OPEN WINDOW w_state AT 8,37 WITH FORM "state_list" ATTRIBUTE (BORDER, RED, FORM LINE 2) CALL set_count(state_cnt) DISPLAY ARRAY p_state TO s_state.* LET idx = arr_curr() CLOSE WINDOW w_state LET p_customer.state = p_state[idx].code DISPLAY BY NAME p_customer.state ATTRIBUTE (MAGENTA) RETURN END FUNCTION

Demonstration Database and Application

A-25

The Demonstration Application

d4_orders.4gl
GLOBALS "d4_globals.4gl" FUNCTION orders() OPEN FORM order_form FROM "orderform" DISPLAY FORM order_form ATTRIBUTE(MAGENTA) MENU "ORDERS" COMMAND "Add-order" "Enter new order to database and print invoice" HELP 301 CALL add_order() COMMAND "Update-order" "Enter shipping or payment data" HELP 302 CALL update_order() COMMAND "Find-order" "Look up and display orders" HELP 303 CALL get_order() COMMAND "Delete-order" "Remove an order from the database" HELP 304 CALL delete_order() COMMAND "Exit" "Return to MAIN Menu" HELP 305 CLEAR SCREEN EXIT MENU END MENU END FUNCTION FUNCTION add_order() DEFINE pa_curr, s_curr, num_stocks INTEGER, file_name CHAR(20), query_stat INTEGER CALL clear_menu() LET query_stat = query_customer(2) IF query_stat IS NULL THEN RETURN END IF IF NOT query_stat THEN OPEN WINDOW cust_w AT 3,5 WITH 19 ROWS, 72 COLUMNS ATTRIBUTE(BORDER, YELLOW) OPEN FORM o_cust FROM "custform" DISPLAY FORM o_cust ATTRIBUTE(MAGENTA) CALL fgl_drawbox(3,61,4,7) CALL fgl_drawbox(11,61,4,7) CALL add_customer(FALSE) CLOSE FORM o_cust CLOSE WINDOW cust_w IF p_customer.customer_num IS NULL THEN RETURN ELSE DISPLAY by name p_customer.* END IF END IF MESSAGE "Enter the order date, PO number and shipping instructions." INPUT BY NAME p_orders.order_date, p_orders.po_num, p_orders.ship_instruct IF int_flag THEN LET int_flag = FALSE CLEAR FORM ERROR "Order input aborted" ATTRIBUTE (RED, REVERSE) RETURN END IF INPUT ARRAY p_items FROM s_items.* HELP 311

A-26

Demonstration Database and Application

The Demonstration Application

BEFORE FIELD stock_num MESSAGE "Press ESC to write order" DISPLAY "Enter a stock number or press CTRL-B to scan stock list" AT 1,1 BEFORE FIELD manu_code MESSAGE "Enter the code for a manufacturer" BEFORE FIELD quantity DISPLAY "" AT 1,1 MESSAGE "Enter the item quantity" ON KEY (CONTROL-B) IF INFIELD(stock_num) OR INFIELD(manu_code) THEN LET pa_curr = arr_curr() LET s_curr = scr_line() CALL get_stock() RETURNING p_items[pa_curr].stock_num, p_items[pa_curr].manu_code, p_items[pa_curr].description, p_items[pa_curr].unit_price DISPLAY p_items[pa_curr].stock_num TO s_items[s_curr].stock_num DISPLAY p_items[pa_curr].manu_code TO s_items[s_curr].manu_code DISPLAY p_items[pa_curr].description TO s_items[s_curr].description DISPLAY p_items[pa_curr].unit_price TO s_items[s_curr].unit_price NEXT FIELD quantity END IF AFTER FIELD stock_num, manu_code LET pa_curr = arr_curr() IF p_items[pa_curr].stock_num IS NOT NULL AND p_items[pa_curr].manu_code IS NOT NULL THEN CALL get_item() END IF AFTER FIELD quantity MESSAGE "" LET pa_curr = arr_curr() IF p_items[pa_curr].unit_price IS NOT NULL AND p_items[pa_curr].quantity IS NOT NULL THEN CALL item_total() ELSE ERROR "A valid stock code, manufacturer, and quantity must all be entered" ATTRIBUTE (RED, REVERSE) NEXT FIELD stock_num END IF AFTER INSERT, DELETE CALL renum_items() CALL order_total() AFTER ROW CALL order_total() END INPUT IF int_flag THEN LET int_flag = FALSE CLEAR FORM ERROR "Order input aborted" ATTRIBUTE (RED, REVERSE) RETURN END IF

Demonstration Database and Application

A-27

The Demonstration Application

WHENEVER ERROR CONTINUE BEGIN WORK INSERT INTO orders (order_num, order_date, customer_num, ship_instruct, po_num) VALUES (0, p_orders.order_date, p_customer.customer_num, p_orders.ship_instruct, p_orders.po_num) IF status < 0 THEN ROLLBACK WORK ERROR "Unable to complete update of orders table" ATTRIBUTE(RED, REVERSE, BLINK) RETURN END IF LET p_orders.order_num = SQLCA.SQLERRD[2] DISPLAY BY NAME p_orders.order_num IF NOT insert_items() THEN ROLLBACK WORK ERROR "Unable to insert items" ATTRIBUTE(RED, REVERSE, BLINK) RETURN END IF COMMIT WORK WHENEVER ERROR STOP CALL mess("Order added", 23) LET file_name = "inv", p_orders.order_num USING "<<<<&",".out" CALL invoice(file_name) CLEAR FORM END FUNCTION

FUNCTION update_order() ERROR "This option has not been implemented" ATTRIBUTE (RED) END FUNCTION

FUNCTION delete_order() ERROR "This option has not been implemented" ATTRIBUTE (RED) END FUNCTION

FUNCTION order_total() DEFINE order_total MONEY(8), i INTEGER LET order_total = 0.00 FOR i = 1 TO ARR_COUNT() IF p_items[i].total_price IS NOT NULL THEN LET order_total = order_total + p_items[i].total_price END IF END FOR LET order_total = 1.1 * order_total DISPLAY order_total TO t_price ATTRIBUTE(GREEN) END FUNCTION

A-28

Demonstration Database and Application

The Demonstration Application

FUNCTION item_total() DEFINE pa_curr, sc_curr INTEGER LET pa_curr = arr_curr() LET sc_curr = scr_line() LET p_items[pa_curr].total_price = p_items[pa_curr].quantity * p_items[pa_curr].unit_price DISPLAY p_items[pa_curr].total_price TO s_items[sc_curr].total_price END FUNCTION

FUNCTION renum_items() DEFINE pa_curr, pa_total, sc_curr, sc_total, k INTEGER pa_curr = arr_curr() pa_total = arr_count() sc_curr = scr_line() sc_total = 4 k = pa_curr TO pa_total LET p_items[k].item_num = k IF sc_curr <= sc_total THEN DISPLAY k TO s_items[sc_curr].item_num LET sc_curr = sc_curr + 1 END IF END FOR END FUNCTION LET LET LET LET FOR

FUNCTION insert_items() DEFINE idx INTEGER FOR idx = 1 TO arr_count() IF p_items[idx].quantity != 0 THEN INSERT INTO items VALUES (p_items[idx].item_num, p_orders.order_num, p_items[idx].stock_num, p_items[idx].manu_code, p_items[idx].quantity, p_items[idx].total_price) IF status < 0 THEN RETURN (FALSE) END IF END IF END FOR RETURN (TRUE) END FUNCTION

FUNCTION get_stock() DEFINE idx integer OPEN WINDOW stock_w AT 7, 3 WITH FORM "stock_sel" ATTRIBUTE(BORDER, YELLOW) CALL set_count(stock_cnt) DISPLAY "Use cursor using F3, F4, and arrow keys; press ESC to select a stock item" AT 1,1 DISPLAY ARRAY p_stock TO s_stock.* LET idx = arr_curr() CLOSE WINDOW stock_w RETURN p_stock[idx].stock_num, p_stock[idx].manu_code, p_stock[idx].description, p_stock[idx].unit_price END FUNCTION

Demonstration Database and Application

A-29

The Demonstration Application

FUNCTION get_order() DEFINE idx, exist, chosen INTEGER, answer CHAR(1) CALL clear_menu() CLEAR FORM IF NOT query_customer(2) THEN RETURN END IF DECLARE order_list CURSOR FOR SELECT order_num, order_date, po_num, ship_instruct FROM orders WHERE customer_num = p_customer.customer_num LET exist = FALSE LET chosen = FALSE FOREACH order_list INTO p_orders.* LET exist = TRUE CLEAR orders.* FOR idx = 1 TO 4 CLEAR s_items[idx].* END FOR DISPLAY p_orders.* TO orders.* DECLARE item_list CURSOR FOR SELECT item_num, items.stock_num, items.manu_code, description, quantity, unit_price, total_price FROM items, stock WHERE order_num = p_orders.order_num AND items.stock_num = stock.stock_num AND items.manu_code = stock.manu_code ORDER BY item_num LET idx = 1 FOREACH item_list INTO p_items[idx].* LET idx = idx + 1 IF idx > 10 THEN ERROR "More than 10 items; only 10 items displayed" ATTRIBUTE (RED, REVERSE) EXIT FOREACH END IF END FOREACH CALL set_count(idx - 1) CALL order_total() MESSAGE "Press ESC when you finish viewing the items" DISPLAY ARRAY p_items TO s_items.* ATTRIBUTE(CYAN) MESSAGE "" IF int_flag THEN LET int_flag = FALSE EXIT FOREACH END IF PROMPT " Enter ’y’ to select this order ", "or RETURN to view next order: " FOR CHAR answer IF answer MATCHES "[yY]" THEN LET chosen = TRUE EXIT FOREACH END IF END FOREACH IF NOT exist THEN ERROR "No orders found for this customer" ATTRIBUTE (RED) ELSE IF NOT chosen THEN CLEAR FORM ERROR "No order selected for this customer" ATTRIBUTE (RED) END IF

A-30

Demonstration Database and Application

The Demonstration Application

END IF END FUNCTION

FUNCTION get_item() DEFINE pa_curr, sc_curr INTEGER LET pa_curr = arr_curr() LET sc_curr = scr_line() SELECT description, unit_price INTO p_items[pa_curr].description, p_items[pa_curr].unit_price FROM stock WHERE stock.stock_num = p_items[pa_curr].stock_num AND stock.manu_code = p_items[pa_curr].manu_code IF status THEN LET p_items[pa_curr].description = NULL LET p_items[pa_curr].unit_price = NULL END IF DISPLAY p_items[pa_curr].description, p_items[pa_curr].unit_price TO s_items[sc_curr].description, s_items[sc_curr].unit_price IF p_items[pa_curr].quantity IS NOT NULL THEN CALL item_total() END IF END FUNCTION

FUNCTION invoice(file_name) DEFINE x_invoice RECORD order_num order_date ship_instruct backlog po_num ship_date ship_weight ship_charge item_num stock_num manu_code quantity total_price description unit_price unit unit_descr manu_name END RECORD, file_name CHAR(20), msg CHAR(40)

LIKE LIKE LIKE LIKE LIKE LIKE LIKE LIKE LIKE LIKE LIKE LIKE LIKE LIKE LIKE LIKE LIKE LIKE

orders.order_num, orders.order_date, orders.ship_instruct, orders.backlog, orders.po_num, orders.ship_date, orders.ship_weight, orders.ship_charge, items.item_num, items.stock_num, items.manu_code, items.quantity, items.total_price, stock.description, stock.unit_price, stock.unit, stock.unit_descr, manufact.manu_name

DECLARE invoice_data CURSOR FOR SELECT o.order_num,order_date,ship_instruct,backlog,po_num,ship_date, ship_weight,ship_charge, item_num,i.stock_num,i.manu_code,quantity,total_price, s.description,unit_price,unit,unit_descr, manu_name FROM orders o,items i,stock s,manufact m WHERE ((o.order_num=p_orders.order_num) AND (i.order_num=p_orders.order_num) AND (i.stock_num=s.stock_num AND i.manu_code=s.manu_code) AND (i.manu_code=m.manu_code)) ORDER BY 9

Demonstration Database and Application

A-31

The Demonstration Application

CASE (print_option) WHEN "f" START REPORT r_invoice TO file_name CALL clear_menu() MESSAGE "Writing invoice -- please wait" WHEN "p" START REPORT r_invoice TO PRINTER CALL clear_menu() MESSAGE "Writing invoice -- please wait" WHEN "s" START REPORT r_invoice END CASE FOREACH invoice_data INTO x_invoice.* OUTPUT TO REPORT r_invoice (p_customer.*, x_invoice.*) END FOREACH FINISH REPORT r_invoice IF print_option = "f" THEN LET msg = "Invoice written to file ", file_name CLIPPED CALL mess(msg, 23) END IF END FUNCTION

REPORT r_invoice (c, x) DEFINE c RECORD LIKE customer.*, x RECORD order_num LIKE orders.order_num, order_date LIKE orders.order_date, ship_instruct LIKE orders.ship_instruct, backlog LIKE orders.backlog, po_num LIKE orders.po_num, ship_date LIKE orders.ship_date, ship_weight LIKE orders.ship_weight, ship_charge LIKE orders.ship_charge, item_num LIKE items.item_num, stock_num LIKE items.stock_num, manu_code LIKE items.manu_code, quantity LIKE items.quantity, total_price LIKE items.total_price, description LIKE stock.description, unit_price LIKE stock.unit_price, unit LIKE stock.unit, unit_descr LIKE stock.unit_descr, manu_name LIKE manufact.manu_name END RECORD, sales_tax, calc_total MONEY(8,2) OUTPUT LEFT MARGIN 0 RIGHT MARGIN 0 TOP MARGIN 1 BOTTOM MARGIN 1 PAGE LENGTH 48

A-32

Demonstration Database and Application

The Demonstration Application

FORMAT BEFORE GROUP OF x.order_num SKIP TO TOP OF PAGE SKIP 1 LINE PRINT 10 SPACES, " W E S T C O A S T W H O L E S A L E R S , I N C ." PRINT 30 SPACES," 1400 Hanbonon Drive" PRINT 30 SPACES,"Menlo Park, CA 94025" SKIP 1 LINES PRINT "Bill To:", COLUMN 10,c.fname CLIPPED, " ", c.lname CLIPPED; PRINT COLUMN 56,"Invoice No. ",x.order_num USING "&&&&&" PRINT COLUMN 10,c.company PRINT COLUMN 10,c.address1 CLIPPED; PRINT COLUMN 56,"Invoice Date: ", x.order_date PRINT COLUMN 10,c.address2 CLIPPED; PRINT COLUMN 56,"Customer No. ", c.customer_num USING "####&" PRINT COLUMN 10,c.city CLIPPED,", ",c.state CLIPPED," ", c.zipcode CLIPPED; PRINT COLUMN 56,"PO No. ",x.po_num PRINT COLUMN 10,c.phone CLIPPED; PRINT COLUMN 56,"Backlog Status: ",x.backlog SKIP 1 LINES PRINT COLUMN 10,"Shipping Instructions: ", x.ship_instruct PRINT COLUMN 10,"Ship Date: ",x.ship_date USING "ddd. mmm dd, yyyy"; PRINT " Weight: ", x.ship_weight USING "#####&.&&" SKIP 1 LINES PRINT "----------------------------------------"; PRINT "---------------------------------------" PRINT " Stock Unit "; PRINT " Item " PRINT " # Num Man Description Qty Cost Unit "; PRINT " Unit Description Total" SKIP 1 LINES LET calc_total = 0.00 ON EVERY ROW PRINT x.item_num USING "#&"," ", x.stock_num USING "&&", " ",x.manu_code; PRINT " ",x.description," ",x.quantity USING "###&", " "; PRINT x.unit_price USING "$$$&.&&"," ",x.unit, " ",x.unit_descr," PRINT x.total_price USING "$$$$$$$&.&&" LET calc_total = calc_total + x.total_price

";

AFTER GROUP OF x.order_num SKIP 1 LINES PRINT "----------------------------------------"; PRINT "---------------------------------------" PRINT COLUMN 50, " Sub-total: ",calc_total USING "$$$$$$$&.&&" LET sales_tax = 0.065 * calc_total LET x.ship_charge = 0.035 * calc_total PRINT COLUMN 45, "Shipping Charge (3.5%): ", x.ship_charge USING "$$$$$$$&.&&" PRINT COLUMN 50, " Sales Tax (6.5%): ",sales_tax USING "$$$$$$$&.&&" PRINT COLUMN 50, " -----------" LET calc_total = calc_total + x.ship_charge + sales_tax PRINT COLUMN 50, " Total: ",calc_total USING "$$$$$$$&.&&" IF print_option = "s" THEN PAUSE "Type RETURN to continue" END IF END REPORT

Demonstration Database and Application

A-33

The Demonstration Application

d4_stock.4gl
GLOBALS "d4_globals.4gl"

FUNCTION stock() MENU "STOCK" COMMAND "Add-stock" "Add new stock items to database" HELP 401 CALL add_stock() COMMAND "Find-stock" "Look up specific stock item" HELP 402 CALL query_stock() COMMAND "Update-stock" "Modify current stock information" HELP 403 CALL update_stock() COMMAND "Delete-stock" "Remove a stock item from database" HELP 404 CALL delete_stock() COMMAND "Exit" "Return to MAIN Menu" HELP 405 CLEAR SCREEN EXIT MENU END MENU END FUNCTION

FUNCTION add_stock() ERROR "This option has not been implemented" ATTRIBUTE (RED) END FUNCTION

FUNCTION query_stock() ERROR "This option has not been implemented" ATTRIBUTE (RED) END FUNCTION

FUNCTION update_stock() ERROR "This option has not been implemented" ATTRIBUTE (RED) END FUNCTION

FUNCTION delete_stock() ERROR "This option has not been implemented" ATTRIBUTE (RED) END FUNCTION

A-34

Demonstration Database and Application

The Demonstration Application

d4_report.4gl
GLOBALS "d4_globals.4gl"

FUNCTION reports() CALL ring_menu() MENU "REPORTS" COMMAND "Labels" "Print mailing labels from customer list" HELP 501 CALL print_labels() CLEAR SCREEN CALL ring_menu() COMMAND "Accounts-receivable" "Print current unpaid orders" HELP 502 CALL print_ar() CLEAR SCREEN CALL ring_menu() COMMAND "Backlog" "Print backlogged orders" HELP 503 CALL print_backlog() CLEAR SCREEN CALL ring_menu() COMMAND "Stock-list" "Print stock available" HELP 504 CALL print_stock() CLEAR SCREEN CALL ring_menu() COMMAND "Options" "Change the report output options" HELP 505 CALL update_options() CALL ring_menu() COMMAND "Exit" "Return to MAIN Menu" HELP 506 CLEAR SCREEN EXIT MENU END MENU END FUNCTION FUNCTION print_labels() DEFINE where_part CHAR(200), query_text CHAR(250), msg CHAR(50), file_name CHAR(20) OPTIONS FORM LINE 7 OPEN FORM customer FROM "custform" DISPLAY FORM customer ATTRIBUTE(MAGENTA) CALL fgl_drawbox(3,30,3,43) CALL fgl_drawbox(3,61,8,7) CALL fgl_drawbox(11,61,8,7) CALL clear_menu() DISPLAY "CUSTOMER LABELS:" AT 1,1 MESSAGE "Use query-by-example to select customer list" CONSTRUCT BY NAME where_part ON customer.* IF int_flag THEN LET int_flag = FALSE ERROR "Label print request aborted" RETURN END IF MESSAGE "" LET query_text = "select * from customer where ", where_part CLIPPED, " order by zipcode" PREPARE label_st FROM query_text DECLARE label_list CURSOR FOR label_st CASE (print_option)

Demonstration Database and Application

A-35

The Demonstration Application

WHEN "f" PROMPT " Enter file name for labels >" FOR file_name IF file_name IS NULL THEN LET file_name = "labels.out" END IF MESSAGE "Printing mailing labels to ", file_name CLIPPED, " -- Please wait" START REPORT labels_report TO file_name WHEN "p" MESSAGE "Printing mailing labels -- Please wait" START REPORT labels_report TO PRINTER WHEN "s" START REPORT labels_report CLEAR SCREEN END CASE FOREACH label_list INTO p_customer.* OUTPUT TO REPORT labels_report (p_customer.*) IF int_flag THEN LET int_flag = FALSE EXIT FOREACH END IF END FOREACH FINISH REPORT labels_report IF int_flag THEN LET int_flag = FALSE ERROR "Label printing aborted" ATTRIBUTE (RED, REVERSE) RETURN END IF IF print_option = "f" THEN LET msg = "Labels printed to ", file_name CLIPPED CALL mess(msg, 23) END IF CLOSE FORM customer OPTIONS FORM LINE 3 END FUNCTION

REPORT labels_report (rl) DEFINE rl RECORD LIKE customer.* OUTPUT TOP MARGIN 0 BOTTOM MARGIN 0 PAGE LENGTH 6 FORMAT ON EVERY ROW SKIP TO TOP OF PAGE PRINT rl.fname CLIPPED, 1 SPACE, rl.lname PRINT rl.company PRINT rl.address1

A-36

Demonstration Database and Application

The Demonstration Application

IF rl.address2 IS NOT NULL THEN PRINT rl.address2 END IF PRINT rl.city CLIPPED, ", ", rl.state, 2 SPACES, rl.zipcode IF print_option = "s" THEN PAUSE "Type RETURN to continue" END IF END REPORT

FUNCTION print_ar() DEFINE r RECORD customer_num fname lname company order_num order_date ship_date paid_date total_price END RECORD, file_name CHAR(20), msg CHAR(50)

LIKE LIKE LIKE LIKE LIKE LIKE LIKE LIKE LIKE

customer.customer_num, customer.fname, customer.lname, customer.company, orders.order_num, orders.order_date, orders.ship_date, orders.paid_date, items.total_price

DECLARE ar_list CURSOR FOR SELECT customer.customer_num,fname,lname,company, orders.order_num,order_date,ship_date,paid_date, total_price FROM customer,orders,items WHERE customer.customer_num=orders.customer_num AND paid_date IS NULL AND orders.order_num=items.order_num ORDER BY 1,5 CALL clear_menu() CASE (print_option) WHEN "f" PROMPT " Enter file name for AR Report >" FOR file_name IF file_name IS NULL THEN LET file_name = "ar.out" END IF MESSAGE "Printing AR REPORT to ", file_name CLIPPED, " -- Please wait" START REPORT ar_report TO file_name WHEN "p" MESSAGE "Printing AR REPORT -- Please wait" START REPORT ar_report TO PRINTER WHEN "s" START REPORT ar_report CLEAR SCREEN MESSAGE "Printing AR REPORT -- Please wait" END CASE

Demonstration Database and Application

A-37

The Demonstration Application

FOREACH ar_list INTO r.* OUTPUT TO REPORT ar_report (r.*) IF int_flag THEN LET int_flag = FALSE EXIT FOREACH END IF END FOREACH FINISH REPORT ar_report IF int_flag THEN LET int_flag = FALSE ERROR "AR REPORT printing aborted" ATTRIBUTE (RED, REVERSE) RETURN END IF IF print_option = "f" THEN LET msg = "AR REPORT printed to ", file_name CLIPPED CALL mess(msg, 23) END IF END FUNCTION REPORT ar_report (r) DEFINE r RECORD customer_num fname lname company order_num order_date ship_date paid_date total_price END RECORD, name_text CHAR(80) OUTPUT PAGE LENGTH 22 LEFT MARGIN 0 FORMAT PAGE HEADER PRINT 15 SPACES,"West Coast Wholesalers, Inc." PRINT 6 SPACES, "Statement of ACCOUNTS RECEIVABLE - ", TODAY USING "mmm dd, yyyy" SKIP 1 LINES LET name_text = r.fname CLIPPED," ",r.lname CLIPPED,"/", r.company CLIPPED PRINT 29 - length(name_text)/2 SPACES, name_text SKIP 1 LINES PRINT " Order Date Order Number Ship Date Amount" PRINT "----------------------------------------------------------" BEFORE GROUP OF r.customer_num SKIP TO TOP OF PAGE AFTER GROUP OF r.order_num NEED 3 LINES PRINT " ",r.order_date,7 SPACES,r.order_num USING "###&",8 SPACES, r.ship_date," ", GROUP SUM(r.total_price) USING "$$$$,$$$,$$$.&&" AFTER GROUP OF r.customer_num PRINT 42 SPACES,"----------------" PRINT 42 SPACES,GROUP SUM(r.total_price) USING "$$$$,$$$,$$$.&&"

LIKE LIKE LIKE LIKE LIKE LIKE LIKE LIKE LIKE

customer.customer_num, customer.fname, customer.lname, customer.company, orders.order_num, orders.order_date, orders.ship_date, orders.paid_date, items.total_price

A-38

Demonstration Database and Application

The Demonstration Application

PAGE TRAILER IF print_option = "s" THEN PAUSE "Type RETURN to continue" END IF END REPORT FUNCTION update_options() DEFINE po CHAR(2) DISPLAY "Current print option:" AT 8,25 LET po = " ", print_option DISPLAY po AT 8,46 ATTRIBUTE(CYAN) MENU "REPORT OPTIONS" COMMAND "File" "Send all reports to a file" LET print_option = "f" EXIT MENU COMMAND "Printer" "Send all reports to the printer" LET print_option = "p" EXIT MENU COMMAND "Screen" "Send all reports to the terminal screen" LET print_option = "s" EXIT MENU COMMAND "Exit" EXIT MENU END MENU DISPLAY "" AT 8,1 END FUNCTION

FUNCTION print_backlog() ERROR "This option has not been implemented" ATTRIBUTE (RED) END FUNCTION

FUNCTION print_stock() ERROR "This option has not been implemented" ATTRIBUTE (RED) END FUNCTION

Demonstration Database and Application

A-39

The Demonstration Application

d4_demo.4gl
FUNCTION demo() CALL ring_menu() MENU "DEMO" COMMAND "Menus" "Source code for MAIN Menu" CALL showhelp(2001) COMMAND "Windows" "Source code for STATE CODE Window" CALL showhelp(2007) COMMAND "Forms" "Source code for new CUSTOMER data entry" CALL showhelp(2006) COMMAND "Detail-Scrolling" "Source code for scrolling of new ORDER line-items" CALL showhelp(2003) COMMAND "Scroll-Cursor" "Source code for customer record BROWSE/SCROLL" CALL showhelp(2008) COMMAND "Query_language" "Source code for new order insertion using SQL" CALL showhelp(2004) COMMAND "Construct_query" "Source code for QUERY-BY-EXAMPLE selection and reporting" CALL showhelp(2002) COMMAND "Reports" "Source code for MAILING LABEL report" CALL showhelp(2005) COMMAND "Exit" "Return to MAIN MENU" CLEAR SCREEN EXIT MENU END MENU END FUNCTION

A-40

Demonstration Database and Application

The Demonstration Application

helpdemo.src
.101 The Customer option presents you with a menu that allows you to: o o o o Add new customers to the database Locate customers in the database Update customer files Remove customers from the database

.102 The Orders option presents you with a menu that allows you to: o o o o Enter a new order and print an invoice Update an existing order Look up and display orders Remove orders from the database

.103 The Stock option presents you with a menu that allows you to: o o o o Add new items to the list of stock Look up and display stock items Modify current stock descriptions and values Remove items from the list of stock

.104 The Reports option presents you with a menu that allows you to: o o o o o Select and print mailing labels sorted by zip code Print a report of current accounts receivable Print a report of backloged orders Print a list of current stock available Change the report output options

.105 The Exit option leaves the program and returns you to the operating system. .201 The One-add option enables you to enter data on new customers to the database. You may get assistance on what input is appropriate for each field by pressing the function key F1 when the cursor is in the field. When you have entered all the data you want for a given customer, press ESC to enter the data in the database. If you want to abort a given entry and not write it to the database, press the INTERRUPT key (usually DEL or CTRL-C). .202 The Many-add option enables you to enter data on new customers to the database. You may get assistance on what input is appropriate for each field by pressing the function key F1 when the cursor is in the field. When you have entered all the data you want for a given customer, press ESC to enter the data in the database. If you want to abort a given entry and not write it to the database, press the INTERRUPT key (usually DEL or CTRL-C). After each entry, the cursor will move to the beginning of the form and await the entry of the next customer. If you have no more customers to add, press CTRL-Z to return to the CUSTOMER Menu.

Demonstration Database and Application

A-41

The Demonstration Application

.203 The Find-cust option allows you to select one or more customers and to display their data on the screen by using query-by-example input. Use the RETURN or arrow keys to move through the form. Enter the criteria you want the program to use in searching for customers. Your options include: o o o o o Literal values A range of values (separated by ":") A list of values (separated by "|") Relational operators (for example ">105") Wildcards like ? and * to match single or any number of characters

.204 The Update-cust option enables you to alter data on old customers in the database. You must first select a current customer row to deal with by using the Find-cust option. You may get assistance on what input is appropriate for each field by pressing the function key F1 when the cursor is in the field. When you have altered all the data you want for a given customer, press ESC to enter the data in the database. If you want to abort the changes and not write them to the database, press the INTERRUPT key (usually DEL or CTRL-C). .205 The Delete-cust option enables you to remove customers from the database. You must first select a current customer row to deal with by using the Find-cust option. For your protection, you will be asked to confirm that the record should be deleted. Once deleted, it cannot be restored. Customers with active orders can not be deleted. .206 The Exit option of the CUSTOMER Menu takes you back to the MAIN Menu. .301 The Add-order option enables you to add a new order for an existing customer. You must first select the desired customer using query-by-example selection criteria. You will then enter the order date, PO number, and shipping instructions. The detail line items are then entered into a scrolling display array. Up to ten items may be entered using the four line screen array. After the new order is entered, an invoice is automatically generated and displayed on the screen. .302 The Update-order option is currently not implemented. .303 The Find-order option enables you to browse through and select an existing order. You must first select the desired customer (or customers) who’s orders you wish to scan. For each customer selected, each corresponding order will be displayed on the screen for examination. You may either select an invoice, skip to the next invoice, or cancel processing.

.304 The Delete-order option is currently not implemented. .305 The Exit option of the ORDER Menu returns you to the MAIN Menu.

A-42

Demonstration Database and Application

The Demonstration Application

.311 You may enter up to ten line items into the scrolling screen array. A number of standard functions are available for manipulating the cursor in a screen array. o o o o o o F1 F2 F3 F4 ESC CTRL-B Insert new line in the screen array Remove the current line from the screen array Page down one page in the screen array Page up one page in the screen array Exit input array When in the Stock Number or Manufacturer Code fields, a window will open in the middle of the screen and display a scrolled list of all items in stock, identified by the stock number and manufacturer. Using F3, F4, and the up and down arrow keys, move the cursor to the line that identifies the desired item and hit ESC. The window will disappear and the selected information will automatically appear in the proper line. The arrow-keys, and the standard field editing keys are available

o

etc...

The item_total field will be displayed in reverse-video green for total amounts over $500. .401 The Add-stock option is currently not implemented. .402 The Find-stock option is currently not implemented. .403 The Update-stock option is currently not implemented. .404 The Delete-stock option is currently not implemented. .405 The Exit option of the STOCK Menu returns you to the MAIN Menu. .501 The Labels option enables you to create a list of mailing labels generated using a query-by-example specification. You will be prompted for the output file name. .502 The Accounts-receivable option enables you to create a report summarizing all unpaid orders in the database. You will be prompted for the output file name. .503 The Backlog option is currently not implemented. .504 The Stock-list option is currently not implemented. .505 The Options option enables you to change the destination of any report generated during the current session. The default option is to display all reports on the terminal screen. The other options are to print all reports to either the printer or an operating system file. .506 The Exit option of the REPORT Menu returns you to the MAIN Menu.

Demonstration Database and Application

A-43

The Demonstration Application

.1001 The Number field on the Customer Form contains the serial integer assigned to the customer row when the data for the customer is first entered into the database. It is a unique number for each customer. The lowest value of this field is 101. .1002 The first section following the Name label should contain the first name of the contact person at the customer’s company. .1003 The second section following the Name label should contain the last name of the contact person at the customer’s company. .1004 This field should contain the name of the customer’s company. .1005 The first line of the Address section of the form should contain the mailing address of the company. .1006 The second line of the Address section of the form should be used only when there is not sufficient room in the first line to contain the entire mailing address. .1007 The City field should contain the city name portion of the mailing the customer.

address

of

.1008 Enter the two-character code for the desired state. If no code is entered, or the entered code is not in the program’s list of valid entries, a window will appear on the screen with a scrolling list of all states and codes. Using the F3, F4, up and down arrow keys, move the cursor to the line containing the desired state. After typing ESC, the window will disappear and the selected state code will appear in the customer entry screen. .1009 Enter the five digit Zip Code in this field. .1010 Enter the telephone number of the contact person at the customer’s company. Include the Area Code and extension using the format "###-###-#### #####". .2001 The following is the INFORMIX-4GL source for the main menu. Note that only the text is specified by the MENU statement; the structure and runtime menu functions are built-in. OPTIONS HELP FILE "helpdemo" OPEN FORM menu_form FROM "ring_menu" DISPLAY FORM menu_form MENU "MAIN" COMMAND "Customer" "Enter and maintain customer data" HELP 101 CALL customer() DISPLAY FORM menu_form COMMAND "Orders" "Enter and maintain orders" HELP 102 CALL orders() DISPLAY FORM menu_form COMMAND "Stock" "Enter and maintain stock list" HELP 103 CALL stock() DISPLAY FORM menu_form

A-44

Demonstration Database and Application

The Demonstration Application

COMMAND "Reports" "Print reports and mailing labels" HELP 104 CALL reports() DISPLAY FORM menu_form COMMAND "Exit" "Exit program and return to operating system" HELP 105 CLEAR SCREEN EXIT PROGRAM END MENU .2002 The following is the INFORMIX-4GL source code for mailing-label selection and printing. The CONSTRUCT statement manages the query-by-example input and builds the corresponding SQL where-clause. CONSTRUCT BY NAME where_part ON customer.* LET query_text = "select * from customer where ", where_part CLIPPED, " order by zipcode" PREPARE mail_query FROM query_text DECLARE label_list CURSOR FOR mail_query PROMPT "Enter file name for labels >" FOR file_name MESSAGE "Printing mailing labels to ", file_name CLIPPED," -- Please wait" START REPORT labels_report TO file_name FOREACH label_list INTO p_customer.* OUTPUT TO REPORT labels_report (p_customer.*) END FOREACH FINISH REPORT labels_report See the source code option REPORT for the corresponding report routine. .2003 The following is the INFORMIX-4GL source code for order entry using scrolled input fields. Only the INPUT ARRAY statement in needed to utilize the full scrolling features. Some additional code has been added merely to customize the array processing to this application. DISPLAY "Press ESC to write order" AT 1,1 INPUT ARRAY p_items FROM s_items.* HELP 311 BEFORE FIELD stock_num MESSAGE "Enter a stock number." BEFORE FIELD manu_code MESSAGE "Enter the code for a manufacturer." AFTER FIELD stock_num, manu_code LET pa = arr_curr() LET sc = scr_line() SELECT description, unit_price INTO p_items[pa].description, p_items[pa].unit_price FROM stock WHERE stock_num = p_items[pa].stock_num AND stock_manu = p_items[pa].menu_code DISPLAY p_items[pa].description, p_items[pa].unit_price TO stock[sc].* CALL item_total() AFTER FIELD quantity CALL item_total() AFTER INSERT, DELETE, ROW CALL order_total() END INPUT See the source code option QUERY-LANGUAGE for the SQL statements that insert the order information into the database.

Demonstration Database and Application

A-45

The Demonstration Application

.2004 The following is the INFORMIX-4GL source code that uses SQL to insert the entered order information into the database. Note that the use of transactions ensures that database integrity is maintained, even if an intermediate operation fails. BEGIN WORK LET p_orders.order_num = 0 INSERT INTO orders VALUES (p_orders.*) IF status < 0 THEN ROLLBACK WORK MESSAGE "Unable to complete update of orders table" RETURN END IF LET p_orders.order_num = SQLCA.SQLERRD[2] DISPLAY BY NAME p_orders.order_num FOR i = 1 to arr_count() INSERT INTO items VALUES (p_items[counter].item_num, p_orders.order_num, p_items[counter].stock_num, p_items[counter].manu_code, p_items[counter].quantity, p_items[counter].total_price) IF status < 0 THEN ROLLBACK WORK Message "Unable to insert items" RETURN FALSE END IF END FOR COMMIT WORK .2005 The following is the INFORMIX-4GL source code that generates the mailing-label report. See the source code option CONSTRUCT for the report calling sequence. REPORT labels_report (rl) DEFINE rl RECORD LIKE customer.* OUTPUT TOP MARGIN 0 PAGE LENGTH 6 FORMAT ON EVERY ROW SKIP TO TOP OF PAGE PRINT rl.fname CLIPPED, 1 SPACE, rl.lname PRINT rl.company PRINT rl.address1 IF rl.address2 IS NOT NULL THEN PRINT rl.address2 END IF PRINT rl.city CLIPPED, ", ", rl.state, 2 SPACES, rl.zipcode END REPORT

.2006 The following is the INFORMIX-4GL source code that manages a simple form for data entry. Note the use of special key definitions during data entry. OPEN FORM cust_form FROM "customer" DISPLAY FORM cust_form MESSAGE "Press F1 or CTRL-F for field help;", "F2 or CTRL-Z to return to CUSTOMER Menu" DISPLAY "Press ESC to enter new customer data or DEL to abort entry" INPUT BY NAME p_customer.* AFTER FIELD state CALL statehelp() ON KEY (F1, CONTROL-F)

A-46

Demonstration Database and Application

The Demonstration Application

CALL customer_help() ON KEY (F2, CONTROL-Z) CLEAR FORM RETURN END INPUT .2007 The following is the INFORMIX-4GL source code that opens a window in the customer entry screen, displays the list of valid state names and codes, saves the index into the p_state array for the selected state, closes the window, and returns the index to the calling routine. OPEN WINDOW w_state AT 8,40 WITH FORM "state_list" ATTRIBUTE (BORDER, RED, FORM LINE 2) CALL set_count(state_cnt) DISPLAY ARRAY p_state TO s_state.* LET idx = arr_curr() CLOSE WINDOW w_state RETURN (idx) .2008 The following is the INFORMIX-4GL source code that allows the user to browse through the rows returned by a "scroll" cursor. DECLARE customer_set SCROLL CURSOR FOR SELECT * FROM customer ORDER BY lname OPEN customer_set FETCH FIRST customer_set INTO p_customer.* IF status = NOTFOUND THEN LET exist = FALSE ELSE LET exist = TRUE DISPLAY BY NAME p_customer.* MENU "BROWSE" COMMAND "Next" "View the next customer in the list" FETCH NEXT customer_set INTO p_customer.* IF status = NOTFOUND THEN ERROR "No more customers in this direction" FETCH LAST customer_set INTO p_customer.* END IF DISPLAY BY NAME p_customer.* COMMAND "Previous" "View the previous customer in the list" FETCH PREVIOUS customer_set INTO p_customer.* IF status = NOTFOUND THEN ERROR "No more customers in this direction" FETCH FIRST customer_set INTO p_customer.* END IF DISPLAY BY NAME p_customer.* COMMAND "First" "View the first customer in the list" FETCH FIRST customer_set INTO p_customer.* DISPLAY BY NAME p_customer.* COMMAND "Last" "View the last customer in the list"

Demonstration Database and Application

A-47

The Demonstration Application

FETCH LAST customer_set INTO p_customer.* DISPLAY BY NAME p_customer.* COMMAND "Select" "Exit BROWSE selecting the current customer" LET chosen = TRUE EXIT MENU COMMAND "Quit" "Quit BROWSE without selecting a customer" LET chosen = FALSE EXIT MENU END MENU END IF CLOSE customer_set

A-48

Demonstration Database and Application

Appendix

System Catalogs
Information about the database is maintained in the system catalogs. The system catalogs are as follows: systables syscolumns sysindexes systabauth syscolauth sysdepend syssynonyms sysusers sysviews sysconstraints syssyntable describes database tables. describes columns in tables. describes indexes on columns. identifies table-level privileges. identifies column-level privileges. describes how views depend on tables. lists synonyms for tables. identifies database-level privileges. defines views. records constraints placed on database tables. used for mapping of synonyms.

B

The following list gives a brief description of the system catalogs.

The SYSTABLES Catalog

The SYSTABLES Catalog
Column Name tabname owner dirpath tabid rowsize ncols nindexes nrows created version tabtype audpath Index Name tabname tabid Type char(18) char(8) char(64) serial smallint smallint smallint integer date integer char(1) char(64) Type unique unique Explanation name of table owner of table directory path for the table file internal table identifier row size number of columns number of indexes number of rows date created table version number table type (T = table, V = view, S = synonym) audit filename (full pathname) Columns tabname, owner tabid

The SYSCOLUMNS Catalog
Column Name colname tabid colno coltype collength Index Name column Type char(18) integer smallint smallint smallint Type unique Explanation column name table identifier column number column type column length (physical) Columns tabid, colno

B-2

System Catalogs

The SYSINDEXES Catalog

The SYSINDEXES Catalog
Column Name idxname owner tabid idxtype clustered part1 part2 part3 part4 part5 part6 part7 part8 Index Name idxtab idxname Type char(18) char(8) integer char(1) char(1) smallint smallint smallint smallint smallint smallint smallint smallint Type dupls unique Explanation index name owner of index table identifier index type (U = unique, D = dupls) clustering column number column number column number column number column number column number column number column number Columns tabid idxname, tabid

The SYSTABAUTH Catalog
Column Name grantor grantee tabid tabauth Index Name tabgtor tabgtee Type char(8) char(8) integer char(7) Type unique dupls Explanation grantor of permission grantee (receiver) of permission table identifier authorization type Columns tabid, grantor, grantee tabid, grantee

The SYSCOLAUTH Catalog
Column Name grantor grantee tabid colno colauth Type char(8) char(8) integer smallint char(2) Explanation grantor of permission grantee (receiver) of permission table identifier column number authorization type

System Catalogs

B-3

The SYSDEPEND Catalog

Index Name colgtor colgtee

Type unique dupls

Columns tabid, grantor, grantee, colno tabid, grantee

The SYSDEPEND Catalog
Column Name btabid btype dtabid dtype Index Name btabid dtabid Type integer char(1) integer char(1) Type dupls dupls Explanation tabid of base table or view base object type (table or view) tabid of dependent table dependent object type (only view now) Columns btabid dtabid

The SYSSYNONYMS Catalog
Column Name owner synonym created tabid Index Name synonym syntabid Type char(8) char(18) date integer Type unique dupls Explanation user name of owner synonym identifier date synonym created table identifier Columns owner, synonym tabid

The SYSUSERS Catalog
Column Name username usertype priority password Index Name users Type char(8) char(1) smallint char(8) Type unique Explanation user login identifier D = DBA, R = RESOURCE, C = CONNECT reserved for future use reserved for future use Columns username

B-4

System Catalogs

The SYSVIEWS Catalog

The SYSVIEWS Catalog
Column Name tabid seqno viewtext Index Name view Type integer smallint char(64) Type unique Explanation table identifier sequence number portion of SELECT statement Columns tabid, seqno

The SYSCONSTRAINTS Catalog
Column Name Type constrid serial constrname char(18) owner char(8) tabid integer constrtype char(1) idxname char(18) Index Name Type constrname unique constrtabid dupls constrid unique Explanation reserved for future use constraint identifier user name of owner table identifier reserved for future use index name Columns constrname, owner tabid constrid

The SYSSYNTABLE Catalog
Column Name Type tabid integer turboname dbname tabname owner btabid integer Index Name Type synntabid unique synnbtabid dupls Explanation table identifier used on INFORMIX-OnLine only used on INFORMIX-OnLine only used on INFORMIX-OnLine only used on INFORMIX-OnLine only tabid of base table or view Columns tabid btabid

System Catalogs

B-5

The SYSSYNTABLE Catalog

B-6

System Catalogs

Appendix

Environment Variables
INFORMIX-4GL makes the following assumptions about the user’s environment:

• The editor used is the predominant operating system
editor (usually vi).

C

• • • •

The database worked with is in the current directory. The program that sends files to the printer is lp. You use /tmp to store temporary files. The INFORMIX-4GL program and its associated files are located in /usr/informix.

Setting Environment Variables

Setting Environment Variables
You can change any of the assumptions by setting one or more of the environment variables recognized by INFORMIX-4GL. You can set environment variables at the system prompt or in your .profile (Bourne shell) or .login (C shell) file. If you set an environment variable at the system prompt, you will have to assign it again the next time you log onto the system. If you set a variable in your .profile (Bourne shell) or .login (C shell) file, UNIX will assign it automatically every time you log onto the system. If you are using the Bourne shell, enter the following two commands to set the ABCD environment variable to value:
ABCD=value export ABCD

If you are using the C shell, enter the following command to set the ABCD environment variable to value:
setenv ABCD value INFORMIX-4GL recognizes the following environment variables:

DBANSIWARN
DBANSIWARN specifies that you want to initiate Informix extension checking. Setting the DBANSIWARN environment variable before you compile a 4GL program is functionally equivalent to compiling with the -ansi flag. When Informix extensions to ANSI standard syntax are encountered in your program, warning messages are written to a .err file. At run time, the DBANSIWARN environment variable causes SQLAWARN[6] to be set to W when a non-ANSI statement is executed.

Unlike most environment variables, you do not set DBANSIWARN to a value. Simply setting it in the environment is sufficient. Set the DBANSIWARN environment as follows:

C shell:
setenv DBANSIWARN

Bourne shell:
DBANSIWARN= export DBANSIWARN

C-2

Environment Variables

DBDELIMITER

Once you have set DBANSIWARN, Informix extension checking is automatic until you logout or unset DBANSIWARN. When you want to turn off Informix extension checking, you can unset the DBANSIWARN environment variable using the following commands.

C shell:
unsetenv DBANSIWARN

Bourne shell:
unset DBANSIWARN

DBDELIMITER
DBDELIMITER specifies the field delimiter used by the dbload utility in unloaded data files. The vertical bar ( | = ASCII 124) is the default.

For example, to make plus ( + ) the field delimiter on a C shell system, enter:
setenv DBDELIMITER +

DBDATE
DBDATE specifies the format you want to use for DATE values. Through DBDATE, you can specify

• The order of the month, day, and year in a date • Whether the year should be printed with two digits (Y2) or four digits
(Y4)

• The separator between the month, day, and year
The default value for DBDATE is
MDY4/

where M represents the month, D represents the day, Y4 represents a fourdigit year, and the separator is a (/) slash (mm/dd/yyyy). Other acceptable values for the separator are a hyphen ( - ), a period ( . ), or a zero ( 0 ). (You use the zero to indicate no separator.) The slash appears if you attempt to use a value other than the hyphen, period, or zero to indicate the separator, or if you do not include a separator character in the DBDATE definition.

Environment Variables C-3

DBEDIT

The separator value must always be specified last. The number of digits specified for the year must always follow the Y. To make the date appear as mmddyy (with no separator), you would set the DBDATE environment variable for the C shell as follows:
setenv DBDATE MDY20

For the Bourne shell, you would use
DBDATE=MDY20 export DBDATE

Suppose that you wanted the date to appear in European format (dd-mm-yyyy). For the C shell, you would set the DBDATE environment variable as follows:
setenv DBDATE DMY4-

For the Bourne shell, you would use
DBDATE=DMY4export DBDATE

DBEDIT
DBEDIT names the text editor for creating program files, form specification files, and command files from within the INFORMIX-4GL Programmer’s

Environment. For most systems, the default is vi.

DBLANG
DBLANG specifies the subdirectory of $INFORMIXDIR that contains the message (.iem) files used by your program. The default is $INFORMIXDIR/msg.

C-4

Environment Variables

DBMONEY

If you want to use a message directory other than $INFORMIXDIR/msg, perform the following steps: 1. Use the mkdir command to create the appropriate subdirectory in $INFORMIXDIR. Set the user and group to informix and the access permission for this directory to 755. 2. Set the DBLANG environment variable to the new subdirectory. (Specify only the name of the subdirectory and not the full pathname of the subdirectory.) If you are using the Bourne shell, enter
DBLANG=dirname export DBLANG

If you are using the C shell, enter
setenv DBLANG dirname

3. Copy the .iem files to the message directory specified by $INFORMIXDIR/ $DBLANG. All files in the message directory should have user and group informix and 644 access permission. 4. Run your program.

DBMONEY
DBMONEY applies to MONEY values. It has the format [ front ] { . | , } [ back ]

where front is the optional symbol that precedes the MONEY value, the comma or the period is the optional symbol that separates the integral from the fractional part of the MONEY value, and back is the optional symbol that follows the MONEY value. The front and back symbols can be up to seven characters long and can contain any characters except commas or periods. The default value for DBMONEY is
$.

where the dollar sign precedes the MONEY value, and the period (.) separates the integral from the fractional part of the MONEY value. (No back symbol appears.) Suppose you wanted to represent MONEY values in deutsche marks. For the C shell, you would set the DBMONEY environment variable as follows:
setenv DBMONEY DM,

Environment Variables C-5

DBPATH

For the Bourne shell, you would use
DBMONEY=DM, export DBMONEY

where DM is the currency symbol, and the comma separates the integral from the fractional part of the MONEY value. If you have specified both symbols and you make a change to either one, you must respecify the other symbol and the value separator (comma or period). Similarly, if you change the value separator from a comma to a period, you must respecify the front symbol as well as the back symbol (if you had previously specified a back symbol).

DBPATH
DBPATH specifies a list of directories (in addition to the current directory) for INFORMIX-4GL to search for databases and associated files. If you have not selected a database, INFORMIX-4GL looks to DBPATH as well as the current

directory to determine the list of available databases. Once you have selected a database, INFORMIX-4GL looks first in the current directory and then in the parent directory of the directory containing the database (recall that each database is contained in a separate directory) for the associated forms, reports, and command files. For example, if you want INFORMIX-4GL to search for database files in Kevin’s and Zooie’s directories, as well as in your current directory, you would specify
DBPATH=/usr/Kevin:/usr/Zooie export DBPATH

Make sure you enter a colon between the directory names.

DBPRINT
DBPRINT specifies the print program for your computer. For most UNIX systems, the default program is lp.

DBTEMP
DBTEMP specifies the directory into which INFORMIX-4GL should place its

temporary files. The default is the /tmp directory.

C-6

Environment Variables

INFORMIXDIR

INFORMIXDIR
INFORMIXDIR specifies the directory containing the INFORMIX-4GL files. The default is the /usr/informix directory.

INFORMIXTERM
INFORMIXTERM specifies whether INFORMIX-4GL should use the termcap or

terminfo files to locate terminal capability information. If you do not set
INFORMIXTERM, INFORMIX-4GL uses termcap.

If you are using the Bourne shell, enter:
INFORMIXTERM=type export INFORMIXTERM

where type is termcap or terminfo. If you are using the C shell, enter:
setenv INFORMIXTERM=type

SQLEXEC
SQLEXEC is needed only if you have both INFORMIX-SE and INFORMIX-OnLine installed on your system, and you want to access INFORMIX-SE. If you have both engines installed, but you do not specify SQLEXEC, then INFORMIX-OnLine is the default engine. SQLEXEC must contain the full pathname of the database engine, which is located in the lib subdirectory of $INFORMIXDIR.

To use INFORMIX-OnLine with the Bourne shell, specify:
SQLEXEC=$INFORMIXDIR/lib/sqlturbo export SQLEXEC

To use INFORMIX-SE with the Bourne shell, specify:
set SQLEXEC=$INFORMIXDIR/lib/sqlexec export SQLEXEC

To use INFORMIX-OnLine with the C shell, specify:
setenv SQLEXEC $INFORMIXDIR/lib/sqlturbo

To use INFORMIX-SE with the C shell, specify:
setenv SQLEXEC $INFORMIXDIR/lib/sqlexec

Environment Variables C-7

SQLEXEC

C-8

Environment Variables

Appendix

Reserved Words
This appendix contains a list of Informix reserved words. Do not use these words as identifiers or as program variable or host variable names. If you use reserved words as identifiers or variables, your program (or SQL statement) may fail with an error. This list contains reserved words from all Informix products, although not all are reserved in each product. Note that, while their use is not recommended, some reserved words may not cause errors in every case. For example, words that are reserved in INFORMIX-4GL will not generate an error if used with only INFORMIX-SQL. However, if your INFORMIX-SQL application is later ported to an INFORMIX-4GL environment, any INFORMIX-4GL reserved words will cause errors. Additionally, some words only generate errors if used as host or program variables, while other words only generate errors if used as identifiers. In addition to the words on this list, you should not use C, ADA, or COBOL language keywords in your programs.

D

abort absolute accept access add after all allowing alter and ansi any array as asc ascending ascii at attribute attributes audit auto autonext average avg background before begin beginning bell between black blanks blink blue bold border bottom buffered by byte call case
D-2 Reserved Words

char character check clear clipped close cluster col color colors column columns command comment comments commit committed composites compress connect constant constraint construct continue convert count create current cursor cyan database date datetime date_type day dba debug dec decimal decimal_type declare dec_t default

defaults defer define delete delimiter delimiters desc descending describe descriptor dim dirty display displayonly distinct do dominant double down downshift drop dtime dtime_t eco-* editadd editupdate else end end-exec endif ending error escape every exclusive exec execute exists exit exitnow exits explain extend

extent extern external false fetch field file finish first fixchar float flush for foreach form format formonly found fraction free from function globals go go to goto grant green group having header headings help hold hour identified if ifdef ifndef immediate in include index

indicator infield info initialize input insert instructions int integer interrupt intersect interval into intrvl_t inverse invisible is isam isolation join joining key label last left len length let like line lineno lines load locator lock loc_t log long long_float long_integer lookup loop magenta

main margin master matches max mdy memory menu message min minus minute mod mode modify module money month name natural need new next nextfield no nocr noentry normal not not found notfound noupdate now null numeric of off on open option options or order

otherwise out outer output package page pageno param pause percent perform picture pipe positive precision prepare previous print printer prior privilege privileges program prompt public put query queryclear quit raise range read readonly real record recover red register relative remove rename repair repeatable

report required resource return returning reverse revoke right rollback rollforward row rowid rows run savepoint screen scroll second section select serial serial_type set share shift short short_float short_integer sitename size skip sleep smallfloat smallint some space spaces sql sql* sqlca sqlchar_type sqlda sqldecimal_type
Appendix D: Reserved Words 3

sqlerr sqlerror sqlfloat_type sqlint_type sqlmoney_type sqlsmfloat_type sqlsmint_type sqlwarning stability start startlog static statistics status stdv step stop string struct subtract

subtype sum synonym systables table temp text then through thru time tiny_integer to today top total trailer trailing true type

typedef undef underline union unique units unload unlock up update upshift user using validate values varchar variable vc_t verify view

wait waiting warning weekday when whenever where while white window with without wordwrap work wrap year yellow yes zerofill

D-4

Reserved Words

Appendix

INFORMIX-4GL Utility Programs
This appendix describes nine utility programs that are included with the INFORMIX-4GL software. You can invoke these utilities at the system prompt to perform any of the following tasks:

• The bcheck utility checks and restores the integrity of
your index files.

• The dbload utility allows you to load data from other
database systems or from raw data files into INFORMIX-4GL databases.

• The dbexport utility allows you to unload a database
into ASCII files.

E

• The dbimport utility allows you to create a database • • • • •
from appropriate ASCII files. The dbschema utility allows you to output the SQL statements necessary to replicate an individual table or an entire database. The dbupdate utility updates an SQL Version 1 database to an SQL Version 2 database. The mkmessage utility compiles programmer-defined help messages for INFORMIX-4GL applications. The sqlconv utility converts an INFORMIX database to an SQL-compatible database. The upscol utility enables you to establish default attributes for display fields that are linked to database columns in your screen forms. It can also establish initial default values for program variables and screen fields that you associate with columns of tables in your database.

The bcheck Utility

The bcheck Utility
For every database table, INFORMIX-4GL creates two files in the database directory. These files have names consisting of a few characters of the table name, a unique number (starting at 100), and a filename extension. The extension .dat identifes the data file, while the extension .idx identifies the index file. In the stores database, for instance, data in the customer table is stored in a file named custome100.dat, while a file named custome100.idx contains the table indexes. To identify the actual filenames that INFORMIX-4GL has assigned on your system, you can examine the stores.dbs directory, where both files reside. Should these files be damaged, you may experience symptoms ranging from sluggish performance to seemingly missing data. The bcheck utility, supplied with INFORMIX-4GL on INFORMIX-SE, can verify the integrity of both files and repair and rebuild corrupted indexes. If you have used INFORMIX-4GL only as described in your manual and have not intentionally modified these files in some other way, any damage is normally due either to power fluctuations or to hardware problems in your mass storage system. The bcheck utility compares an index file to a data file to see whether the two are consistent. If they are not, bcheck asks whether you want each damaged index to be deleted and rebuilt. For each index, bcheck prints a group of up to eight numbers. These numbers indicate the position of the key in each record. In running bcheck, you must specify the table name as it exists in the database directory (custome100, for example, instead of customer). The following example runs bcheck, with the -n option, on the customer table.
bcheck -n custome100

E-2

INFORMIX-4GL Utility Programs

The bcheck Utility

In the example on the next page of output from this command line, bcheck finds no errors.
BCHECK C-ISAM B-tree Checker version 4.00.00 Copyright (C) 1981-1989 Informix Software, Inc. Software Serial Number INF#R000000

C-ISAM File: custome100 Checking dictionary and file sizes. Index file node size = 1024 Current C_ISAM index file node size = 1024 Checking data file records. Checking indexes and key descriptions. Index 1 = unique key 0 index node(s) used -- 1 index b-tree level(s) used Index 2 = unique key (0,4,2) 1 index node(s) used -- 1 index b-tree level(s) used Index 3 = duplicates (111,5,0) 1 index node(s) used -- 1 index b-tree level(s) used Checking data record and index node free lists. 4 index node(s) used, 0 free -- 18 data record(s) used, 4 free

You can also run bcheck with the following options: -i -l -n -y -q -s Check index file only List entries in B+ trees Answer no to all questions Answer yes to all questions Suppress printing of the program banner Resize the index file node size

The bcheck command syntax is as follows:
bcheck -[i | l | y | n | q | s] filename

Unless you use the -n or -y option, bcheck is interactive, waiting for you to respond to each error that it finds. Use the -y option with caution. Do not run bcheck using the -y option if you are checking the files for the first time.

INFORMIX-4GL Utility Programs

E-3

The bcheck Utility

Here is an example of bcheck output in which bcheck finds errors. The -n option is selected, so that each question bcheck asks is automatically answered ‘‘no.’’
BCHECK C-ISAM B-tree Checker version 4.00.00 Copyright (C) 1981-1989 Informix Software, Inc. Software Serial Number INF#R000000

C-ISAM File: custome100 Checking dictionary and file sizes. Index file node size = 1024 Current C_ISAM index file node size = 1024 Checking data file records. Checking indexes and key descriptions. Index 1 = unique key 0 index node(s) used -- 1 index b-tree level(s) used ERROR: 3 bad data record(s) Delete index ? no Index 2 = unique key (0,4,2) 1 index node(s) used -- 1 index b-tree level(s) used ERROR: 3 bad data record(s) Delete index ? no Index 3 = duplicates (111,5,0) 1 index node(s) used -- 1 index b-tree level(s) used ERROR: 3 bad data record(s) Delete index ? no Checking data record and index node free lists. ERROR: 3 missing data record(s) Fix data record free list ? no 4 index node(s) used, 0 free -- 18 data record(s) used, 4 free

Since bcheck finds errors, you must delete and rebuild the corrupted indexes.

E-4

INFORMIX-4GL Utility Programs

The bcheck Utility

The -y option is used to answer ‘‘yes’’ to all questions asked by bcheck:
BCHECK C-ISAM B-tree Checker version 4.00.00 Copyright (C) 1981-1989 Informix Software, Inc. Software Serial Number INF#R000000

C-ISAM File: custome100 Checking dictionary and file sizes. Checking data file records. Checking indexes and key descriptions. Index 1 = unique key 1 index node(s) used -- 1 index b-tree level(s) used ERROR: 3 bad data record(s) Delete index ? yes Remake index ? yes Index 2 = unique key (0,4,2) 1 index node(s) used -- 1 index b-tree level(s) used ERROR: 3 bad data record(s) Delete index ? yes Remake index ? yes Index 3 = duplicates (111,5,0) 1 index node(s) used -- 1 index b-tree level(s) used ERROR: 3 bad data record(s) Delete index ? yes Remake index ? yes Checking data record and index node free lists. ERROR: 3 missing data record(s) Fix data record free list ? yes Recreate Recreate Recreate Recreate data record free list index 3 index 2 index 1

4 index node(s) used, 0 free -- 18 data record(s) used, 4 free

You can run bcheck as often as you like.

INFORMIX-4GL Utility Programs

E-5

The dbexport Utility

The dbexport Utility
Overview
Use dbexport to unload a database into ASCII files for import into another database environment.

Syntax
dbexport [ -c ] [ -q ] database [ -o directory-path | -t device -b blksize -s tapesize [ -f pathname ] ]

Explanation
dbexport -c -q database -t device -b blksize -s tapesize -f pathname is the program name. tells the program to continue even though errors occur. tells the program not to display anything on its standard output. is the name of the database to be exported. directs the output to a specified tape device. specifies the tape block size in kilobytes. specifies the capacity of one tape reel. tells the program to write data definition statements to the file pathname and not to the tape.

-o directory-path directs the output to a specified directory on disk.

Notes
1. You must have DBA privilege or log in as user informix to export a database. 2. The database is locked in exclusive mode during export. If an exclusive lock cannot be obtained, the program ends with a diagnostic message. 3. The dbexport program always creates a file of messages called dbexport.out. This file contains any error messages and warnings, and it also contains a display of the SQL data definition statements that it is generating. The same material is also written to the standard output unless you specify the -q option.

E-6

INFORMIX-4GL Utility Programs

The dbexport Utility

4. You can cancel the program with an Interrupt signal. The dbexport program asks for confirmation before terminating. 5. The dbexport program writes multiple files containing database data, either to disk or to tape. The -t option specifies that the destination is a tape drive; otherwise, dbexport writes the files to disk. When you include the -t option, you must also specify the tape device, the block size, and the volume capacity. 6. When you include the -t option, the file of data definition statements and other commands (used by the dbimport utility) are ordinarily also written to the tape. Use the -f option to instruct the program to write these to the file pathname. This allows you to inspect and modify the statements. 7. When you do not include the -t option, the destination is a disk directory with the name database.exp. This directory must not exist; the program will create it. Its group will be informix. If you include the -o directorypath option, the database.exp directory is located in the specified directory. By default, the database is placed in your current working directory. 8. When output is to disk, the file containing the data definition statements and other commands to dbimport is written to the file database.sql in the database.exp directory.

Examples
The following command exports the stores database to tape with a block size of 16 kilobytes and a tape capacity of 24,000 kilobytes. The file of data definition statements and other directions to dbimport is written to stores.imp in the /tmp directory.
dbexport -c stores -t /dev/rmt0 -b 16 -s 24000 -f /tmp/stores.imp

The following command exports the stores database to the /usr/informix/port/stores.exp directory.
dbexport -c stores -o /usr/informix/port INFORMIX-OnLine supports additional functionality. Refer to the INFORMIXOnLine Programmer’s Manual for more information.

INFORMIX-4GL Utility Programs

E-7

The dbimport Utility

The dbimport Utility
Overview
Use dbimport to create a database from ASCII files.

Syntax
dbimport [-c] [-q] database [-i directory-path |-t device -b blksize -s tapesize [-f pathname] ] [-d dbspace] [-l [ logpath | buffered] ] [-ansi]

Explanation
-c -q database -t device -b blksize -s tapesize -f pathname -d dbspace -l logpath buffered -ansi tells the program to continue even when errors occur, unless it is a fatal error. tells the program not to display anything on its standard output. is the name of the database to import. specifies input from a particular tape device. specifies the tape block size in Kbytes. specifies the capacity of one tape reel. tells the program to read data definition statements from the file pathname and not from the tape. when importing to INFORMIX-OnLine only, specifies the dbspace where the new database is to go. specifies that the imported database is to use transaction logging. when importing to the standard database engine only, specifies the pathname of the transaction log file. when importing to INFORMIX-OnLine only, specifies buffered or unbuffered logging (unbuffered is the default). tells the program to create the new database as MODE ANSI.

-i directory-path specifies the path to an input directory.

E-8

INFORMIX-4GL Utility Programs

The dbimport Utility

Notes
1. The program always creates a message file called dbimport.out in the current directory. This file contains messages and warnings related to the running of the program. The message are also written to the standard output (normally the terminal screen) unless you include the -q option. 2. You can cancel the program with an interrupt signal. You are prompted for confirmation before the program terminates. 3. The individual who runs dbimport is granted DBA privilege on the new database. 4. When importing a database that uses the standard database engine, database files are created in the current directory. 5. Use the -l option to establish transaction logging for the imported database. This option is equivalent to the WITH LOG IN clause of the CREATE DATABASE statement. A database created as MODE ANSI requires transaction logging. In this situation, you must include the -l option. 6. The dbimport utility reads multiple files containing database data from either disk or tape. Use the -t option to specify the source as tape; the default is disk. When you include the -t option, you must also specify the tape device, blocksize and volume capacity. 7. When you include the -t option, dbimport reads the data definition statements and other dbimport commands from the tape. Use the -f pathname option to instruct the program to read the database.sql file in pathname (instead of the tape) for the data definition statements and other commands. To use the -f option you must have also used it when you executed the dbexport program. 8. If you do not specify the -t option, the source of the database data is a disk directory with the name database.exp. The dbimport program looks for this directory in the current working directory, or on the path specified with the -i option. In either case, the program takes data definition and other commands from the file database.sql in the directory database.exp. (This is why the name database must be the same as was given to dbexport.)

INFORMIX-4GL Utility Programs

E-9

The dbimport Utility

Example
The following command imports the stores database from a tape with a blocksize of 16 Kbytes and capacity of 24,000 Kbytes. The file of data definition statements and other import commands was put in stores.imp in the /tmp directory when dbexport was run.
dbimport -c stores -t /dev/rmt0 -b 16 -s 24000 -f /tmp/stores.imp

The following command imports the stores database from the /usr/informix/ port/stores.exp directory using data definition and commands from the file stores.sql in that directory. The new database is created as MODE ANSI and uses logging.
dbimport -c stores -i /usr/informix/port -ansi -l /usr/work/stores.log

INFORMIX-OnLine supports additional functionality. Refer to the INFORMIXOnLine Programmer’s Manual for more information.

E-10

INFORMIX-4GL Utility Programs

The dbload Utility

The dbload Utility
The dbload utility provides a method for transferring data from ASCII files into an existing database. This program supports the easy and efficient transfer of database files created for other Informix products, or even for entirely different database management systems. The dbload utility includes the following features:

• Data from selected fields of one or more input files can be loaded into
selected columns of one or more database tables.

• Loading can begin at any line in the input file. • Loading proceeds in batches of n records (where n is an integer that you
specify).

• Both fixed- and variable-length data records can be loaded. • NULL values can be defined for any field of a record. • Constants that are not in the data records can be loaded. • Records that cannot be loaded into the database are trapped and stored
(with diagnostic information) in an error log file.

• The user can specify an error limit, and dbload stops when that limit is
reached on the number of records that cannot be entered into the database because of errors.

• If your database supports transactions, you have the option of terminating the loading process without committing any data from the batch of records that exceeded your error limit. To use dbload, you must have at least one ASCII input file of data records to enter, and at least one table to receive the data. You must then create a command file to specify instructions for reading and loading the data. Finally, you must invoke dbload by entering an appropriate command line. The following sections provide details about these procedures.

Input Files for the dbload Utility
Just as database tables store data in columns within rows, input file data must be arranged in fields within records. You must be able to specify a one-to-one correspondence between fields of the input records and columns of the new rows that dbload will insert in the database. Data files for dbload must be ‘‘flat’’ ASCII files, containing only printable characters. The records containing the data to be transferred must be separated by the NEWLINE character. Output from the UNLOAD statement of SQL, for example, can be used as an input file by dbload.
INFORMIX-4GL Utility Programs E-11

The dbload Utility

Fixed-Length and Variable-Length Records
The record length can be either fixed or variable. An input file has fixed-length records if the locations of data fields and the number of characters are the same across all records. If a file has variable-length records, every field must end with the same delimiter character (which must not occur as data within any field). This character does not need to be the same one that the DBDELIMITER environment variable specifies. Two consecutive delimiters in a variable-length record define a NULL field. For each field in a fixed-length record, you can use the dbload command file to specify a character string to store as a NULL value.

Data Type Formats
Leading blanks are allowed in data fields. A currency symbol is optional in data fields for MONEY columns. Values of type DATE must be in mm / dd / yyyy format. Data for DATETIME and INTERVAL columns must be in character form, showing only field digits and delimiters (no type or qualifiers):
yyyy - mm - dd hh : mi : ss . fff

Here yyyy represents year digits, mm the month (January = 1 or 01), dd the day of the month, hh the hour, mi the minute, ss the second, and fff the fractional part of a second.

Specifying a dbload Command File
Before you can use dbload, you must first create an ASCII command file that maps fields from one or more input files into columns of one or more tables within your database. This command file must specify two kinds of information:

• One or more FILE statements, to define data fields within the records of
the input file(s)

• One or more INSERT statements, to indicate how to place the new data
into the columns of the database table(s)
INSERT statements in dbload command files resemble INSERT statements in SQL, except that they cannot incorporate SELECT statements (since the data are not yet in any table). In effect, the most recent FILE statement replaces SELECT in defining the list of data values for a dbload INSERT statement to

enter as new rows.

E-12

INFORMIX-4GL Utility Programs

The dbload Utility

The format of a command file for dbload is indicated here:
FILE { "filename" } { DELIMITER "c" nfields | (fieldn1 start [ - end ] [: . . . ] [ NULL = "null-str1" ] , fieldn2 start [ - end ] [: . . . ] [ NULL = "null-str2" ] , . . . fieldnN start [ - end ] [: . . . ] [ NULL = "null-strN" ] ) } ; INSERT INTO tablename [ (column-list) ] [ VALUES (value-list) ] ; [ . . . ]

The command file can include multiple FILE and INSERT statements. An explanation of these terms, notes, and an example follow.

Explanation
FILE

is a required keyword. is the pathname of an input file, enclosed between a pair of quotation ( " ) marks. is a keyword that is required if filename has variable-length data records. is the field delimiter (enclosed in quotes) between fields of a variable-length data record, and before the NEWLINE character that terminates each record. is an integer, specifying the number of fields in each variable-length data record. is a name that you assign to a data field within a fixed-length record of filename. is an integer, indicating a character position within a fixedlength record. is a hyphen ( - ) and an integer, indicating (with start) a range of character positions. is a keyword to specify a NULL symbol. is a quoted string, specifying a data value for which dbload should substitute a NULL. are required keywords. identifies a table in which to store the data.

filename
DELIMITER

c

nfields fieldn start -end
NULL

null-str
INSERT INTO

tablename

INFORMIX-4GL Utility Programs

E-13

The dbload Utility

column-list
VALUES

is a list of column names within tablename, separated by commas. is an optional keyword to specify a list that can include constants and data field names. is a comma-separated list of constants and/or data field names from filename.

value-list

Notes
1. The dbload utility recognizes valid owner.table references. 2. You need UNIX read permission for filename, and you must also be granted the INSERT privilege for tablename. 3. Every statement must end with a semicolon ( ; ) symbol. 4. You cannot specify character positions or null-str symbols in a record defined with the DELIMITER option. 5. Use a colon ( : ) to separate character position or range values in each data field definition. The list of field definitions must be enclosed in parentheses and separated by commas. 6. The same character position can be repeated in the FILE specification of a field, or in different fields. (See the command file example that follows these notes.) 7. The scope of reference of a null-str is the field for which you define it, but you can define the same null-str for other fields. 8. The DELIMITER option automatically assigns the sequential names f01, f02, f03, . . . to fields in variable-length records. The value-list of an INSERT statement can reference field names assigned by the user or by dbload in the previous FILE statement. 9. If your INSERT statement omits the column-list, then the default columns are every column in tablename. If you do not specify a value-list, then the default values are those in every field of the previous FILE statement. 10. An error results if the column-list and the value-list have different numbers of elements. 11. If the column-list includes fewer columns than tablename, dbload attempts to insert NULL values in the remaining columns. If a NOT NULL restriction or UNIQUE CONSTRAINT would be violated, the insertion fails, and an error message appears. 12. Inserted data types correspond to the explicit or default column-list. If the data field width is different from its corresponding character column,
E-14 INFORMIX-4GL Utility Programs

The dbload Utility

inserted values are padded with blanks if the column is wider, or are truncated if the field is wider. 13. Enclose between braces ( { } ) any comments in filename. 14. Use the DELIMITER option to avoid truncation of long character fields. If the delimiter c (or a backslash) appears as a literal character, you must prefix it with a backslash ( \ ) in the input file. 15. If you specify DELIMITER, the same delimiter must be used throughout the input file and must appear in quotes in the FILE statement. You must remember to place the delimiter immediately before the NEWLINE character that marks the end of each record. (If you omit this delimiter, an error results whenever the last field of a record is empty.)

Examples
FILE "datafile1" (fld1 1 - 10 : 13 : 5 - 22 NULL = "str1" , fld2 10 - 21 : 28 - 32 , fld3 8 - 10 : 33 - 50 : 29 - 33 NULL = "str2" , . . . fldN 9 : 16 - 19 NULL = "string") ;

INSERT INTO tab1 (col1, col2, col9, . . . , colN) ; INSERT INTO tab2 VALUES (fld1, fld3, "kevin", . . . , fldN) ; INSERT INTO tab3 ; {no column or values list provided} {variable-length fields}

FILE "datafile.2" DELIMITER "|" 8 ;

INSERT INTO tab1 VALUES (f01, f02, "kevin", "234", . . . , f08) ; INSERT INTO tab4 ;

Note: The ellipses (. . .) in this example are typographic conventions that cannot appear in command files. Unless you use the DELIMITER option, for example, you must explicitly list every field that a FILE statement defines. Each statement in this example is described in the pages that follow.
FILE "datafile1" (fld1 1 - 10 : 13 : 5 - 22 NULL = "str1" ,

Here datafile1 is the input file, and fld1, fld2, fld3, through fldN are userassigned field names in its fixed-length data records. In this example, fld1 consists of the characters in positions 1 through 10, 13, and 5 through 22 of every datafile1 record. (Each record ends with a NEWLINE character.) Notice that the characters 5 through 10 and 13 appear twice in fld1, and characters 10, 13, and 21 appear in fld1 and fld2. In field fld1, the NULL symbol is defined as ‘‘str1.’’ A NULL value is entered whenever ‘‘str1’’ is read in fld1.
INFORMIX-4GL Utility Programs E-15

The dbload Utility

The fld2 field consists of positions 10 through 21, and 28 through 32. The fld3 field is defined as the characters in positions 8 through 10, 33 through 50, and 29 through 33. The NULL symbol for field fld3 is defined as ‘‘str2.’’ The field-definition process continues until the last field is reached. Field fldN contains characters in positions 9, and 16 through 19. The NULL value is defined as ‘‘string.’’
INSERT INTO tab1 (col1, col2, col9, . . . , colN) ;

An INSERT statement follows. Here col1, col2, col9, and so on are the actual database column names in table tab1. Since no value list is provided, dbload takes the values in the fields defined in the preceding FILE statement. It inserts the data from fld1 into col1, from fld2 into col2, from fld3 into col9, and so forth, until the value from fldN is inserted into colN. (Columns 4 through 8 are skipped, so the new rows will have NULL values there, if the columns permit NULLs.)
INSERT INTO tab2 VALUES (fld1, fld3, "kevin", . . . , fldN) ;

Since no column list is provided, dbload reads the names of all the columns in tab2 from the system catalogs. Values to load into each column are specified by field names from the previous FILE statement or as constants. Data in fld1 go into the first column, data from fld3 into the second, and the constant ‘‘kevin’’ into the third. The dbload utility continues until the value in fldN is inserted into the final column.
INSERT INTO tab3 ; {no column or values list provided}

As noted in the comment, this statement specifies no column names or data values. To create a default column-list, dbload checks the system catalogs for the names of all the columns in table tab3. The default value-list comes from the most recent FILE statement, in this case the first statement in the command file. Data from fld1 go into the first column, data from fld2 into the second, and so forth, with data from field fldN going into the Nth column. Note: This statement requires that the field list in the FILE statement have a one-toone correspondence with the columns of table tab3, as listed in the system catalogs. Unless this correspondence exists, dbload will not load the records. Instead, you will receive an error message on each record. The loading process terminates when the total number of records that cannot be inserted as new rows exceeds a limit that you can specify at the dbload command line (by using the -c option).
FILE "datafile.2" DELIMITER "|" 8 ; {variable-length fields}

E-16

INFORMIX-4GL Utility Programs

The dbload Utility

The DELIMITER clause tells dbload that file datafile.2 has variable-length fields, and that the vertical-bar character ( | = ASCII 124) separates each field. Here 8 is the number of fields in each input record. Fields are automatically assigned the names f01, f02, f03, and so on.
INSERT INTO tab1 VALUES (f01, f02, "kevin", "234", . . . , f08) ;

A value-list but no column-list is specified, so dbload reads all the column names of tab1 from the system catalogs. Here the value in field f01 goes into the first column, the f02 value into the second, the constant ‘‘kevin’’ into the third, the constant ‘‘234’’ into the fourth, and so forth, until the value in field f08 is inserted into the last column. You must reference fields in a variable-length data file with the letter f followed by a two-digit number: f01, f02, f10, and so on. Other formats like fld01 or f3 are incorrect.
INSERT INTO tab4 ;

Since no column-list or value-list is provided, dbload finds all the names of columns in table tab4 in the system catalogs. The value-list is all the fields defined in the previous FILE statement. (Notice that this is not the same FILE statement that was used with table tab3.) If these values have a one-to-one correspondence with the columns, the value from field f01 goes into the first column, the value from f02 into the second column, and so on, until the value in f08 is placed in the last column. An error results if 8 is not the number of columns in table tab4.

Specifying a dbload Command Line
After you have created a valid command file, you invoke dbload at the operating system prompt. The argument list that you include in your command line determines whether the program operates in command mode or interactive mode. If you enter the keyword dbload without any arguments, the screen displays a syntax summary for dbload usage, and control returns to the operating system.

INFORMIX-4GL Utility Programs

E-17

The dbload Utility

To use dbload to read and execute a command file, you must enter a command line that includes at least one of its required specifications. The following elements are required in a dbload command line:
dbload { -d database | -c comfile | -l logfile } . . .

dbload -d database -c comfile -l logfile

invokes the dbload utility. identifies a database to receive the new data. identifies a dbload command file. identifies a file to log any error messages.

The following sections describe both the interactive and command modes of dbload.

Running dbload Interactively
If you specify part (but not all) of the required information after the dbload keyword, the program automatically enters interactive mode and prompts you for additional specifications. Depending on what you entered at the command line, these specifications can include

• The name of the database to receive the new data. • The name of the command file to be executed. • The name of an error log file in which to store any input file records that
dbload cannot insert into the database, as well as diagnostic information.

• Whether you only want dbload to check the syntax of the FILE and
INSERT statements in your command file, without changing the database.

• How many bad input records can be encountered before dbload stops
inserting new rows.

• How many input file records to read before committing new rows to the
database, if your database supports transactions.

• Whether to discard or to commit to the database any rows that were successfully read between the last COMMIT and the first bad record that exceeds your cumulative error limit.

• How many input records to ignore before dbload begins to insert data.
(That is, how many NEWLINE characters to read before actual processing begins.) After you enter these specifications or press RETURN to accept the default values that appear in the prompts, the screen is cleared, and the dbload utility begins execution.

E-18

INFORMIX-4GL Utility Programs

The dbload Utility

Running dbload in Command Mode
If a valid dbload command line includes the required database, command file, and error log specifications, with or without any additional options, program execution begins. The complete syntax of dbload is indicated here:

Syntax
dbload -d database -c comfile -l logfile [ -e num1 ] [ -n num2 ] [ -i num3 ] [ -p ] [ -r ] [ -s [ > outfile ] ]

Explanation
dbload -d database -c comfile -l logfile -e num1 -n num2 -i num3 -p -r -s > outfile is a required keyword. is the name of a database to receive the data. is the pathname of a dbload command file. is the pathname of an error logging file. is the number of bad records that dbload will read before it terminates (where num1 is an integer). displays a message after each batch of num2 new rows are inserted (where num2 is an integer). ignores the first num3 input records (where num3 is an integer). prompts for instructions if the number of bad records exceeds num1. instructs dbload not to lock the table(s). (Otherwise, tablelevel locking occurs during loading.) instructs dbload only to check the syntax of the statements in comfile, without inserting any data. is an optional > symbol and the name of a file in which to save output from the syntax check.

Notes
1. Unless you include at least one of the first three options, dbload displays a help message and terminates. If you omit one or two of the three required options, dbload prompts you for additional specifications. 2. You can prefix comfile, logfile, or outfile with a pathname.

INFORMIX-4GL Utility Programs

E-19

The dbload Utility

3. You should run dbload with the -s or -s > outfile options before you begin loading data. These options perform a syntax check on the FILE and INSERT statements in comfile and ignore any other options except -d database and -c comfile. The screen displays comfile with any errors marked where they are found. 4. If you do not specify a value for num1, the default is 10 bad records, so the program stops loading when it reads the 11th bad record. If you set num1 at zero, dbload terminates when it reads the first bad record. 5. If your database supports transactions, dbload reads and inserts a batch of num2 records between each COMMIT. If you do not specify a value for num2, the default is 100 records. 6. The -i option instructs dbload to ignore the first num3 lines in the input file, so processing does not begin until dbload has read num3 NEWLINE characters. This option is useful, for example, if your most recent dbload session with the same command file ended after 240 lines of input. You can resume loading at line 241 by setting num3 equal to 240. It is also useful if header information in the input file precedes the data records. 7. After (num1 + 1) bad records in a database with transactions, the -p option prompts you to roll back or to commit any rows inserted since the last transaction. The default is to commit. 8. If you press the Interrupt key, dbload terminates and discards any new rows that have been inserted but not yet committed to the database (if the database has transactions). 9. The presence of indexes greatly affects the speed with which the dbload utility loads data. For best performance, drop any indexes on the tables receiving the data before you run dbload. You can create new indexes after dbload has finished.

Examples
The following example shows a dbload command line at the system prompt that uses all options (except the -s option): dbload -d stores -c cfyl -l lfyl -e 5 -n 75 -i 20 -p -r This example specifies the following parameters: -d stores -c cfyl -l lfyl is the name of the database to receive the data. is the name of the dbload command file. is the name of the error-log file.

E-20

INFORMIX-4GL Utility Programs

The dbload Utility

-e 5 -n 75

specifies that dbload will log up to five bad records. The program terminates if a 6th bad record is encountered. specifies that screen messages will indicate when successive batches of 75 rows have been inserted (or committed, in a database with transactions). tells dbload to ignore the first 20 lines of the data file. Processing begins at the 21st line. prompts you to commit or discard any uncommitted rows after six bad records. tells dbload not to lock the table(s) of the stores database that are being accessed by dbload while the new rows are being inserted. This allows other users to access the same table(s) during the dbload operation. Unless you specify the -r option, table-level locking occurs.

-i 20 -p -r

Notice that the names of the input file and the table(s) to receive the data do not appear explicitly in the command line. These names must be specified within the dbload command file, which is called cfyl in this example.

INFORMIX-4GL Utility Programs

E-21

The dbschema Utility

The dbschema Utility
You can use the dbschema utility to produce quickly an SQL command file containing the CREATE TABLE, CREATE INDEX, and CREATE VIEW statements required to replicate an entire database or a selected table. In addition, dbschema can produce all CREATE SYNONYM and GRANT statements in effect for the database or a selected table or view. You must be the DBA or have CONNECT or RESOURCE permission to the database before you can run dbschema. By default, dbschema produces all CREATE TABLE, CREATE VIEW, CREATE INDEX, CREATE SYNONYM, and GRANT statements in effect for the entire database. By including the appropriate command-line option, you can limit the output to a selected table or view, or produce synonyms and permissions for a particular user. dbschema uses the owner.object convention when it generates any CREATE TABLE, CREATE INDEX, CREATE SYNONYM, CREATE VIEW, or GRANT statements, and when it reproduces any UNIQUE CONSTRAINTs. As a result, if you use the dbschema output to create a new object (table, index, view, or synonym), the new object is owned by the owner of the original object. If you want to change the owner of the new object, you must edit the dbschema output before running it as an SQL script. The syntax for the dbschema utility follows:
dbschema [-t tabname] [-s sname] [-p pname] -d database [filename]

-t tabname

specifies the table or view for which you want dbschema to output CREATE TABLE and CREATE INDEX statements or the CREATE VIEW statement. If you specify all for tabname, dbschema outputs the SQL statements for all database tables and views. specifies the user for whom you want dbschema to output the CREATE SYNONYM statements. If you specify all for sname, dbschema outputs all CREATE SYNONYM statements. If you include the -t option, dbschema produces the CREATE SYNONYM statements only for the indicated tabname. specifies the user for whom you want dbschema to output permission statements. If you specify all for pname, dbschema outputs the GRANT statements for all users. If you include the -t option, dbschema produces the GRANT statements only for the indicated tabname. specifies the name of the database.

-s sname

-p pname

-d database
E-22

INFORMIX-4GL Utility Programs

The dbschema Utility

filename

specifies the name of the file in which to save the dbschema output. If filename is not provided, dbschema outputs to the screen.

Notes
1. The following command line produces the SQL statements necessary to replicate an entire database:
dbschema -d database

where database is the name of the database. 2. You must be the DBA or have CONNECT or RESOURCE permission to the database before you can run dbschema on it. 3. When you include the -t option, dbschema produces SQL statements only for the indicated tabname. The dbschema utility uses the tabname to filter the output. If you use the -t option with the -p and -s options, only the CREATE SYNONYM and GRANT statements for tabname are provided. 4. All objects listed in the dbschema output include the name of the owner. If you want to use the dbschema output to create a schema with different owners, you must first change the owner names in the output file. 5. All SERIAL fields included in CREATE TABLE statements output by dbschema have a starting value of one, regardless of their original starting value. 6. In the dbschema output, the AS keyword is used to indicate the grantor of a GRANT statement, as in the following example:
GRANT ALL ON "tom".customer TO "claire" AS "norma"

This statement tells you that norma issued the GRANT statement. 7. When the GRANT..AS keywords appear in your dbschema output, you may need to grant certain permissions before running the output as an SQL script. Consider the following GRANT statement:
GRANT tab-privilege ON user1.tablename TO "user2" AS "user3"

Before this statement can be run to create another schema, the following must be true:

• user3 must have CONNECT permission to the database. • user3 must have tab-privilege WITH GRANT OPTION for tablename.
8. The database must exist in your current directory or a directory cited in your DBPATH environment variable.

INFORMIX-4GL Utility Programs

E-23

The dbschema Utility

Examples
The following statement outputs the SQL statements relating to the customer table in the stores database to the file c_schema.sql.
dbschema -t customer -s alice -p dinah -d stores c_schema.sql

The output consists of the following components:

• The CREATE TABLE and CREATE INDEX statements for the customer table • All CREATE SYNONYM statements executed by the user alice on the
customer table

• All permissions granted to the user dinah on the customer table
The output from this dbschema statement follows:
{ TABLE "alice".customer row size = 134 number of columns = 10 index size = 0 } CREATE TABLE "alice".customer ( customer_num serial not null, fname char(15), lname char(15), company char(20), address1 char(20), address2 char(20), city char(15), state char(2), zipcode char(5), phone char(18) ); REVOKE ALL ON "alice".customer FROM "public"; CREATE UNIQUE INDEX "alice".c_num_ix ON "alice".customer (customer_num); CREATE INDEX "alice".zip_ix ON "alice".customer (zipcode); GRANT ALL ON "alice".customer TO "dinah" AS "alice"; CREATE SYNONYM "alice".cust FOR "alice".customer;

The next dbschema statement outputs the SQL statements for all tables in the stores database to the file s_schema.sql.
dbschema -t all -s alice -p alice -d stores s_schema.sql

The output consists of the following components:

• The CREATE TABLE, CREATE VIEW, and CREATE INDEX statements that
replicate all tables, views, and indexes in the stores database

• All CREATE SYNONYM statements executed by the user alice • All permissions granted to the user alice

E-24

INFORMIX-4GL Utility Programs

The dbupdate Utility

The dbupdate Utility
Databases created through Informix products that used an early implementation of SQL (Version 1.1 or earlier) have a different structure than databases created through products using the current implementation. The current structure includes additional system catalogs, content changes to some existing system catalogs (see Appendix B), and the introduction of NULL values. A database will have the old structure if it was created by an application using Version 2.0 (or earlier) of INFORMIX-ESQL/C, INFORMIX-ESQL/ COBOL, or INFORMIX-SQL or Version 1.0 of INFORMIX-4GL. Such a database cannot be used with current application development tools or database engines until the database is converted to the current structure. You can convert old databases to the current structure through the dbupdate utility.

Using dbupdate
To convert an old database to the new structure, execute the following command:
dbupdate [ -b | -n ] old-database-name new-database-name

The dbupdate utility creates a new database in the current directory with the name new-database-name, and copies the data from the old system catalogs to the new system catalogs, making the appropriate changes. If you do not use the -b or -n option, dbupdate converts the value of all CHAR type columns with blank data to NULL and, for each number column, asks you whether it should convert zero values to NULL values. The -b option causes dbupdate to leave blank data in CHAR columns as blanks. The -n option alters the system catalogs to define all columns as NOT NULL, and does not touch the data files. The -n option includes the -b option. In addition to these changes, dbupdate corrects a bug in the representation of negative DECIMAL values. When dbupdate finishes, you have two database directories (the new and the old) with two separate system catalogs, but the data and index files are shared (linked). To complete the update, you should remove the old database directory.

INFORMIX-4GL Utility Programs

E-25

The dbupdate Utility

No NULL Databases
You may want to avoid dealing with NULL values and their three-valued logic. You can do this if you carefully adhere to the following rules:

• When converting an old database, select the -n option of dbupdate. • When creating new tables, define all columns as NOT NULL. • In all form specification files, add the WITHOUT NULL INPUT clause in the
DATABASE section.

• In form specification files, specify all formonly fields as NOT NULL.
The last two rules mean that you must recompile all your old form specification files.

E-26

INFORMIX-4GL Utility Programs

The mkmessage Utility

The mkmessage Utility
The mkmessage utility converts ASCII source files that contain user messages into a format that 4GL programs can use in on-line displays. This section describes how to use mkmessage with help files and with customized runtime error messages.

Programmer-Defined Help Messages
When executing an INFORMIX-4GL program, the user can request help whenever the program is waiting for user input. This can occur while making a menu selection, while inputting data to a form, or while responding to a prompt. You can supply help messages that are displayed whenever the user presses the Help key (specified in the OPTIONS statement). These messages can be specific to the menu option currently highlighted, or to the INPUT, INPUT ARRAY, or PROMPT statement.

Message Source Files
INFORMIX-4GL looks for the appropriate help message in the help file that you specify in an OPTIONS statement, using the HELP FILE option. You can have several help files, but only one can be in effect at a time. The structure of the message source file is very simple:

Syntax
.num message-text ... [ ... ]

Explanation
.num message-text is a period, followed by an integer. is a line of characters and/or blanks.

Notes
1. Each line must end in a RETURN. 2. Each help message should be preceded by a line with nothing on it but a period (in the first column) and a unique integer num.
INFORMIX-4GL Utility Programs E-27

The mkmessage Utility

3. The message-text starts on the next line, and continues until the next numbered line. 4. You can use the integer num to identify the help message in your INFORMIX-4GL programs. (See the INPUT, INPUT ARRAY, MENU, and PROMPT statement descriptions in Chapter 7.) 5. All blank lines between two numbered lines are considered part of the message that belongs to the first of the two numbers. 6. Lines beginning with # are considered comment lines, and are ignored by mkmessage. 7. If the text of a message occupies more than 20 lines, INFORMIX-4GL automatically breaks the message into ‘‘pages’’ of 20 lines. You can change these default page breaks by entering CTRL-L in the first column of a line in your message file to start a new page. 8. INFORMIX-4GL handles clearing and redisplaying the screen.

Examples
For an example, see the helpdemo.src file from the demonstration application in Appendix A. (See also the section ‘‘Creating a Help File’’ in Chapter 8 of the INFORMIX-4GL User Guide.)

Creating Executable Message Files
Once you have created your message source file, you can process it for use by INFORMIX-4GL with this syntax:

Syntax
mkmessage helpfile.src helpfile.out

Explanation
helpfile.src helpfile.out is an ASCII source file of help messages. is the pathname of the executable output file.

E-28

INFORMIX-4GL Utility Programs

The mkmessage Utility

Notes
1. You can give the input and output help files any valid names and extensions in place of those shown above. 2. You can specify the output help file name in the OPTIONS statement to identify it as the current help file. 3. If you want to use help messages from the help file on a field-by-field basis in an INPUT or INPUT ARRAY statement, you must use the infield() and showhelp( ) library functions that are supplied with INFORMIX-4GL.

Examples
The example that follows illustrates the use of these functions:
OPTIONS HELP FILE "stores.hlp&